xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 5c0b3261bd16d5eb356ffc864b6eab76c2e760e5)
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  * Copyright 2022 Garrett D'Amore
34  */
35 /*
36  * Copyright 2011 cyril.galibern@opensvc.com
37  */
38 
39 /*
40  * SCSI disk target driver.
41  */
42 #include <sys/scsi/scsi.h>
43 #include <sys/dkbad.h>
44 #include <sys/dklabel.h>
45 #include <sys/dkio.h>
46 #include <sys/fdio.h>
47 #include <sys/cdio.h>
48 #include <sys/mhd.h>
49 #include <sys/vtoc.h>
50 #include <sys/dktp/fdisk.h>
51 #include <sys/kstat.h>
52 #include <sys/vtrace.h>
53 #include <sys/note.h>
54 #include <sys/thread.h>
55 #include <sys/proc.h>
56 #include <sys/efi_partition.h>
57 #include <sys/var.h>
58 #include <sys/aio_req.h>
59 #include <sys/dkioc_free_util.h>
60 
61 #ifdef __lock_lint
62 #define	_LP64
63 #define	__amd64
64 #endif
65 
66 #if (defined(__fibre))
67 /* Note: is there a leadville version of the following? */
68 #include <sys/fc4/fcal_linkapp.h>
69 #endif
70 #include <sys/taskq.h>
71 #include <sys/uuid.h>
72 #include <sys/byteorder.h>
73 #include <sys/sdt.h>
74 
75 #include "sd_xbuf.h"
76 
77 #include <sys/scsi/targets/sddef.h>
78 #include <sys/cmlb.h>
79 #include <sys/sysevent/eventdefs.h>
80 #include <sys/sysevent/dev.h>
81 
82 #include <sys/fm/protocol.h>
83 
84 /*
85  * Loadable module info.
86  */
87 #if (defined(__fibre))
88 #define	SD_MODULE_NAME	"SCSI SSA/FCAL Disk Driver"
89 #else /* !__fibre */
90 #define	SD_MODULE_NAME	"SCSI Disk Driver"
91 #endif /* !__fibre */
92 
93 /*
94  * Define the interconnect type, to allow the driver to distinguish
95  * between parallel SCSI (sd) and fibre channel (ssd) behaviors.
96  *
97  * This is really for backward compatibility. In the future, the driver
98  * should actually check the "interconnect-type" property as reported by
99  * the HBA; however at present this property is not defined by all HBAs,
100  * so we will use this #define (1) to permit the driver to run in
101  * backward-compatibility mode; and (2) to print a notification message
102  * if an FC HBA does not support the "interconnect-type" property.  The
103  * behavior of the driver will be to assume parallel SCSI behaviors unless
104  * the "interconnect-type" property is defined by the HBA **AND** has a
105  * value of either INTERCONNECT_FIBRE, INTERCONNECT_SSA, or
106  * INTERCONNECT_FABRIC, in which case the driver will assume Fibre
107  * Channel behaviors (as per the old ssd).  (Note that the
108  * INTERCONNECT_1394 and INTERCONNECT_USB types are not supported and
109  * will result in the driver assuming parallel SCSI behaviors.)
110  *
111  * (see common/sys/scsi/impl/services.h)
112  *
113  * Note: For ssd semantics, don't use INTERCONNECT_FABRIC as the default
114  * since some FC HBAs may already support that, and there is some code in
115  * the driver that already looks for it.  Using INTERCONNECT_FABRIC as the
116  * default would confuse that code, and besides things should work fine
117  * anyways if the FC HBA already reports INTERCONNECT_FABRIC for the
118  * "interconnect_type" property.
119  *
120  */
121 #if (defined(__fibre))
122 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_FIBRE
123 #else
124 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_PARALLEL
125 #endif
126 
127 /*
128  * The name of the driver, established from the module name in _init.
129  */
130 static	char *sd_label			= NULL;
131 
132 /*
133  * Driver name is unfortunately prefixed on some driver.conf properties.
134  */
135 #if (defined(__fibre))
136 #define	sd_max_xfer_size		ssd_max_xfer_size
137 #define	sd_config_list			ssd_config_list
138 static	char *sd_max_xfer_size		= "ssd_max_xfer_size";
139 static	char *sd_config_list		= "ssd-config-list";
140 #else
141 static	char *sd_max_xfer_size		= "sd_max_xfer_size";
142 static	char *sd_config_list		= "sd-config-list";
143 #endif
144 
145 /*
146  * Driver global variables
147  */
148 
149 #if (defined(__fibre))
150 /*
151  * These #defines are to avoid namespace collisions that occur because this
152  * code is currently used to compile two separate driver modules: sd and ssd.
153  * All global variables need to be treated this way (even if declared static)
154  * in order to allow the debugger to resolve the names properly.
155  * It is anticipated that in the near future the ssd module will be obsoleted,
156  * at which time this namespace issue should go away.
157  */
158 #define	sd_state			ssd_state
159 #define	sd_io_time			ssd_io_time
160 #define	sd_failfast_enable		ssd_failfast_enable
161 #define	sd_ua_retry_count		ssd_ua_retry_count
162 #define	sd_report_pfa			ssd_report_pfa
163 #define	sd_max_throttle			ssd_max_throttle
164 #define	sd_min_throttle			ssd_min_throttle
165 #define	sd_rot_delay			ssd_rot_delay
166 
167 #define	sd_retry_on_reservation_conflict	\
168 					ssd_retry_on_reservation_conflict
169 #define	sd_reinstate_resv_delay		ssd_reinstate_resv_delay
170 #define	sd_resv_conflict_name		ssd_resv_conflict_name
171 
172 #define	sd_component_mask		ssd_component_mask
173 #define	sd_level_mask			ssd_level_mask
174 #define	sd_debug_un			ssd_debug_un
175 #define	sd_error_level			ssd_error_level
176 
177 #define	sd_xbuf_active_limit		ssd_xbuf_active_limit
178 #define	sd_xbuf_reserve_limit		ssd_xbuf_reserve_limit
179 
180 #define	sd_tr				ssd_tr
181 #define	sd_reset_throttle_timeout	ssd_reset_throttle_timeout
182 #define	sd_qfull_throttle_timeout	ssd_qfull_throttle_timeout
183 #define	sd_qfull_throttle_enable	ssd_qfull_throttle_enable
184 #define	sd_check_media_time		ssd_check_media_time
185 #define	sd_wait_cmds_complete		ssd_wait_cmds_complete
186 #define	sd_log_buf			ssd_log_buf
187 #define	sd_log_mutex			ssd_log_mutex
188 
189 #define	sd_disk_table			ssd_disk_table
190 #define	sd_disk_table_size		ssd_disk_table_size
191 #define	sd_sense_mutex			ssd_sense_mutex
192 #define	sd_cdbtab			ssd_cdbtab
193 
194 #define	sd_cb_ops			ssd_cb_ops
195 #define	sd_ops				ssd_ops
196 #define	sd_additional_codes		ssd_additional_codes
197 #define	sd_tgops			ssd_tgops
198 
199 #define	sd_minor_data			ssd_minor_data
200 #define	sd_minor_data_efi		ssd_minor_data_efi
201 
202 #define	sd_tq				ssd_tq
203 #define	sd_wmr_tq			ssd_wmr_tq
204 #define	sd_taskq_name			ssd_taskq_name
205 #define	sd_wmr_taskq_name		ssd_wmr_taskq_name
206 #define	sd_taskq_minalloc		ssd_taskq_minalloc
207 #define	sd_taskq_maxalloc		ssd_taskq_maxalloc
208 
209 #define	sd_dump_format_string		ssd_dump_format_string
210 
211 #define	sd_iostart_chain		ssd_iostart_chain
212 #define	sd_iodone_chain			ssd_iodone_chain
213 
214 #define	sd_pm_idletime			ssd_pm_idletime
215 
216 #define	sd_force_pm_supported		ssd_force_pm_supported
217 
218 #define	sd_dtype_optical_bind		ssd_dtype_optical_bind
219 
220 #define	sd_ssc_init			ssd_ssc_init
221 #define	sd_ssc_send			ssd_ssc_send
222 #define	sd_ssc_fini			ssd_ssc_fini
223 #define	sd_ssc_assessment		ssd_ssc_assessment
224 #define	sd_ssc_post			ssd_ssc_post
225 #define	sd_ssc_print			ssd_ssc_print
226 #define	sd_ssc_ereport_post		ssd_ssc_ereport_post
227 #define	sd_ssc_set_info			ssd_ssc_set_info
228 #define	sd_ssc_extract_info		ssd_ssc_extract_info
229 
230 #endif
231 
232 #ifdef	SDDEBUG
233 int	sd_force_pm_supported		= 0;
234 #endif	/* SDDEBUG */
235 
236 void *sd_state				= NULL;
237 int sd_io_time				= SD_IO_TIME;
238 int sd_failfast_enable			= 1;
239 int sd_ua_retry_count			= SD_UA_RETRY_COUNT;
240 int sd_report_pfa			= 1;
241 int sd_max_throttle			= SD_MAX_THROTTLE;
242 int sd_min_throttle			= SD_MIN_THROTTLE;
243 int sd_rot_delay			= 4; /* Default 4ms Rotation delay */
244 int sd_qfull_throttle_enable		= TRUE;
245 
246 int sd_retry_on_reservation_conflict	= 1;
247 int sd_reinstate_resv_delay		= SD_REINSTATE_RESV_DELAY;
248 _NOTE(SCHEME_PROTECTS_DATA("safe sharing", sd_reinstate_resv_delay))
249 
250 static int sd_dtype_optical_bind	= -1;
251 
252 /* Note: the following is not a bug, it really is "sd_" and not "ssd_" */
253 static	char *sd_resv_conflict_name	= "sd_retry_on_reservation_conflict";
254 
255 /*
256  * Global data for debug logging. To enable debug printing, sd_component_mask
257  * and sd_level_mask should be set to the desired bit patterns as outlined in
258  * sddef.h.
259  */
260 uint_t	sd_component_mask		= 0x0;
261 uint_t	sd_level_mask			= 0x0;
262 struct	sd_lun *sd_debug_un		= NULL;
263 uint_t	sd_error_level			= SCSI_ERR_RETRYABLE;
264 
265 /* Note: these may go away in the future... */
266 static uint32_t	sd_xbuf_active_limit	= 512;
267 static uint32_t sd_xbuf_reserve_limit	= 16;
268 
269 static struct sd_resv_reclaim_request	sd_tr = { NULL, NULL, NULL, 0, 0, 0 };
270 
271 /*
272  * Timer value used to reset the throttle after it has been reduced
273  * (typically in response to TRAN_BUSY or STATUS_QFULL)
274  */
275 static int sd_reset_throttle_timeout	= SD_RESET_THROTTLE_TIMEOUT;
276 static int sd_qfull_throttle_timeout	= SD_QFULL_THROTTLE_TIMEOUT;
277 
278 /*
279  * Interval value associated with the media change scsi watch.
280  */
281 static int sd_check_media_time		= 3000000;
282 
283 /*
284  * Wait value used for in progress operations during a DDI_SUSPEND
285  */
286 static int sd_wait_cmds_complete	= SD_WAIT_CMDS_COMPLETE;
287 
288 /*
289  * Global buffer and mutex for debug logging
290  */
291 static char	sd_log_buf[1024];
292 static kmutex_t	sd_log_mutex;
293 
294 /*
295  * Structs and globals for recording attached lun information.
296  * This maintains a chain. Each node in the chain represents a SCSI controller.
297  * The structure records the number of luns attached to each target connected
298  * with the controller.
299  * For parallel scsi device only.
300  */
301 struct sd_scsi_hba_tgt_lun {
302 	struct sd_scsi_hba_tgt_lun	*next;
303 	dev_info_t			*pdip;
304 	int				nlun[NTARGETS_WIDE];
305 };
306 
307 /*
308  * Flag to indicate the lun is attached or detached
309  */
310 #define	SD_SCSI_LUN_ATTACH	0
311 #define	SD_SCSI_LUN_DETACH	1
312 
313 static kmutex_t	sd_scsi_target_lun_mutex;
314 static struct sd_scsi_hba_tgt_lun	*sd_scsi_target_lun_head = NULL;
315 
316 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
317     sd_scsi_hba_tgt_lun::next sd_scsi_hba_tgt_lun::pdip))
318 
319 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
320     sd_scsi_target_lun_head))
321 
322 /*
323  * "Smart" Probe Caching structs, globals, #defines, etc.
324  * For parallel scsi and non-self-identify device only.
325  */
326 
327 /*
328  * The following resources and routines are implemented to support
329  * "smart" probing, which caches the scsi_probe() results in an array,
330  * in order to help avoid long probe times.
331  */
332 struct sd_scsi_probe_cache {
333 	struct	sd_scsi_probe_cache	*next;
334 	dev_info_t	*pdip;
335 	int		cache[NTARGETS_WIDE];
336 };
337 
338 static kmutex_t	sd_scsi_probe_cache_mutex;
339 static struct	sd_scsi_probe_cache *sd_scsi_probe_cache_head = NULL;
340 
341 /*
342  * Really we only need protection on the head of the linked list, but
343  * better safe than sorry.
344  */
345 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
346     sd_scsi_probe_cache::next sd_scsi_probe_cache::pdip))
347 
348 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
349     sd_scsi_probe_cache_head))
350 
351 /*
352  * Power attribute table
353  */
354 static sd_power_attr_ss sd_pwr_ss = {
355 	{ "NAME=spindle-motor", "0=off", "1=on", NULL },
356 	{0, 100},
357 	{30, 0},
358 	{20000, 0}
359 };
360 
361 static sd_power_attr_pc sd_pwr_pc = {
362 	{ "NAME=spindle-motor", "0=stopped", "1=standby", "2=idle",
363 		"3=active", NULL },
364 	{0, 0, 0, 100},
365 	{90, 90, 20, 0},
366 	{15000, 15000, 1000, 0}
367 };
368 
369 /*
370  * Power level to power condition
371  */
372 static int sd_pl2pc[] = {
373 	SD_TARGET_START_VALID,
374 	SD_TARGET_STANDBY,
375 	SD_TARGET_IDLE,
376 	SD_TARGET_ACTIVE
377 };
378 
379 /*
380  * Vendor specific data name property declarations
381  */
382 
383 #if defined(__fibre) || defined(__x86)
384 
385 static sd_tunables seagate_properties = {
386 	SEAGATE_THROTTLE_VALUE,
387 	0,
388 	0,
389 	0,
390 	0,
391 	0,
392 	0,
393 	0,
394 	0
395 };
396 
397 
398 static sd_tunables fujitsu_properties = {
399 	FUJITSU_THROTTLE_VALUE,
400 	0,
401 	0,
402 	0,
403 	0,
404 	0,
405 	0,
406 	0,
407 	0
408 };
409 
410 static sd_tunables ibm_properties = {
411 	IBM_THROTTLE_VALUE,
412 	0,
413 	0,
414 	0,
415 	0,
416 	0,
417 	0,
418 	0,
419 	0
420 };
421 
422 static sd_tunables sve_properties = {
423 	SVE_THROTTLE_VALUE,
424 	0,
425 	0,
426 	SVE_BUSY_RETRIES,
427 	SVE_RESET_RETRY_COUNT,
428 	SVE_RESERVE_RELEASE_TIME,
429 	SVE_MIN_THROTTLE_VALUE,
430 	SVE_DISKSORT_DISABLED_FLAG,
431 	0
432 };
433 
434 static sd_tunables maserati_properties = {
435 	0,
436 	0,
437 	0,
438 	0,
439 	0,
440 	0,
441 	0,
442 	MASERATI_DISKSORT_DISABLED_FLAG,
443 	MASERATI_LUN_RESET_ENABLED_FLAG
444 };
445 
446 static sd_tunables pirus_properties = {
447 	PIRUS_THROTTLE_VALUE,
448 	0,
449 	PIRUS_NRR_COUNT,
450 	PIRUS_BUSY_RETRIES,
451 	PIRUS_RESET_RETRY_COUNT,
452 	0,
453 	PIRUS_MIN_THROTTLE_VALUE,
454 	PIRUS_DISKSORT_DISABLED_FLAG,
455 	PIRUS_LUN_RESET_ENABLED_FLAG
456 };
457 
458 #endif
459 
460 #if (defined(__sparc) && !defined(__fibre)) || \
461 	(defined(__x86))
462 
463 
464 static sd_tunables elite_properties = {
465 	ELITE_THROTTLE_VALUE,
466 	0,
467 	0,
468 	0,
469 	0,
470 	0,
471 	0,
472 	0,
473 	0
474 };
475 
476 static sd_tunables st31200n_properties = {
477 	ST31200N_THROTTLE_VALUE,
478 	0,
479 	0,
480 	0,
481 	0,
482 	0,
483 	0,
484 	0,
485 	0
486 };
487 
488 #endif /* Fibre or not */
489 
490 static sd_tunables lsi_properties_scsi = {
491 	LSI_THROTTLE_VALUE,
492 	0,
493 	LSI_NOTREADY_RETRIES,
494 	0,
495 	0,
496 	0,
497 	0,
498 	0,
499 	0
500 };
501 
502 static sd_tunables symbios_properties = {
503 	SYMBIOS_THROTTLE_VALUE,
504 	0,
505 	SYMBIOS_NOTREADY_RETRIES,
506 	0,
507 	0,
508 	0,
509 	0,
510 	0,
511 	0
512 };
513 
514 static sd_tunables lsi_properties = {
515 	0,
516 	0,
517 	LSI_NOTREADY_RETRIES,
518 	0,
519 	0,
520 	0,
521 	0,
522 	0,
523 	0
524 };
525 
526 static sd_tunables lsi_oem_properties = {
527 	0,
528 	0,
529 	LSI_OEM_NOTREADY_RETRIES,
530 	0,
531 	0,
532 	0,
533 	0,
534 	0,
535 	0,
536 	1
537 };
538 
539 
540 
541 #if (defined(SD_PROP_TST))
542 
543 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
544 #define	SD_TST_THROTTLE_VAL	16
545 #define	SD_TST_NOTREADY_VAL	12
546 #define	SD_TST_BUSY_VAL		60
547 #define	SD_TST_RST_RETRY_VAL	36
548 #define	SD_TST_RSV_REL_TIME	60
549 
550 static sd_tunables tst_properties = {
551 	SD_TST_THROTTLE_VAL,
552 	SD_TST_CTYPE_VAL,
553 	SD_TST_NOTREADY_VAL,
554 	SD_TST_BUSY_VAL,
555 	SD_TST_RST_RETRY_VAL,
556 	SD_TST_RSV_REL_TIME,
557 	0,
558 	0,
559 	0
560 };
561 #endif
562 
563 /* This is similar to the ANSI toupper implementation */
564 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
565 
566 /*
567  * Static Driver Configuration Table
568  *
569  * This is the table of disks which need throttle adjustment (or, perhaps
570  * something else as defined by the flags at a future time.)  device_id
571  * is a string consisting of concatenated vid (vendor), pid (product/model)
572  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
573  * the parts of the string are as defined by the sizes in the scsi_inquiry
574  * structure.  Device type is searched as far as the device_id string is
575  * defined.  Flags defines which values are to be set in the driver from the
576  * properties list.
577  *
578  * Entries below which begin and end with a "*" are a special case.
579  * These do not have a specific vendor, and the string which follows
580  * can appear anywhere in the 16 byte PID portion of the inquiry data.
581  *
582  * Entries below which begin and end with a " " (blank) are a special
583  * case. The comparison function will treat multiple consecutive blanks
584  * as equivalent to a single blank. For example, this causes a
585  * sd_disk_table entry of " NEC CDROM " to match a device's id string
586  * of  "NEC       CDROM".
587  *
588  * Note: The MD21 controller type has been obsoleted.
589  *	 ST318202F is a Legacy device
590  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
591  *	 made with an FC connection. The entries here are a legacy.
592  */
593 static sd_disk_config_t sd_disk_table[] = {
594 #if defined(__fibre) || defined(__x86)
595 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
596 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
597 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
598 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
599 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
600 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
601 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
602 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
603 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
604 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
605 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
606 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
607 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
608 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
609 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
610 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
611 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
612 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
613 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
614 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
615 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
616 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
617 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
618 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
619 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
620 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
621 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
622 	{ "IBM     1724-100",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
623 	{ "IBM     1726-2xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
624 	{ "IBM     1726-22x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
625 	{ "IBM     1726-4xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
626 	{ "IBM     1726-42x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
627 	{ "IBM     1726-3xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
628 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
629 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
630 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
631 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
632 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
633 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
634 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
635 	{ "IBM     1814",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
636 	{ "IBM     1814-200",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
637 	{ "IBM     1818",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
638 	{ "DELL    MD3000",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
639 	{ "DELL    MD3000i",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
640 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
641 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
642 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
643 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
644 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT |
645 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
646 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT |
647 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
648 	{ "Fujitsu SX300",	SD_CONF_BSET_THROTTLE,  &lsi_oem_properties },
649 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
650 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
651 		SD_CONF_BSET_BSY_RETRY_COUNT|
652 		SD_CONF_BSET_RST_RETRIES|
653 		SD_CONF_BSET_RSV_REL_TIME|
654 		SD_CONF_BSET_MIN_THROTTLE|
655 		SD_CONF_BSET_DISKSORT_DISABLED,
656 		&sve_properties },
657 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
658 		SD_CONF_BSET_LUN_RESET_ENABLED,
659 		&maserati_properties },
660 	{ "SUN     SE6920", SD_CONF_BSET_THROTTLE |
661 		SD_CONF_BSET_NRR_COUNT|
662 		SD_CONF_BSET_BSY_RETRY_COUNT|
663 		SD_CONF_BSET_RST_RETRIES|
664 		SD_CONF_BSET_MIN_THROTTLE|
665 		SD_CONF_BSET_DISKSORT_DISABLED|
666 		SD_CONF_BSET_LUN_RESET_ENABLED,
667 		&pirus_properties },
668 	{ "SUN     SE6940", SD_CONF_BSET_THROTTLE |
669 		SD_CONF_BSET_NRR_COUNT|
670 		SD_CONF_BSET_BSY_RETRY_COUNT|
671 		SD_CONF_BSET_RST_RETRIES|
672 		SD_CONF_BSET_MIN_THROTTLE|
673 		SD_CONF_BSET_DISKSORT_DISABLED|
674 		SD_CONF_BSET_LUN_RESET_ENABLED,
675 		&pirus_properties },
676 	{ "SUN     StorageTek 6920", SD_CONF_BSET_THROTTLE |
677 		SD_CONF_BSET_NRR_COUNT|
678 		SD_CONF_BSET_BSY_RETRY_COUNT|
679 		SD_CONF_BSET_RST_RETRIES|
680 		SD_CONF_BSET_MIN_THROTTLE|
681 		SD_CONF_BSET_DISKSORT_DISABLED|
682 		SD_CONF_BSET_LUN_RESET_ENABLED,
683 		&pirus_properties },
684 	{ "SUN     StorageTek 6940", SD_CONF_BSET_THROTTLE |
685 		SD_CONF_BSET_NRR_COUNT|
686 		SD_CONF_BSET_BSY_RETRY_COUNT|
687 		SD_CONF_BSET_RST_RETRIES|
688 		SD_CONF_BSET_MIN_THROTTLE|
689 		SD_CONF_BSET_DISKSORT_DISABLED|
690 		SD_CONF_BSET_LUN_RESET_ENABLED,
691 		&pirus_properties },
692 	{ "SUN     PSX1000", SD_CONF_BSET_THROTTLE |
693 		SD_CONF_BSET_NRR_COUNT|
694 		SD_CONF_BSET_BSY_RETRY_COUNT|
695 		SD_CONF_BSET_RST_RETRIES|
696 		SD_CONF_BSET_MIN_THROTTLE|
697 		SD_CONF_BSET_DISKSORT_DISABLED|
698 		SD_CONF_BSET_LUN_RESET_ENABLED,
699 		&pirus_properties },
700 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
701 		SD_CONF_BSET_NRR_COUNT|
702 		SD_CONF_BSET_BSY_RETRY_COUNT|
703 		SD_CONF_BSET_RST_RETRIES|
704 		SD_CONF_BSET_MIN_THROTTLE|
705 		SD_CONF_BSET_DISKSORT_DISABLED|
706 		SD_CONF_BSET_LUN_RESET_ENABLED,
707 		&pirus_properties },
708 	{ "SUN     STK6580_6780", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
709 	{ "SUN     SUN_6180", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
710 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
711 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
712 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
713 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
714 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
715 #endif /* fibre or NON-sparc platforms */
716 #if ((defined(__sparc) && !defined(__fibre)) ||\
717 	(defined(__x86)))
718 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
719 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
720 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
721 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
722 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
723 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
724 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
725 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
726 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
727 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
728 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
729 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
730 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
731 	    &symbios_properties },
732 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
733 	    &lsi_properties_scsi },
734 #if defined(__x86)
735 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
736 				    | SD_CONF_BSET_READSUB_BCD
737 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
738 				    | SD_CONF_BSET_NO_READ_HEADER
739 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
740 
741 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
742 				    | SD_CONF_BSET_READSUB_BCD
743 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
744 				    | SD_CONF_BSET_NO_READ_HEADER
745 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
746 #endif /* __x86 */
747 #endif /* sparc NON-fibre or NON-sparc platforms */
748 
749 #if (defined(SD_PROP_TST))
750 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
751 				| SD_CONF_BSET_CTYPE
752 				| SD_CONF_BSET_NRR_COUNT
753 				| SD_CONF_BSET_FAB_DEVID
754 				| SD_CONF_BSET_NOCACHE
755 				| SD_CONF_BSET_BSY_RETRY_COUNT
756 				| SD_CONF_BSET_PLAYMSF_BCD
757 				| SD_CONF_BSET_READSUB_BCD
758 				| SD_CONF_BSET_READ_TOC_TRK_BCD
759 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
760 				| SD_CONF_BSET_NO_READ_HEADER
761 				| SD_CONF_BSET_READ_CD_XD4
762 				| SD_CONF_BSET_RST_RETRIES
763 				| SD_CONF_BSET_RSV_REL_TIME
764 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
765 #endif
766 };
767 
768 static const int sd_disk_table_size =
769 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
770 
771 /*
772  * Emulation mode disk drive VID/PID table
773  */
774 static char sd_flash_dev_table[][25] = {
775 	"ATA     MARVELL SD88SA02",
776 	"MARVELL SD88SA02",
777 	"TOSHIBA THNSNV05",
778 };
779 
780 static const int sd_flash_dev_table_size =
781 	sizeof (sd_flash_dev_table) / sizeof (sd_flash_dev_table[0]);
782 
783 #define	SD_INTERCONNECT_PARALLEL	0
784 #define	SD_INTERCONNECT_FABRIC		1
785 #define	SD_INTERCONNECT_FIBRE		2
786 #define	SD_INTERCONNECT_SSA		3
787 #define	SD_INTERCONNECT_SATA		4
788 #define	SD_INTERCONNECT_SAS		5
789 
790 #define	SD_IS_PARALLEL_SCSI(un)		\
791 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
792 #define	SD_IS_SERIAL(un)		\
793 	(((un)->un_interconnect_type == SD_INTERCONNECT_SATA) ||\
794 	((un)->un_interconnect_type == SD_INTERCONNECT_SAS))
795 
796 /*
797  * Definitions used by device id registration routines
798  */
799 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
800 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
801 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
802 
803 static kmutex_t sd_sense_mutex = {0};
804 
805 /*
806  * Macros for updates of the driver state
807  */
808 #define	New_state(un, s)        \
809 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
810 #define	Restore_state(un)	\
811 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
812 
813 static struct sd_cdbinfo sd_cdbtab[] = {
814 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
815 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
816 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
817 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
818 };
819 
820 /*
821  * Specifies the number of seconds that must have elapsed since the last
822  * cmd. has completed for a device to be declared idle to the PM framework.
823  */
824 static int sd_pm_idletime = 1;
825 
826 /*
827  * Internal function prototypes
828  */
829 
830 #if (defined(__fibre))
831 /*
832  * These #defines are to avoid namespace collisions that occur because this
833  * code is currently used to compile two separate driver modules: sd and ssd.
834  * All function names need to be treated this way (even if declared static)
835  * in order to allow the debugger to resolve the names properly.
836  * It is anticipated that in the near future the ssd module will be obsoleted,
837  * at which time this ugliness should go away.
838  */
839 #define	sd_log_trace			ssd_log_trace
840 #define	sd_log_info			ssd_log_info
841 #define	sd_log_err			ssd_log_err
842 #define	sdprobe				ssdprobe
843 #define	sdinfo				ssdinfo
844 #define	sd_prop_op			ssd_prop_op
845 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
846 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
847 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
848 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
849 #define	sd_scsi_target_lun_init		ssd_scsi_target_lun_init
850 #define	sd_scsi_target_lun_fini		ssd_scsi_target_lun_fini
851 #define	sd_scsi_get_target_lun_count	ssd_scsi_get_target_lun_count
852 #define	sd_scsi_update_lun_on_target	ssd_scsi_update_lun_on_target
853 #define	sd_spin_up_unit			ssd_spin_up_unit
854 #define	sd_enable_descr_sense		ssd_enable_descr_sense
855 #define	sd_reenable_dsense_task		ssd_reenable_dsense_task
856 #define	sd_set_mmc_caps			ssd_set_mmc_caps
857 #define	sd_read_unit_properties		ssd_read_unit_properties
858 #define	sd_process_sdconf_file		ssd_process_sdconf_file
859 #define	sd_process_sdconf_table		ssd_process_sdconf_table
860 #define	sd_sdconf_id_match		ssd_sdconf_id_match
861 #define	sd_blank_cmp			ssd_blank_cmp
862 #define	sd_chk_vers1_data		ssd_chk_vers1_data
863 #define	sd_set_vers1_properties		ssd_set_vers1_properties
864 #define	sd_check_bdc_vpd		ssd_check_bdc_vpd
865 #define	sd_check_emulation_mode		ssd_check_emulation_mode
866 
867 #define	sd_get_physical_geometry	ssd_get_physical_geometry
868 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
869 #define	sd_update_block_info		ssd_update_block_info
870 #define	sd_register_devid		ssd_register_devid
871 #define	sd_get_devid			ssd_get_devid
872 #define	sd_create_devid			ssd_create_devid
873 #define	sd_write_deviceid		ssd_write_deviceid
874 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
875 #define	sd_setup_pm			ssd_setup_pm
876 #define	sd_create_pm_components		ssd_create_pm_components
877 #define	sd_ddi_suspend			ssd_ddi_suspend
878 #define	sd_ddi_resume			ssd_ddi_resume
879 #define	sd_pm_state_change		ssd_pm_state_change
880 #define	sdpower				ssdpower
881 #define	sdattach			ssdattach
882 #define	sddetach			ssddetach
883 #define	sd_unit_attach			ssd_unit_attach
884 #define	sd_unit_detach			ssd_unit_detach
885 #define	sd_set_unit_attributes		ssd_set_unit_attributes
886 #define	sd_create_errstats		ssd_create_errstats
887 #define	sd_set_errstats			ssd_set_errstats
888 #define	sd_set_pstats			ssd_set_pstats
889 #define	sddump				ssddump
890 #define	sd_scsi_poll			ssd_scsi_poll
891 #define	sd_send_polled_RQS		ssd_send_polled_RQS
892 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
893 #define	sd_init_event_callbacks		ssd_init_event_callbacks
894 #define	sd_event_callback		ssd_event_callback
895 #define	sd_cache_control		ssd_cache_control
896 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
897 #define	sd_get_write_cache_changeable	ssd_get_write_cache_changeable
898 #define	sd_get_nv_sup			ssd_get_nv_sup
899 #define	sd_make_device			ssd_make_device
900 #define	sdopen				ssdopen
901 #define	sdclose				ssdclose
902 #define	sd_ready_and_valid		ssd_ready_and_valid
903 #define	sdmin				ssdmin
904 #define	sdread				ssdread
905 #define	sdwrite				ssdwrite
906 #define	sdaread				ssdaread
907 #define	sdawrite			ssdawrite
908 #define	sdstrategy			ssdstrategy
909 #define	sdioctl				ssdioctl
910 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
911 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
912 #define	sd_checksum_iostart		ssd_checksum_iostart
913 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
914 #define	sd_pm_iostart			ssd_pm_iostart
915 #define	sd_core_iostart			ssd_core_iostart
916 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
917 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
918 #define	sd_checksum_iodone		ssd_checksum_iodone
919 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
920 #define	sd_pm_iodone			ssd_pm_iodone
921 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
922 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
923 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
924 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
925 #define	sd_buf_iodone			ssd_buf_iodone
926 #define	sd_uscsi_strategy		ssd_uscsi_strategy
927 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
928 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
929 #define	sd_uscsi_iodone			ssd_uscsi_iodone
930 #define	sd_xbuf_strategy		ssd_xbuf_strategy
931 #define	sd_xbuf_init			ssd_xbuf_init
932 #define	sd_pm_entry			ssd_pm_entry
933 #define	sd_pm_exit			ssd_pm_exit
934 
935 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
936 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
937 
938 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
939 #define	sdintr				ssdintr
940 #define	sd_start_cmds			ssd_start_cmds
941 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
942 #define	sd_bioclone_alloc		ssd_bioclone_alloc
943 #define	sd_bioclone_free		ssd_bioclone_free
944 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
945 #define	sd_shadow_buf_free		ssd_shadow_buf_free
946 #define	sd_print_transport_rejected_message	\
947 					ssd_print_transport_rejected_message
948 #define	sd_retry_command		ssd_retry_command
949 #define	sd_set_retry_bp			ssd_set_retry_bp
950 #define	sd_send_request_sense_command	ssd_send_request_sense_command
951 #define	sd_start_retry_command		ssd_start_retry_command
952 #define	sd_start_direct_priority_command	\
953 					ssd_start_direct_priority_command
954 #define	sd_return_failed_command	ssd_return_failed_command
955 #define	sd_return_failed_command_no_restart	\
956 					ssd_return_failed_command_no_restart
957 #define	sd_return_command		ssd_return_command
958 #define	sd_sync_with_callback		ssd_sync_with_callback
959 #define	sdrunout			ssdrunout
960 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
961 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
962 #define	sd_reduce_throttle		ssd_reduce_throttle
963 #define	sd_restore_throttle		ssd_restore_throttle
964 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
965 #define	sd_init_cdb_limits		ssd_init_cdb_limits
966 #define	sd_pkt_status_good		ssd_pkt_status_good
967 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
968 #define	sd_pkt_status_busy		ssd_pkt_status_busy
969 #define	sd_pkt_status_reservation_conflict	\
970 					ssd_pkt_status_reservation_conflict
971 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
972 #define	sd_handle_request_sense		ssd_handle_request_sense
973 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
974 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
975 #define	sd_validate_sense_data		ssd_validate_sense_data
976 #define	sd_decode_sense			ssd_decode_sense
977 #define	sd_print_sense_msg		ssd_print_sense_msg
978 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
979 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
980 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
981 #define	sd_sense_key_medium_or_hardware_error	\
982 					ssd_sense_key_medium_or_hardware_error
983 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
984 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
985 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
986 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
987 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
988 #define	sd_sense_key_default		ssd_sense_key_default
989 #define	sd_print_retry_msg		ssd_print_retry_msg
990 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
991 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
992 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
993 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
994 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
995 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
996 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
997 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
998 #define	sd_pkt_reason_default		ssd_pkt_reason_default
999 #define	sd_reset_target			ssd_reset_target
1000 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
1001 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
1002 #define	sd_taskq_create			ssd_taskq_create
1003 #define	sd_taskq_delete			ssd_taskq_delete
1004 #define	sd_target_change_task		ssd_target_change_task
1005 #define	sd_log_dev_status_event		ssd_log_dev_status_event
1006 #define	sd_log_lun_expansion_event	ssd_log_lun_expansion_event
1007 #define	sd_log_eject_request_event	ssd_log_eject_request_event
1008 #define	sd_media_change_task		ssd_media_change_task
1009 #define	sd_handle_mchange		ssd_handle_mchange
1010 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
1011 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
1012 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
1013 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
1014 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
1015 					sd_send_scsi_feature_GET_CONFIGURATION
1016 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
1017 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
1018 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
1019 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
1020 					ssd_send_scsi_PERSISTENT_RESERVE_IN
1021 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
1022 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
1023 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
1024 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
1025 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
1026 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
1027 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
1028 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
1029 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
1030 #define	sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION	\
1031 				ssd_send_scsi_GET_EVENT_STATUS_NOTIFICATION
1032 #define	sd_gesn_media_data_valid	ssd_gesn_media_data_valid
1033 #define	sd_alloc_rqs			ssd_alloc_rqs
1034 #define	sd_free_rqs			ssd_free_rqs
1035 #define	sd_dump_memory			ssd_dump_memory
1036 #define	sd_get_media_info_com		ssd_get_media_info_com
1037 #define	sd_get_media_info		ssd_get_media_info
1038 #define	sd_get_media_info_ext		ssd_get_media_info_ext
1039 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
1040 #define	sd_nvpair_str_decode		ssd_nvpair_str_decode
1041 #define	sd_set_properties		ssd_set_properties
1042 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
1043 #define	sd_setup_next_xfer		ssd_setup_next_xfer
1044 #define	sd_dkio_get_temp		ssd_dkio_get_temp
1045 #define	sd_check_mhd			ssd_check_mhd
1046 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1047 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1048 #define	sd_sname			ssd_sname
1049 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1050 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1051 #define	sd_take_ownership		ssd_take_ownership
1052 #define	sd_reserve_release		ssd_reserve_release
1053 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1054 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1055 #define	sd_persistent_reservation_in_read_keys	\
1056 					ssd_persistent_reservation_in_read_keys
1057 #define	sd_persistent_reservation_in_read_resv	\
1058 					ssd_persistent_reservation_in_read_resv
1059 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1060 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1061 #define	sd_mhdioc_release		ssd_mhdioc_release
1062 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1063 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1064 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1065 #define	sr_change_blkmode		ssr_change_blkmode
1066 #define	sr_change_speed			ssr_change_speed
1067 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1068 #define	sr_pause_resume			ssr_pause_resume
1069 #define	sr_play_msf			ssr_play_msf
1070 #define	sr_play_trkind			ssr_play_trkind
1071 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1072 #define	sr_read_subchannel		ssr_read_subchannel
1073 #define	sr_read_tocentry		ssr_read_tocentry
1074 #define	sr_read_tochdr			ssr_read_tochdr
1075 #define	sr_read_cdda			ssr_read_cdda
1076 #define	sr_read_cdxa			ssr_read_cdxa
1077 #define	sr_read_mode1			ssr_read_mode1
1078 #define	sr_read_mode2			ssr_read_mode2
1079 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1080 #define	sr_sector_mode			ssr_sector_mode
1081 #define	sr_eject			ssr_eject
1082 #define	sr_ejected			ssr_ejected
1083 #define	sr_check_wp			ssr_check_wp
1084 #define	sd_watch_request_submit		ssd_watch_request_submit
1085 #define	sd_check_media			ssd_check_media
1086 #define	sd_media_watch_cb		ssd_media_watch_cb
1087 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1088 #define	sr_volume_ctrl			ssr_volume_ctrl
1089 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1090 #define	sd_log_page_supported		ssd_log_page_supported
1091 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1092 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1093 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1094 #define	sd_range_lock			ssd_range_lock
1095 #define	sd_get_range			ssd_get_range
1096 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1097 #define	sd_range_unlock			ssd_range_unlock
1098 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1099 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1100 
1101 #define	sd_iostart_chain		ssd_iostart_chain
1102 #define	sd_iodone_chain			ssd_iodone_chain
1103 #define	sd_initpkt_map			ssd_initpkt_map
1104 #define	sd_destroypkt_map		ssd_destroypkt_map
1105 #define	sd_chain_type_map		ssd_chain_type_map
1106 #define	sd_chain_index_map		ssd_chain_index_map
1107 
1108 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1109 #define	sd_failfast_flushq		ssd_failfast_flushq
1110 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1111 
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 for partial DMA support
1640  */
1641 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1642 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1643 
1644 
1645 /* Function prototypes for cmlb */
1646 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1647     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1648 
1649 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1650 
1651 /*
1652  * For printing RMW warning message timely
1653  */
1654 static void sd_rmw_msg_print_handler(void *arg);
1655 
1656 /*
1657  * Constants for failfast support:
1658  *
1659  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1660  * failfast processing being performed.
1661  *
1662  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1663  * failfast processing on all bufs with B_FAILFAST set.
1664  */
1665 
1666 #define	SD_FAILFAST_INACTIVE		0
1667 #define	SD_FAILFAST_ACTIVE		1
1668 
1669 /*
1670  * Bitmask to control behavior of buf(9S) flushes when a transition to
1671  * the failfast state occurs. Optional bits include:
1672  *
1673  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1674  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1675  * be flushed.
1676  *
1677  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1678  * driver, in addition to the regular wait queue. This includes the xbuf
1679  * queues. When clear, only the driver's wait queue will be flushed.
1680  */
1681 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1682 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1683 
1684 /*
1685  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1686  * to flush all queues within the driver.
1687  */
1688 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1689 
1690 
1691 /*
1692  * SD Testing Fault Injection
1693  */
1694 #ifdef SD_FAULT_INJECTION
1695 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1696 static void sd_faultinjection(struct scsi_pkt *pktp);
1697 static void sd_injection_log(char *buf, struct sd_lun *un);
1698 #endif
1699 
1700 /*
1701  * Device driver ops vector
1702  */
1703 static struct cb_ops sd_cb_ops = {
1704 	sdopen,			/* open */
1705 	sdclose,		/* close */
1706 	sdstrategy,		/* strategy */
1707 	nodev,			/* print */
1708 	sddump,			/* dump */
1709 	sdread,			/* read */
1710 	sdwrite,		/* write */
1711 	sdioctl,		/* ioctl */
1712 	nodev,			/* devmap */
1713 	nodev,			/* mmap */
1714 	nodev,			/* segmap */
1715 	nochpoll,		/* poll */
1716 	sd_prop_op,		/* cb_prop_op */
1717 	0,			/* streamtab  */
1718 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1719 	CB_REV,			/* cb_rev */
1720 	sdaread,		/* async I/O read entry point */
1721 	sdawrite		/* async I/O write entry point */
1722 };
1723 
1724 struct dev_ops sd_ops = {
1725 	DEVO_REV,		/* devo_rev, */
1726 	0,			/* refcnt  */
1727 	sdinfo,			/* info */
1728 	nulldev,		/* identify */
1729 	sdprobe,		/* probe */
1730 	sdattach,		/* attach */
1731 	sddetach,		/* detach */
1732 	nodev,			/* reset */
1733 	&sd_cb_ops,		/* driver operations */
1734 	NULL,			/* bus operations */
1735 	sdpower,		/* power */
1736 	ddi_quiesce_not_needed,		/* quiesce */
1737 };
1738 
1739 /*
1740  * This is the loadable module wrapper.
1741  */
1742 #include <sys/modctl.h>
1743 
1744 static struct modldrv modldrv = {
1745 	&mod_driverops,		/* Type of module. This one is a driver */
1746 	SD_MODULE_NAME,		/* Module name. */
1747 	&sd_ops			/* driver ops */
1748 };
1749 
1750 static struct modlinkage modlinkage = {
1751 	MODREV_1, &modldrv, NULL
1752 };
1753 
1754 static cmlb_tg_ops_t sd_tgops = {
1755 	TG_DK_OPS_VERSION_1,
1756 	sd_tg_rdwr,
1757 	sd_tg_getinfo
1758 };
1759 
1760 static struct scsi_asq_key_strings sd_additional_codes[] = {
1761 	0x81, 0, "Logical Unit is Reserved",
1762 	0x85, 0, "Audio Address Not Valid",
1763 	0xb6, 0, "Media Load Mechanism Failed",
1764 	0xB9, 0, "Audio Play Operation Aborted",
1765 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1766 	0x53, 2, "Medium removal prevented",
1767 	0x6f, 0, "Authentication failed during key exchange",
1768 	0x6f, 1, "Key not present",
1769 	0x6f, 2, "Key not established",
1770 	0x6f, 3, "Read without proper authentication",
1771 	0x6f, 4, "Mismatched region to this logical unit",
1772 	0x6f, 5, "Region reset count error",
1773 	0xffff, 0x0, NULL
1774 };
1775 
1776 
1777 /*
1778  * Struct for passing printing information for sense data messages
1779  */
1780 struct sd_sense_info {
1781 	int	ssi_severity;
1782 	int	ssi_pfa_flag;
1783 };
1784 
1785 /*
1786  * Table of function pointers for iostart-side routines. Separate "chains"
1787  * of layered function calls are formed by placing the function pointers
1788  * sequentially in the desired order. Functions are called according to an
1789  * incrementing table index ordering. The last function in each chain must
1790  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1791  * in the sd_iodone_chain[] array.
1792  *
1793  * Note: It may seem more natural to organize both the iostart and iodone
1794  * functions together, into an array of structures (or some similar
1795  * organization) with a common index, rather than two separate arrays which
1796  * must be maintained in synchronization. The purpose of this division is
1797  * to achieve improved performance: individual arrays allows for more
1798  * effective cache line utilization on certain platforms.
1799  */
1800 
1801 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1802 
1803 
1804 static sd_chain_t sd_iostart_chain[] = {
1805 
1806 	/* Chain for buf IO for disk drive targets (PM enabled) */
1807 	sd_mapblockaddr_iostart,	/* Index: 0 */
1808 	sd_pm_iostart,			/* Index: 1 */
1809 	sd_core_iostart,		/* Index: 2 */
1810 
1811 	/* Chain for buf IO for disk drive targets (PM disabled) */
1812 	sd_mapblockaddr_iostart,	/* Index: 3 */
1813 	sd_core_iostart,		/* Index: 4 */
1814 
1815 	/*
1816 	 * Chain for buf IO for removable-media or large sector size
1817 	 * disk drive targets with RMW needed (PM enabled)
1818 	 */
1819 	sd_mapblockaddr_iostart,	/* Index: 5 */
1820 	sd_mapblocksize_iostart,	/* Index: 6 */
1821 	sd_pm_iostart,			/* Index: 7 */
1822 	sd_core_iostart,		/* Index: 8 */
1823 
1824 	/*
1825 	 * Chain for buf IO for removable-media or large sector size
1826 	 * disk drive targets with RMW needed (PM disabled)
1827 	 */
1828 	sd_mapblockaddr_iostart,	/* Index: 9 */
1829 	sd_mapblocksize_iostart,	/* Index: 10 */
1830 	sd_core_iostart,		/* Index: 11 */
1831 
1832 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1833 	sd_mapblockaddr_iostart,	/* Index: 12 */
1834 	sd_checksum_iostart,		/* Index: 13 */
1835 	sd_pm_iostart,			/* Index: 14 */
1836 	sd_core_iostart,		/* Index: 15 */
1837 
1838 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1839 	sd_mapblockaddr_iostart,	/* Index: 16 */
1840 	sd_checksum_iostart,		/* Index: 17 */
1841 	sd_core_iostart,		/* Index: 18 */
1842 
1843 	/* Chain for USCSI commands (all targets) */
1844 	sd_pm_iostart,			/* Index: 19 */
1845 	sd_core_iostart,		/* Index: 20 */
1846 
1847 	/* Chain for checksumming USCSI commands (all targets) */
1848 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1849 	sd_pm_iostart,			/* Index: 22 */
1850 	sd_core_iostart,		/* Index: 23 */
1851 
1852 	/* Chain for "direct" USCSI commands (all targets) */
1853 	sd_core_iostart,		/* Index: 24 */
1854 
1855 	/* Chain for "direct priority" USCSI commands (all targets) */
1856 	sd_core_iostart,		/* Index: 25 */
1857 
1858 	/*
1859 	 * Chain for buf IO for large sector size disk drive targets
1860 	 * with RMW needed with checksumming (PM enabled)
1861 	 */
1862 	sd_mapblockaddr_iostart,	/* Index: 26 */
1863 	sd_mapblocksize_iostart,	/* Index: 27 */
1864 	sd_checksum_iostart,		/* Index: 28 */
1865 	sd_pm_iostart,			/* Index: 29 */
1866 	sd_core_iostart,		/* Index: 30 */
1867 
1868 	/*
1869 	 * Chain for buf IO for large sector size disk drive targets
1870 	 * with RMW needed with checksumming (PM disabled)
1871 	 */
1872 	sd_mapblockaddr_iostart,	/* Index: 31 */
1873 	sd_mapblocksize_iostart,	/* Index: 32 */
1874 	sd_checksum_iostart,		/* Index: 33 */
1875 	sd_core_iostart,		/* Index: 34 */
1876 
1877 };
1878 
1879 /*
1880  * Macros to locate the first function of each iostart chain in the
1881  * sd_iostart_chain[] array. These are located by the index in the array.
1882  */
1883 #define	SD_CHAIN_DISK_IOSTART			0
1884 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1885 #define	SD_CHAIN_MSS_DISK_IOSTART		5
1886 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1887 #define	SD_CHAIN_MSS_DISK_IOSTART_NO_PM		9
1888 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1889 #define	SD_CHAIN_CHKSUM_IOSTART			12
1890 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1891 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1892 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1893 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1894 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1895 #define	SD_CHAIN_MSS_CHKSUM_IOSTART		26
1896 #define	SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM	31
1897 
1898 
1899 /*
1900  * Table of function pointers for the iodone-side routines for the driver-
1901  * internal layering mechanism.  The calling sequence for iodone routines
1902  * uses a decrementing table index, so the last routine called in a chain
1903  * must be at the lowest array index location for that chain.  The last
1904  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1905  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1906  * of the functions in an iodone side chain must correspond to the ordering
1907  * of the iostart routines for that chain.  Note that there is no iodone
1908  * side routine that corresponds to sd_core_iostart(), so there is no
1909  * entry in the table for this.
1910  */
1911 
1912 static sd_chain_t sd_iodone_chain[] = {
1913 
1914 	/* Chain for buf IO for disk drive targets (PM enabled) */
1915 	sd_buf_iodone,			/* Index: 0 */
1916 	sd_mapblockaddr_iodone,		/* Index: 1 */
1917 	sd_pm_iodone,			/* Index: 2 */
1918 
1919 	/* Chain for buf IO for disk drive targets (PM disabled) */
1920 	sd_buf_iodone,			/* Index: 3 */
1921 	sd_mapblockaddr_iodone,		/* Index: 4 */
1922 
1923 	/*
1924 	 * Chain for buf IO for removable-media or large sector size
1925 	 * disk drive targets with RMW needed (PM enabled)
1926 	 */
1927 	sd_buf_iodone,			/* Index: 5 */
1928 	sd_mapblockaddr_iodone,		/* Index: 6 */
1929 	sd_mapblocksize_iodone,		/* Index: 7 */
1930 	sd_pm_iodone,			/* Index: 8 */
1931 
1932 	/*
1933 	 * Chain for buf IO for removable-media or large sector size
1934 	 * disk drive targets with RMW needed (PM disabled)
1935 	 */
1936 	sd_buf_iodone,			/* Index: 9 */
1937 	sd_mapblockaddr_iodone,		/* Index: 10 */
1938 	sd_mapblocksize_iodone,		/* Index: 11 */
1939 
1940 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1941 	sd_buf_iodone,			/* Index: 12 */
1942 	sd_mapblockaddr_iodone,		/* Index: 13 */
1943 	sd_checksum_iodone,		/* Index: 14 */
1944 	sd_pm_iodone,			/* Index: 15 */
1945 
1946 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1947 	sd_buf_iodone,			/* Index: 16 */
1948 	sd_mapblockaddr_iodone,		/* Index: 17 */
1949 	sd_checksum_iodone,		/* Index: 18 */
1950 
1951 	/* Chain for USCSI commands (non-checksum targets) */
1952 	sd_uscsi_iodone,		/* Index: 19 */
1953 	sd_pm_iodone,			/* Index: 20 */
1954 
1955 	/* Chain for USCSI commands (checksum targets) */
1956 	sd_uscsi_iodone,		/* Index: 21 */
1957 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1958 	sd_pm_iodone,			/* Index: 22 */
1959 
1960 	/* Chain for "direct" USCSI commands (all targets) */
1961 	sd_uscsi_iodone,		/* Index: 24 */
1962 
1963 	/* Chain for "direct priority" USCSI commands (all targets) */
1964 	sd_uscsi_iodone,		/* Index: 25 */
1965 
1966 	/*
1967 	 * Chain for buf IO for large sector size disk drive targets
1968 	 * with checksumming (PM enabled)
1969 	 */
1970 	sd_buf_iodone,			/* Index: 26 */
1971 	sd_mapblockaddr_iodone,		/* Index: 27 */
1972 	sd_mapblocksize_iodone,		/* Index: 28 */
1973 	sd_checksum_iodone,		/* Index: 29 */
1974 	sd_pm_iodone,			/* Index: 30 */
1975 
1976 	/*
1977 	 * Chain for buf IO for large sector size disk drive targets
1978 	 * with checksumming (PM disabled)
1979 	 */
1980 	sd_buf_iodone,			/* Index: 31 */
1981 	sd_mapblockaddr_iodone,		/* Index: 32 */
1982 	sd_mapblocksize_iodone,		/* Index: 33 */
1983 	sd_checksum_iodone,		/* Index: 34 */
1984 };
1985 
1986 
1987 /*
1988  * Macros to locate the "first" function in the sd_iodone_chain[] array for
1989  * each iodone-side chain. These are located by the array index, but as the
1990  * iodone side functions are called in a decrementing-index order, the
1991  * highest index number in each chain must be specified (as these correspond
1992  * to the first function in the iodone chain that will be called by the core
1993  * at IO completion time).
1994  */
1995 
1996 #define	SD_CHAIN_DISK_IODONE			2
1997 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
1998 #define	SD_CHAIN_RMMEDIA_IODONE			8
1999 #define	SD_CHAIN_MSS_DISK_IODONE		8
2000 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
2001 #define	SD_CHAIN_MSS_DISK_IODONE_NO_PM		11
2002 #define	SD_CHAIN_CHKSUM_IODONE			15
2003 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
2004 #define	SD_CHAIN_USCSI_CMD_IODONE		20
2005 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
2006 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
2007 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
2008 #define	SD_CHAIN_MSS_CHKSUM_IODONE		30
2009 #define	SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM	34
2010 
2011 
2012 
2013 /*
2014  * Array to map a layering chain index to the appropriate initpkt routine.
2015  * The redundant entries are present so that the index used for accessing
2016  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2017  * with this table as well.
2018  */
2019 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
2020 
2021 static sd_initpkt_t	sd_initpkt_map[] = {
2022 
2023 	/* Chain for buf IO for disk drive targets (PM enabled) */
2024 	sd_initpkt_for_buf,		/* Index: 0 */
2025 	sd_initpkt_for_buf,		/* Index: 1 */
2026 	sd_initpkt_for_buf,		/* Index: 2 */
2027 
2028 	/* Chain for buf IO for disk drive targets (PM disabled) */
2029 	sd_initpkt_for_buf,		/* Index: 3 */
2030 	sd_initpkt_for_buf,		/* Index: 4 */
2031 
2032 	/*
2033 	 * Chain for buf IO for removable-media or large sector size
2034 	 * disk drive targets (PM enabled)
2035 	 */
2036 	sd_initpkt_for_buf,		/* Index: 5 */
2037 	sd_initpkt_for_buf,		/* Index: 6 */
2038 	sd_initpkt_for_buf,		/* Index: 7 */
2039 	sd_initpkt_for_buf,		/* Index: 8 */
2040 
2041 	/*
2042 	 * Chain for buf IO for removable-media or large sector size
2043 	 * disk drive targets (PM disabled)
2044 	 */
2045 	sd_initpkt_for_buf,		/* Index: 9 */
2046 	sd_initpkt_for_buf,		/* Index: 10 */
2047 	sd_initpkt_for_buf,		/* Index: 11 */
2048 
2049 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2050 	sd_initpkt_for_buf,		/* Index: 12 */
2051 	sd_initpkt_for_buf,		/* Index: 13 */
2052 	sd_initpkt_for_buf,		/* Index: 14 */
2053 	sd_initpkt_for_buf,		/* Index: 15 */
2054 
2055 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2056 	sd_initpkt_for_buf,		/* Index: 16 */
2057 	sd_initpkt_for_buf,		/* Index: 17 */
2058 	sd_initpkt_for_buf,		/* Index: 18 */
2059 
2060 	/* Chain for USCSI commands (non-checksum targets) */
2061 	sd_initpkt_for_uscsi,		/* Index: 19 */
2062 	sd_initpkt_for_uscsi,		/* Index: 20 */
2063 
2064 	/* Chain for USCSI commands (checksum targets) */
2065 	sd_initpkt_for_uscsi,		/* Index: 21 */
2066 	sd_initpkt_for_uscsi,		/* Index: 22 */
2067 	sd_initpkt_for_uscsi,		/* Index: 22 */
2068 
2069 	/* Chain for "direct" USCSI commands (all targets) */
2070 	sd_initpkt_for_uscsi,		/* Index: 24 */
2071 
2072 	/* Chain for "direct priority" USCSI commands (all targets) */
2073 	sd_initpkt_for_uscsi,		/* Index: 25 */
2074 
2075 	/*
2076 	 * Chain for buf IO for large sector size disk drive targets
2077 	 * with checksumming (PM enabled)
2078 	 */
2079 	sd_initpkt_for_buf,		/* Index: 26 */
2080 	sd_initpkt_for_buf,		/* Index: 27 */
2081 	sd_initpkt_for_buf,		/* Index: 28 */
2082 	sd_initpkt_for_buf,		/* Index: 29 */
2083 	sd_initpkt_for_buf,		/* Index: 30 */
2084 
2085 	/*
2086 	 * Chain for buf IO for large sector size disk drive targets
2087 	 * with checksumming (PM disabled)
2088 	 */
2089 	sd_initpkt_for_buf,		/* Index: 31 */
2090 	sd_initpkt_for_buf,		/* Index: 32 */
2091 	sd_initpkt_for_buf,		/* Index: 33 */
2092 	sd_initpkt_for_buf,		/* Index: 34 */
2093 };
2094 
2095 
2096 /*
2097  * Array to map a layering chain index to the appropriate destroypktpkt routine.
2098  * The redundant entries are present so that the index used for accessing
2099  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2100  * with this table as well.
2101  */
2102 typedef void (*sd_destroypkt_t)(struct buf *);
2103 
2104 static sd_destroypkt_t	sd_destroypkt_map[] = {
2105 
2106 	/* Chain for buf IO for disk drive targets (PM enabled) */
2107 	sd_destroypkt_for_buf,		/* Index: 0 */
2108 	sd_destroypkt_for_buf,		/* Index: 1 */
2109 	sd_destroypkt_for_buf,		/* Index: 2 */
2110 
2111 	/* Chain for buf IO for disk drive targets (PM disabled) */
2112 	sd_destroypkt_for_buf,		/* Index: 3 */
2113 	sd_destroypkt_for_buf,		/* Index: 4 */
2114 
2115 	/*
2116 	 * Chain for buf IO for removable-media or large sector size
2117 	 * disk drive targets (PM enabled)
2118 	 */
2119 	sd_destroypkt_for_buf,		/* Index: 5 */
2120 	sd_destroypkt_for_buf,		/* Index: 6 */
2121 	sd_destroypkt_for_buf,		/* Index: 7 */
2122 	sd_destroypkt_for_buf,		/* Index: 8 */
2123 
2124 	/*
2125 	 * Chain for buf IO for removable-media or large sector size
2126 	 * disk drive targets (PM disabled)
2127 	 */
2128 	sd_destroypkt_for_buf,		/* Index: 9 */
2129 	sd_destroypkt_for_buf,		/* Index: 10 */
2130 	sd_destroypkt_for_buf,		/* Index: 11 */
2131 
2132 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2133 	sd_destroypkt_for_buf,		/* Index: 12 */
2134 	sd_destroypkt_for_buf,		/* Index: 13 */
2135 	sd_destroypkt_for_buf,		/* Index: 14 */
2136 	sd_destroypkt_for_buf,		/* Index: 15 */
2137 
2138 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2139 	sd_destroypkt_for_buf,		/* Index: 16 */
2140 	sd_destroypkt_for_buf,		/* Index: 17 */
2141 	sd_destroypkt_for_buf,		/* Index: 18 */
2142 
2143 	/* Chain for USCSI commands (non-checksum targets) */
2144 	sd_destroypkt_for_uscsi,	/* Index: 19 */
2145 	sd_destroypkt_for_uscsi,	/* Index: 20 */
2146 
2147 	/* Chain for USCSI commands (checksum targets) */
2148 	sd_destroypkt_for_uscsi,	/* Index: 21 */
2149 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2150 	sd_destroypkt_for_uscsi,	/* Index: 22 */
2151 
2152 	/* Chain for "direct" USCSI commands (all targets) */
2153 	sd_destroypkt_for_uscsi,	/* Index: 24 */
2154 
2155 	/* Chain for "direct priority" USCSI commands (all targets) */
2156 	sd_destroypkt_for_uscsi,	/* Index: 25 */
2157 
2158 	/*
2159 	 * Chain for buf IO for large sector size disk drive targets
2160 	 * with checksumming (PM disabled)
2161 	 */
2162 	sd_destroypkt_for_buf,		/* Index: 26 */
2163 	sd_destroypkt_for_buf,		/* Index: 27 */
2164 	sd_destroypkt_for_buf,		/* Index: 28 */
2165 	sd_destroypkt_for_buf,		/* Index: 29 */
2166 	sd_destroypkt_for_buf,		/* Index: 30 */
2167 
2168 	/*
2169 	 * Chain for buf IO for large sector size disk drive targets
2170 	 * with checksumming (PM enabled)
2171 	 */
2172 	sd_destroypkt_for_buf,		/* Index: 31 */
2173 	sd_destroypkt_for_buf,		/* Index: 32 */
2174 	sd_destroypkt_for_buf,		/* Index: 33 */
2175 	sd_destroypkt_for_buf,		/* Index: 34 */
2176 };
2177 
2178 
2179 
2180 /*
2181  * Array to map a layering chain index to the appropriate chain "type".
2182  * The chain type indicates a specific property/usage of the chain.
2183  * The redundant entries are present so that the index used for accessing
2184  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
2185  * with this table as well.
2186  */
2187 
2188 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
2189 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
2190 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
2191 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
2192 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
2193 						/* (for error recovery) */
2194 
2195 static int sd_chain_type_map[] = {
2196 
2197 	/* Chain for buf IO for disk drive targets (PM enabled) */
2198 	SD_CHAIN_BUFIO,			/* Index: 0 */
2199 	SD_CHAIN_BUFIO,			/* Index: 1 */
2200 	SD_CHAIN_BUFIO,			/* Index: 2 */
2201 
2202 	/* Chain for buf IO for disk drive targets (PM disabled) */
2203 	SD_CHAIN_BUFIO,			/* Index: 3 */
2204 	SD_CHAIN_BUFIO,			/* Index: 4 */
2205 
2206 	/*
2207 	 * Chain for buf IO for removable-media or large sector size
2208 	 * disk drive targets (PM enabled)
2209 	 */
2210 	SD_CHAIN_BUFIO,			/* Index: 5 */
2211 	SD_CHAIN_BUFIO,			/* Index: 6 */
2212 	SD_CHAIN_BUFIO,			/* Index: 7 */
2213 	SD_CHAIN_BUFIO,			/* Index: 8 */
2214 
2215 	/*
2216 	 * Chain for buf IO for removable-media or large sector size
2217 	 * disk drive targets (PM disabled)
2218 	 */
2219 	SD_CHAIN_BUFIO,			/* Index: 9 */
2220 	SD_CHAIN_BUFIO,			/* Index: 10 */
2221 	SD_CHAIN_BUFIO,			/* Index: 11 */
2222 
2223 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2224 	SD_CHAIN_BUFIO,			/* Index: 12 */
2225 	SD_CHAIN_BUFIO,			/* Index: 13 */
2226 	SD_CHAIN_BUFIO,			/* Index: 14 */
2227 	SD_CHAIN_BUFIO,			/* Index: 15 */
2228 
2229 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2230 	SD_CHAIN_BUFIO,			/* Index: 16 */
2231 	SD_CHAIN_BUFIO,			/* Index: 17 */
2232 	SD_CHAIN_BUFIO,			/* Index: 18 */
2233 
2234 	/* Chain for USCSI commands (non-checksum targets) */
2235 	SD_CHAIN_USCSI,			/* Index: 19 */
2236 	SD_CHAIN_USCSI,			/* Index: 20 */
2237 
2238 	/* Chain for USCSI commands (checksum targets) */
2239 	SD_CHAIN_USCSI,			/* Index: 21 */
2240 	SD_CHAIN_USCSI,			/* Index: 22 */
2241 	SD_CHAIN_USCSI,			/* Index: 23 */
2242 
2243 	/* Chain for "direct" USCSI commands (all targets) */
2244 	SD_CHAIN_DIRECT,		/* Index: 24 */
2245 
2246 	/* Chain for "direct priority" USCSI commands (all targets) */
2247 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2248 
2249 	/*
2250 	 * Chain for buf IO for large sector size disk drive targets
2251 	 * with checksumming (PM enabled)
2252 	 */
2253 	SD_CHAIN_BUFIO,			/* Index: 26 */
2254 	SD_CHAIN_BUFIO,			/* Index: 27 */
2255 	SD_CHAIN_BUFIO,			/* Index: 28 */
2256 	SD_CHAIN_BUFIO,			/* Index: 29 */
2257 	SD_CHAIN_BUFIO,			/* Index: 30 */
2258 
2259 	/*
2260 	 * Chain for buf IO for large sector size disk drive targets
2261 	 * with checksumming (PM disabled)
2262 	 */
2263 	SD_CHAIN_BUFIO,			/* Index: 31 */
2264 	SD_CHAIN_BUFIO,			/* Index: 32 */
2265 	SD_CHAIN_BUFIO,			/* Index: 33 */
2266 	SD_CHAIN_BUFIO,			/* Index: 34 */
2267 };
2268 
2269 
2270 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2271 #define	SD_IS_BUFIO(xp)			\
2272 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2273 
2274 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2275 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2276 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2277 
2278 
2279 
2280 /*
2281  * Struct, array, and macros to map a specific chain to the appropriate
2282  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2283  *
2284  * The sd_chain_index_map[] array is used at attach time to set the various
2285  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2286  * chain to be used with the instance. This allows different instances to use
2287  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2288  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2289  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2290  * dynamically & without the use of locking; and (2) a layer may update the
2291  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2292  * to allow for deferred processing of an IO within the same chain from a
2293  * different execution context.
2294  */
2295 
2296 struct sd_chain_index {
2297 	int	sci_iostart_index;
2298 	int	sci_iodone_index;
2299 };
2300 
2301 static struct sd_chain_index	sd_chain_index_map[] = {
2302 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2303 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2304 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2305 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2306 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2307 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2308 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2309 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2310 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2311 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2312 	{ SD_CHAIN_MSS_CHKSUM_IOSTART,		SD_CHAIN_MSS_CHKSUM_IODONE },
2313 	{ SD_CHAIN_MSS_CHKSUM_IOSTART_NO_PM, SD_CHAIN_MSS_CHKSUM_IODONE_NO_PM },
2314 
2315 };
2316 
2317 
2318 /*
2319  * The following are indexes into the sd_chain_index_map[] array.
2320  */
2321 
2322 /* un->un_buf_chain_type must be set to one of these */
2323 #define	SD_CHAIN_INFO_DISK		0
2324 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2325 #define	SD_CHAIN_INFO_RMMEDIA		2
2326 #define	SD_CHAIN_INFO_MSS_DISK		2
2327 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2328 #define	SD_CHAIN_INFO_MSS_DSK_NO_PM	3
2329 #define	SD_CHAIN_INFO_CHKSUM		4
2330 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2331 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM	10
2332 #define	SD_CHAIN_INFO_MSS_DISK_CHKSUM_NO_PM	11
2333 
2334 /* un->un_uscsi_chain_type must be set to one of these */
2335 #define	SD_CHAIN_INFO_USCSI_CMD		6
2336 /* USCSI with PM disabled is the same as DIRECT */
2337 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2338 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2339 
2340 /* un->un_direct_chain_type must be set to one of these */
2341 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2342 
2343 /* un->un_priority_chain_type must be set to one of these */
2344 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2345 
2346 /* size for devid inquiries */
2347 #define	MAX_INQUIRY_SIZE		0xF0
2348 
2349 /*
2350  * Macros used by functions to pass a given buf(9S) struct along to the
2351  * next function in the layering chain for further processing.
2352  *
2353  * In the following macros, passing more than three arguments to the called
2354  * routines causes the optimizer for the SPARC compiler to stop doing tail
2355  * call elimination which results in significant performance degradation.
2356  */
2357 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2358 	((*(sd_iostart_chain[index]))(index, un, bp))
2359 
2360 #define	SD_BEGIN_IODONE(index, un, bp)	\
2361 	((*(sd_iodone_chain[index]))(index, un, bp))
2362 
2363 #define	SD_NEXT_IOSTART(index, un, bp)				\
2364 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2365 
2366 #define	SD_NEXT_IODONE(index, un, bp)				\
2367 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2368 
2369 /*
2370  *    Function: _init
2371  *
2372  * Description: This is the driver _init(9E) entry point.
2373  *
2374  * Return Code: Returns the value from mod_install(9F) or
2375  *		ddi_soft_state_init(9F) as appropriate.
2376  *
2377  *     Context: Called when driver module loaded.
2378  */
2379 
2380 int
2381 _init(void)
2382 {
2383 	int	err;
2384 
2385 	/* establish driver name from module name */
2386 	sd_label = (char *)mod_modname(&modlinkage);
2387 
2388 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2389 	    SD_MAXUNIT);
2390 	if (err != 0) {
2391 		return (err);
2392 	}
2393 
2394 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2395 
2396 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2397 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2398 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2399 
2400 	/*
2401 	 * it's ok to init here even for fibre device
2402 	 */
2403 	sd_scsi_probe_cache_init();
2404 
2405 	sd_scsi_target_lun_init();
2406 
2407 	/*
2408 	 * Creating taskq before mod_install ensures that all callers (threads)
2409 	 * that enter the module after a successful mod_install encounter
2410 	 * a valid taskq.
2411 	 */
2412 	sd_taskq_create();
2413 
2414 	err = mod_install(&modlinkage);
2415 	if (err != 0) {
2416 		/* delete taskq if install fails */
2417 		sd_taskq_delete();
2418 
2419 		mutex_destroy(&sd_log_mutex);
2420 
2421 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2422 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2423 		cv_destroy(&sd_tr.srq_inprocess_cv);
2424 
2425 		sd_scsi_probe_cache_fini();
2426 
2427 		sd_scsi_target_lun_fini();
2428 
2429 		ddi_soft_state_fini(&sd_state);
2430 
2431 		return (err);
2432 	}
2433 
2434 	return (err);
2435 }
2436 
2437 
2438 /*
2439  *    Function: _fini
2440  *
2441  * Description: This is the driver _fini(9E) entry point.
2442  *
2443  * Return Code: Returns the value from mod_remove(9F)
2444  *
2445  *     Context: Called when driver module is unloaded.
2446  */
2447 
2448 int
2449 _fini(void)
2450 {
2451 	int err;
2452 
2453 	if ((err = mod_remove(&modlinkage)) != 0) {
2454 		return (err);
2455 	}
2456 
2457 	sd_taskq_delete();
2458 
2459 	mutex_destroy(&sd_log_mutex);
2460 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2461 
2462 	sd_scsi_probe_cache_fini();
2463 
2464 	sd_scsi_target_lun_fini();
2465 
2466 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2467 	cv_destroy(&sd_tr.srq_inprocess_cv);
2468 
2469 	ddi_soft_state_fini(&sd_state);
2470 
2471 	return (err);
2472 }
2473 
2474 
2475 /*
2476  *    Function: _info
2477  *
2478  * Description: This is the driver _info(9E) entry point.
2479  *
2480  *   Arguments: modinfop - pointer to the driver modinfo structure
2481  *
2482  * Return Code: Returns the value from mod_info(9F).
2483  *
2484  *     Context: Kernel thread context
2485  */
2486 
2487 int
2488 _info(struct modinfo *modinfop)
2489 {
2490 	return (mod_info(&modlinkage, modinfop));
2491 }
2492 
2493 
2494 /*
2495  * The following routines implement the driver message logging facility.
2496  * They provide component- and level- based debug output filtering.
2497  * Output may also be restricted to messages for a single instance by
2498  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2499  * to NULL, then messages for all instances are printed.
2500  *
2501  * These routines have been cloned from each other due to the language
2502  * constraints of macros and variable argument list processing.
2503  */
2504 
2505 
2506 /*
2507  *    Function: sd_log_err
2508  *
2509  * Description: This routine is called by the SD_ERROR macro for debug
2510  *		logging of error conditions.
2511  *
2512  *   Arguments: comp - driver component being logged
2513  *		dev  - pointer to driver info structure
2514  *		fmt  - error string and format to be logged
2515  */
2516 
2517 static void
2518 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2519 {
2520 	va_list		ap;
2521 	dev_info_t	*dev;
2522 
2523 	ASSERT(un != NULL);
2524 	dev = SD_DEVINFO(un);
2525 	ASSERT(dev != NULL);
2526 
2527 	/*
2528 	 * Filter messages based on the global component and level masks.
2529 	 * Also print if un matches the value of sd_debug_un, or if
2530 	 * sd_debug_un is set to NULL.
2531 	 */
2532 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2533 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2534 		mutex_enter(&sd_log_mutex);
2535 		va_start(ap, fmt);
2536 		(void) vsprintf(sd_log_buf, fmt, ap);
2537 		va_end(ap);
2538 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2539 		mutex_exit(&sd_log_mutex);
2540 	}
2541 #ifdef SD_FAULT_INJECTION
2542 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2543 	if (un->sd_injection_mask & comp) {
2544 		mutex_enter(&sd_log_mutex);
2545 		va_start(ap, fmt);
2546 		(void) vsprintf(sd_log_buf, fmt, ap);
2547 		va_end(ap);
2548 		sd_injection_log(sd_log_buf, un);
2549 		mutex_exit(&sd_log_mutex);
2550 	}
2551 #endif
2552 }
2553 
2554 
2555 /*
2556  *    Function: sd_log_info
2557  *
2558  * Description: This routine is called by the SD_INFO macro for debug
2559  *		logging of general purpose informational conditions.
2560  *
2561  *   Arguments: comp - driver component being logged
2562  *		dev  - pointer to driver info structure
2563  *		fmt  - info string and format to be logged
2564  */
2565 
2566 static void
2567 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2568 {
2569 	va_list		ap;
2570 	dev_info_t	*dev;
2571 
2572 	ASSERT(un != NULL);
2573 	dev = SD_DEVINFO(un);
2574 	ASSERT(dev != NULL);
2575 
2576 	/*
2577 	 * Filter messages based on the global component and level masks.
2578 	 * Also print if un matches the value of sd_debug_un, or if
2579 	 * sd_debug_un is set to NULL.
2580 	 */
2581 	if ((sd_component_mask & component) &&
2582 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2583 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2584 		mutex_enter(&sd_log_mutex);
2585 		va_start(ap, fmt);
2586 		(void) vsprintf(sd_log_buf, fmt, ap);
2587 		va_end(ap);
2588 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2589 		mutex_exit(&sd_log_mutex);
2590 	}
2591 #ifdef SD_FAULT_INJECTION
2592 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2593 	if (un->sd_injection_mask & component) {
2594 		mutex_enter(&sd_log_mutex);
2595 		va_start(ap, fmt);
2596 		(void) vsprintf(sd_log_buf, fmt, ap);
2597 		va_end(ap);
2598 		sd_injection_log(sd_log_buf, un);
2599 		mutex_exit(&sd_log_mutex);
2600 	}
2601 #endif
2602 }
2603 
2604 
2605 /*
2606  *    Function: sd_log_trace
2607  *
2608  * Description: This routine is called by the SD_TRACE macro for debug
2609  *		logging of trace conditions (i.e. function entry/exit).
2610  *
2611  *   Arguments: comp - driver component being logged
2612  *		dev  - pointer to driver info structure
2613  *		fmt  - trace string and format to be logged
2614  */
2615 
2616 static void
2617 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2618 {
2619 	va_list		ap;
2620 	dev_info_t	*dev;
2621 
2622 	ASSERT(un != NULL);
2623 	dev = SD_DEVINFO(un);
2624 	ASSERT(dev != NULL);
2625 
2626 	/*
2627 	 * Filter messages based on the global component and level masks.
2628 	 * Also print if un matches the value of sd_debug_un, or if
2629 	 * sd_debug_un is set to NULL.
2630 	 */
2631 	if ((sd_component_mask & component) &&
2632 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2633 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2634 		mutex_enter(&sd_log_mutex);
2635 		va_start(ap, fmt);
2636 		(void) vsprintf(sd_log_buf, fmt, ap);
2637 		va_end(ap);
2638 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2639 		mutex_exit(&sd_log_mutex);
2640 	}
2641 #ifdef SD_FAULT_INJECTION
2642 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2643 	if (un->sd_injection_mask & component) {
2644 		mutex_enter(&sd_log_mutex);
2645 		va_start(ap, fmt);
2646 		(void) vsprintf(sd_log_buf, fmt, ap);
2647 		va_end(ap);
2648 		sd_injection_log(sd_log_buf, un);
2649 		mutex_exit(&sd_log_mutex);
2650 	}
2651 #endif
2652 }
2653 
2654 
2655 /*
2656  *    Function: sdprobe
2657  *
2658  * Description: This is the driver probe(9e) entry point function.
2659  *
2660  *   Arguments: devi - opaque device info handle
2661  *
2662  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2663  *              DDI_PROBE_FAILURE: If the probe failed.
2664  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2665  *				   but may be present in the future.
2666  */
2667 
2668 static int
2669 sdprobe(dev_info_t *devi)
2670 {
2671 	struct scsi_device	*devp;
2672 	int			rval;
2673 	int			instance = ddi_get_instance(devi);
2674 
2675 	/*
2676 	 * if it wasn't for pln, sdprobe could actually be nulldev
2677 	 * in the "__fibre" case.
2678 	 */
2679 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2680 		return (DDI_PROBE_DONTCARE);
2681 	}
2682 
2683 	devp = ddi_get_driver_private(devi);
2684 
2685 	if (devp == NULL) {
2686 		/* Ooops... nexus driver is mis-configured... */
2687 		return (DDI_PROBE_FAILURE);
2688 	}
2689 
2690 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2691 		return (DDI_PROBE_PARTIAL);
2692 	}
2693 
2694 	/*
2695 	 * Call the SCSA utility probe routine to see if we actually
2696 	 * have a target at this SCSI nexus.
2697 	 */
2698 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2699 	case SCSIPROBE_EXISTS:
2700 		switch (devp->sd_inq->inq_dtype) {
2701 		case DTYPE_DIRECT:
2702 			rval = DDI_PROBE_SUCCESS;
2703 			break;
2704 		case DTYPE_RODIRECT:
2705 			/* CDs etc. Can be removable media */
2706 			rval = DDI_PROBE_SUCCESS;
2707 			break;
2708 		case DTYPE_OPTICAL:
2709 			/*
2710 			 * Rewritable optical driver HP115AA
2711 			 * Can also be removable media
2712 			 */
2713 
2714 			/*
2715 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2716 			 * pre solaris 9 sparc sd behavior is required
2717 			 *
2718 			 * If first time through and sd_dtype_optical_bind
2719 			 * has not been set in /etc/system check properties
2720 			 */
2721 
2722 			if (sd_dtype_optical_bind  < 0) {
2723 				sd_dtype_optical_bind = ddi_prop_get_int
2724 				    (DDI_DEV_T_ANY, devi, 0,
2725 				    "optical-device-bind", 1);
2726 			}
2727 
2728 			if (sd_dtype_optical_bind == 0) {
2729 				rval = DDI_PROBE_FAILURE;
2730 			} else {
2731 				rval = DDI_PROBE_SUCCESS;
2732 			}
2733 			break;
2734 
2735 		case DTYPE_NOTPRESENT:
2736 		default:
2737 			rval = DDI_PROBE_FAILURE;
2738 			break;
2739 		}
2740 		break;
2741 	default:
2742 		rval = DDI_PROBE_PARTIAL;
2743 		break;
2744 	}
2745 
2746 	/*
2747 	 * This routine checks for resource allocation prior to freeing,
2748 	 * so it will take care of the "smart probing" case where a
2749 	 * scsi_probe() may or may not have been issued and will *not*
2750 	 * free previously-freed resources.
2751 	 */
2752 	scsi_unprobe(devp);
2753 	return (rval);
2754 }
2755 
2756 
2757 /*
2758  *    Function: sdinfo
2759  *
2760  * Description: This is the driver getinfo(9e) entry point function.
2761  *		Given the device number, return the devinfo pointer from
2762  *		the scsi_device structure or the instance number
2763  *		associated with the dev_t.
2764  *
2765  *   Arguments: dip     - pointer to device info structure
2766  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2767  *			  DDI_INFO_DEVT2INSTANCE)
2768  *		arg     - driver dev_t
2769  *		resultp - user buffer for request response
2770  *
2771  * Return Code: DDI_SUCCESS
2772  *              DDI_FAILURE
2773  */
2774 /* ARGSUSED */
2775 static int
2776 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2777 {
2778 	struct sd_lun	*un;
2779 	dev_t		dev;
2780 	int		instance;
2781 	int		error;
2782 
2783 	switch (infocmd) {
2784 	case DDI_INFO_DEVT2DEVINFO:
2785 		dev = (dev_t)arg;
2786 		instance = SDUNIT(dev);
2787 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2788 			return (DDI_FAILURE);
2789 		}
2790 		*result = (void *) SD_DEVINFO(un);
2791 		error = DDI_SUCCESS;
2792 		break;
2793 	case DDI_INFO_DEVT2INSTANCE:
2794 		dev = (dev_t)arg;
2795 		instance = SDUNIT(dev);
2796 		*result = (void *)(uintptr_t)instance;
2797 		error = DDI_SUCCESS;
2798 		break;
2799 	default:
2800 		error = DDI_FAILURE;
2801 	}
2802 	return (error);
2803 }
2804 
2805 /*
2806  *    Function: sd_prop_op
2807  *
2808  * Description: This is the driver prop_op(9e) entry point function.
2809  *		Return the number of blocks for the partition in question
2810  *		or forward the request to the property facilities.
2811  *
2812  *   Arguments: dev       - device number
2813  *		dip       - pointer to device info structure
2814  *		prop_op   - property operator
2815  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2816  *		name      - pointer to property name
2817  *		valuep    - pointer or address of the user buffer
2818  *		lengthp   - property length
2819  *
2820  * Return Code: DDI_PROP_SUCCESS
2821  *              DDI_PROP_NOT_FOUND
2822  *              DDI_PROP_UNDEFINED
2823  *              DDI_PROP_NO_MEMORY
2824  *              DDI_PROP_BUF_TOO_SMALL
2825  */
2826 
2827 static int
2828 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2829     char *name, caddr_t valuep, int *lengthp)
2830 {
2831 	struct sd_lun	*un;
2832 
2833 	if ((un = ddi_get_soft_state(sd_state, ddi_get_instance(dip))) == NULL)
2834 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2835 		    name, valuep, lengthp));
2836 
2837 	return (cmlb_prop_op(un->un_cmlbhandle,
2838 	    dev, dip, prop_op, mod_flags, name, valuep, lengthp,
2839 	    SDPART(dev), (void *)SD_PATH_DIRECT));
2840 }
2841 
2842 /*
2843  * The following functions are for smart probing:
2844  * sd_scsi_probe_cache_init()
2845  * sd_scsi_probe_cache_fini()
2846  * sd_scsi_clear_probe_cache()
2847  * sd_scsi_probe_with_cache()
2848  */
2849 
2850 /*
2851  *    Function: sd_scsi_probe_cache_init
2852  *
2853  * Description: Initializes the probe response cache mutex and head pointer.
2854  *
2855  *     Context: Kernel thread context
2856  */
2857 
2858 static void
2859 sd_scsi_probe_cache_init(void)
2860 {
2861 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2862 	sd_scsi_probe_cache_head = NULL;
2863 }
2864 
2865 
2866 /*
2867  *    Function: sd_scsi_probe_cache_fini
2868  *
2869  * Description: Frees all resources associated with the probe response cache.
2870  *
2871  *     Context: Kernel thread context
2872  */
2873 
2874 static void
2875 sd_scsi_probe_cache_fini(void)
2876 {
2877 	struct sd_scsi_probe_cache *cp;
2878 	struct sd_scsi_probe_cache *ncp;
2879 
2880 	/* Clean up our smart probing linked list */
2881 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2882 		ncp = cp->next;
2883 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2884 	}
2885 	sd_scsi_probe_cache_head = NULL;
2886 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2887 }
2888 
2889 
2890 /*
2891  *    Function: sd_scsi_clear_probe_cache
2892  *
2893  * Description: This routine clears the probe response cache. This is
2894  *		done when open() returns ENXIO so that when deferred
2895  *		attach is attempted (possibly after a device has been
2896  *		turned on) we will retry the probe. Since we don't know
2897  *		which target we failed to open, we just clear the
2898  *		entire cache.
2899  *
2900  *     Context: Kernel thread context
2901  */
2902 
2903 static void
2904 sd_scsi_clear_probe_cache(void)
2905 {
2906 	struct sd_scsi_probe_cache	*cp;
2907 	int				i;
2908 
2909 	mutex_enter(&sd_scsi_probe_cache_mutex);
2910 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2911 		/*
2912 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2913 		 * force probing to be performed the next time
2914 		 * sd_scsi_probe_with_cache is called.
2915 		 */
2916 		for (i = 0; i < NTARGETS_WIDE; i++) {
2917 			cp->cache[i] = SCSIPROBE_EXISTS;
2918 		}
2919 	}
2920 	mutex_exit(&sd_scsi_probe_cache_mutex);
2921 }
2922 
2923 
2924 /*
2925  *    Function: sd_scsi_probe_with_cache
2926  *
2927  * Description: This routine implements support for a scsi device probe
2928  *		with cache. The driver maintains a cache of the target
2929  *		responses to scsi probes. If we get no response from a
2930  *		target during a probe inquiry, we remember that, and we
2931  *		avoid additional calls to scsi_probe on non-zero LUNs
2932  *		on the same target until the cache is cleared. By doing
2933  *		so we avoid the 1/4 sec selection timeout for nonzero
2934  *		LUNs. lun0 of a target is always probed.
2935  *
2936  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2937  *              waitfunc - indicates what the allocator routines should
2938  *			   do when resources are not available. This value
2939  *			   is passed on to scsi_probe() when that routine
2940  *			   is called.
2941  *
2942  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2943  *		otherwise the value returned by scsi_probe(9F).
2944  *
2945  *     Context: Kernel thread context
2946  */
2947 
2948 static int
2949 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2950 {
2951 	struct sd_scsi_probe_cache	*cp;
2952 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2953 	int		lun, tgt;
2954 
2955 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2956 	    SCSI_ADDR_PROP_LUN, 0);
2957 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2958 	    SCSI_ADDR_PROP_TARGET, -1);
2959 
2960 	/* Make sure caching enabled and target in range */
2961 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2962 		/* do it the old way (no cache) */
2963 		return (scsi_probe(devp, waitfn));
2964 	}
2965 
2966 	mutex_enter(&sd_scsi_probe_cache_mutex);
2967 
2968 	/* Find the cache for this scsi bus instance */
2969 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2970 		if (cp->pdip == pdip) {
2971 			break;
2972 		}
2973 	}
2974 
2975 	/* If we can't find a cache for this pdip, create one */
2976 	if (cp == NULL) {
2977 		int i;
2978 
2979 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
2980 		    KM_SLEEP);
2981 		cp->pdip = pdip;
2982 		cp->next = sd_scsi_probe_cache_head;
2983 		sd_scsi_probe_cache_head = cp;
2984 		for (i = 0; i < NTARGETS_WIDE; i++) {
2985 			cp->cache[i] = SCSIPROBE_EXISTS;
2986 		}
2987 	}
2988 
2989 	mutex_exit(&sd_scsi_probe_cache_mutex);
2990 
2991 	/* Recompute the cache for this target if LUN zero */
2992 	if (lun == 0) {
2993 		cp->cache[tgt] = SCSIPROBE_EXISTS;
2994 	}
2995 
2996 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
2997 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
2998 		return (SCSIPROBE_NORESP);
2999 	}
3000 
3001 	/* Do the actual probe; save & return the result */
3002 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
3003 }
3004 
3005 
3006 /*
3007  *    Function: sd_scsi_target_lun_init
3008  *
3009  * Description: Initializes the attached lun chain mutex and head pointer.
3010  *
3011  *     Context: Kernel thread context
3012  */
3013 
3014 static void
3015 sd_scsi_target_lun_init(void)
3016 {
3017 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
3018 	sd_scsi_target_lun_head = NULL;
3019 }
3020 
3021 
3022 /*
3023  *    Function: sd_scsi_target_lun_fini
3024  *
3025  * Description: Frees all resources associated with the attached lun
3026  *              chain
3027  *
3028  *     Context: Kernel thread context
3029  */
3030 
3031 static void
3032 sd_scsi_target_lun_fini(void)
3033 {
3034 	struct sd_scsi_hba_tgt_lun	*cp;
3035 	struct sd_scsi_hba_tgt_lun	*ncp;
3036 
3037 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
3038 		ncp = cp->next;
3039 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
3040 	}
3041 	sd_scsi_target_lun_head = NULL;
3042 	mutex_destroy(&sd_scsi_target_lun_mutex);
3043 }
3044 
3045 
3046 /*
3047  *    Function: sd_scsi_get_target_lun_count
3048  *
3049  * Description: This routine will check in the attached lun chain to see
3050  *		how many luns are attached on the required SCSI controller
3051  *		and target. Currently, some capabilities like tagged queue
3052  *		are supported per target based by HBA. So all luns in a
3053  *		target have the same capabilities. Based on this assumption,
3054  *		sd should only set these capabilities once per target. This
3055  *		function is called when sd needs to decide how many luns
3056  *		already attached on a target.
3057  *
3058  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
3059  *			  controller device.
3060  *              target	- The target ID on the controller's SCSI bus.
3061  *
3062  * Return Code: The number of luns attached on the required target and
3063  *		controller.
3064  *		-1 if target ID is not in parallel SCSI scope or the given
3065  *		dip is not in the chain.
3066  *
3067  *     Context: Kernel thread context
3068  */
3069 
3070 static int
3071 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
3072 {
3073 	struct sd_scsi_hba_tgt_lun	*cp;
3074 
3075 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
3076 		return (-1);
3077 	}
3078 
3079 	mutex_enter(&sd_scsi_target_lun_mutex);
3080 
3081 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3082 		if (cp->pdip == dip) {
3083 			break;
3084 		}
3085 	}
3086 
3087 	mutex_exit(&sd_scsi_target_lun_mutex);
3088 
3089 	if (cp == NULL) {
3090 		return (-1);
3091 	}
3092 
3093 	return (cp->nlun[target]);
3094 }
3095 
3096 
3097 /*
3098  *    Function: sd_scsi_update_lun_on_target
3099  *
3100  * Description: This routine is used to update the attached lun chain when a
3101  *		lun is attached or detached on a target.
3102  *
3103  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
3104  *                        controller device.
3105  *              target  - The target ID on the controller's SCSI bus.
3106  *		flag	- Indicate the lun is attached or detached.
3107  *
3108  *     Context: Kernel thread context
3109  */
3110 
3111 static void
3112 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
3113 {
3114 	struct sd_scsi_hba_tgt_lun	*cp;
3115 
3116 	mutex_enter(&sd_scsi_target_lun_mutex);
3117 
3118 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
3119 		if (cp->pdip == dip) {
3120 			break;
3121 		}
3122 	}
3123 
3124 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
3125 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
3126 		    KM_SLEEP);
3127 		cp->pdip = dip;
3128 		cp->next = sd_scsi_target_lun_head;
3129 		sd_scsi_target_lun_head = cp;
3130 	}
3131 
3132 	mutex_exit(&sd_scsi_target_lun_mutex);
3133 
3134 	if (cp != NULL) {
3135 		if (flag == SD_SCSI_LUN_ATTACH) {
3136 			cp->nlun[target] ++;
3137 		} else {
3138 			cp->nlun[target] --;
3139 		}
3140 	}
3141 }
3142 
3143 
3144 /*
3145  *    Function: sd_spin_up_unit
3146  *
3147  * Description: Issues the following commands to spin-up the device:
3148  *		START STOP UNIT, and INQUIRY.
3149  *
3150  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3151  *                      structure for this target.
3152  *
3153  * Return Code: 0 - success
3154  *		EIO - failure
3155  *		EACCES - reservation conflict
3156  *
3157  *     Context: Kernel thread context
3158  */
3159 
3160 static int
3161 sd_spin_up_unit(sd_ssc_t *ssc)
3162 {
3163 	size_t	resid		= 0;
3164 	int	has_conflict	= FALSE;
3165 	uchar_t *bufaddr;
3166 	int	status;
3167 	struct sd_lun	*un;
3168 
3169 	ASSERT(ssc != NULL);
3170 	un = ssc->ssc_un;
3171 	ASSERT(un != NULL);
3172 
3173 	/*
3174 	 * Send a throwaway START UNIT command.
3175 	 *
3176 	 * If we fail on this, we don't care presently what precisely
3177 	 * is wrong.  EMC's arrays will also fail this with a check
3178 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
3179 	 * we don't want to fail the attach because it may become
3180 	 * "active" later.
3181 	 * We don't know if power condition is supported or not at
3182 	 * this stage, use START STOP bit.
3183 	 */
3184 	status = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
3185 	    SD_TARGET_START, SD_PATH_DIRECT);
3186 
3187 	if (status != 0) {
3188 		if (status == EACCES)
3189 			has_conflict = TRUE;
3190 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3191 	}
3192 
3193 	/*
3194 	 * Send another INQUIRY command to the target. This is necessary for
3195 	 * non-removable media direct access devices because their INQUIRY data
3196 	 * may not be fully qualified until they are spun up (perhaps via the
3197 	 * START command above).  Note: This seems to be needed for some
3198 	 * legacy devices only.) The INQUIRY command should succeed even if a
3199 	 * Reservation Conflict is present.
3200 	 */
3201 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
3202 
3203 	if (sd_send_scsi_INQUIRY(ssc, bufaddr, SUN_INQSIZE, 0, 0, &resid)
3204 	    != 0) {
3205 		kmem_free(bufaddr, SUN_INQSIZE);
3206 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
3207 		return (EIO);
3208 	}
3209 
3210 	/*
3211 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
3212 	 * Note that this routine does not return a failure here even if the
3213 	 * INQUIRY command did not return any data.  This is a legacy behavior.
3214 	 */
3215 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
3216 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
3217 	}
3218 
3219 	kmem_free(bufaddr, SUN_INQSIZE);
3220 
3221 	/* If we hit a reservation conflict above, tell the caller. */
3222 	if (has_conflict == TRUE) {
3223 		return (EACCES);
3224 	}
3225 
3226 	return (0);
3227 }
3228 
3229 #ifdef _LP64
3230 /*
3231  *    Function: sd_enable_descr_sense
3232  *
3233  * Description: This routine attempts to select descriptor sense format
3234  *		using the Control mode page.  Devices that support 64 bit
3235  *		LBAs (for >2TB luns) should also implement descriptor
3236  *		sense data so we will call this function whenever we see
3237  *		a lun larger than 2TB.  If for some reason the device
3238  *		supports 64 bit LBAs but doesn't support descriptor sense
3239  *		presumably the mode select will fail.  Everything will
3240  *		continue to work normally except that we will not get
3241  *		complete sense data for commands that fail with an LBA
3242  *		larger than 32 bits.
3243  *
3244  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3245  *                      structure for this target.
3246  *
3247  *     Context: Kernel thread context only
3248  */
3249 
3250 static void
3251 sd_enable_descr_sense(sd_ssc_t *ssc)
3252 {
3253 	uchar_t			*header;
3254 	struct mode_control_scsi3 *ctrl_bufp;
3255 	size_t			buflen;
3256 	size_t			bd_len;
3257 	int			status;
3258 	struct sd_lun		*un;
3259 
3260 	ASSERT(ssc != NULL);
3261 	un = ssc->ssc_un;
3262 	ASSERT(un != NULL);
3263 
3264 	/*
3265 	 * Read MODE SENSE page 0xA, Control Mode Page
3266 	 */
3267 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3268 	    sizeof (struct mode_control_scsi3);
3269 	header = kmem_zalloc(buflen, KM_SLEEP);
3270 
3271 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, header, buflen,
3272 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT);
3273 
3274 	if (status != 0) {
3275 		SD_ERROR(SD_LOG_COMMON, un,
3276 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3277 		goto eds_exit;
3278 	}
3279 
3280 	/*
3281 	 * Determine size of Block Descriptors in order to locate
3282 	 * the mode page data. ATAPI devices return 0, SCSI devices
3283 	 * should return MODE_BLK_DESC_LENGTH.
3284 	 */
3285 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3286 
3287 	/* Clear the mode data length field for MODE SELECT */
3288 	((struct mode_header *)header)->length = 0;
3289 
3290 	ctrl_bufp = (struct mode_control_scsi3 *)
3291 	    (header + MODE_HEADER_LENGTH + bd_len);
3292 
3293 	/*
3294 	 * If the page length is smaller than the expected value,
3295 	 * the target device doesn't support D_SENSE. Bail out here.
3296 	 */
3297 	if (ctrl_bufp->mode_page.length <
3298 	    sizeof (struct mode_control_scsi3) - 2) {
3299 		SD_ERROR(SD_LOG_COMMON, un,
3300 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3301 		goto eds_exit;
3302 	}
3303 
3304 	/*
3305 	 * Clear PS bit for MODE SELECT
3306 	 */
3307 	ctrl_bufp->mode_page.ps = 0;
3308 
3309 	/*
3310 	 * Set D_SENSE to enable descriptor sense format.
3311 	 */
3312 	ctrl_bufp->d_sense = 1;
3313 
3314 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3315 
3316 	/*
3317 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3318 	 */
3319 	status = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, header,
3320 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT);
3321 
3322 	if (status != 0) {
3323 		SD_INFO(SD_LOG_COMMON, un,
3324 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3325 	} else {
3326 		kmem_free(header, buflen);
3327 		return;
3328 	}
3329 
3330 eds_exit:
3331 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3332 	kmem_free(header, buflen);
3333 }
3334 
3335 /*
3336  *    Function: sd_reenable_dsense_task
3337  *
3338  * Description: Re-enable descriptor sense after device or bus reset
3339  *
3340  *     Context: Executes in a taskq() thread context
3341  */
3342 static void
3343 sd_reenable_dsense_task(void *arg)
3344 {
3345 	struct	sd_lun	*un = arg;
3346 	sd_ssc_t	*ssc;
3347 
3348 	ASSERT(un != NULL);
3349 
3350 	ssc = sd_ssc_init(un);
3351 	sd_enable_descr_sense(ssc);
3352 	sd_ssc_fini(ssc);
3353 }
3354 #endif /* _LP64 */
3355 
3356 /*
3357  *    Function: sd_set_mmc_caps
3358  *
3359  * Description: This routine determines if the device is MMC compliant and if
3360  *		the device supports CDDA via a mode sense of the CDVD
3361  *		capabilities mode page. Also checks if the device is a
3362  *		dvdram writable device.
3363  *
3364  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
3365  *                      structure for this target.
3366  *
3367  *     Context: Kernel thread context only
3368  */
3369 
3370 static void
3371 sd_set_mmc_caps(sd_ssc_t *ssc)
3372 {
3373 	struct mode_header_grp2		*sense_mhp;
3374 	uchar_t				*sense_page;
3375 	caddr_t				buf;
3376 	int				bd_len;
3377 	int				status;
3378 	struct uscsi_cmd		com;
3379 	int				rtn;
3380 	uchar_t				*out_data_rw, *out_data_hd;
3381 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3382 	uchar_t				*out_data_gesn;
3383 	int				gesn_len;
3384 	struct sd_lun			*un;
3385 
3386 	ASSERT(ssc != NULL);
3387 	un = ssc->ssc_un;
3388 	ASSERT(un != NULL);
3389 
3390 	/*
3391 	 * The flags which will be set in this function are - mmc compliant,
3392 	 * dvdram writable device, cdda support. Initialize them to FALSE
3393 	 * and if a capability is detected - it will be set to TRUE.
3394 	 */
3395 	un->un_f_mmc_cap = FALSE;
3396 	un->un_f_dvdram_writable_device = FALSE;
3397 	un->un_f_cfg_cdda = FALSE;
3398 
3399 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3400 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3401 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3402 
3403 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3404 
3405 	if (status != 0) {
3406 		/* command failed; just return */
3407 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3408 		return;
3409 	}
3410 	/*
3411 	 * If the mode sense request for the CDROM CAPABILITIES
3412 	 * page (0x2A) succeeds the device is assumed to be MMC.
3413 	 */
3414 	un->un_f_mmc_cap = TRUE;
3415 
3416 	/* See if GET STATUS EVENT NOTIFICATION is supported */
3417 	if (un->un_f_mmc_gesn_polling) {
3418 		gesn_len = SD_GESN_HEADER_LEN + SD_GESN_MEDIA_DATA_LEN;
3419 		out_data_gesn = kmem_zalloc(gesn_len, KM_SLEEP);
3420 
3421 		rtn = sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(ssc,
3422 		    out_data_gesn, gesn_len, 1 << SD_GESN_MEDIA_CLASS);
3423 
3424 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3425 
3426 		if ((rtn != 0) || !sd_gesn_media_data_valid(out_data_gesn)) {
3427 			un->un_f_mmc_gesn_polling = FALSE;
3428 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3429 			    "sd_set_mmc_caps: gesn not supported "
3430 			    "%d %x %x %x %x\n", rtn,
3431 			    out_data_gesn[0], out_data_gesn[1],
3432 			    out_data_gesn[2], out_data_gesn[3]);
3433 		}
3434 
3435 		kmem_free(out_data_gesn, gesn_len);
3436 	}
3437 
3438 	/* Get to the page data */
3439 	sense_mhp = (struct mode_header_grp2 *)buf;
3440 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3441 	    sense_mhp->bdesc_length_lo;
3442 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3443 		/*
3444 		 * We did not get back the expected block descriptor
3445 		 * length so we cannot determine if the device supports
3446 		 * CDDA. However, we still indicate the device is MMC
3447 		 * according to the successful response to the page
3448 		 * 0x2A mode sense request.
3449 		 */
3450 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3451 		    "sd_set_mmc_caps: Mode Sense returned "
3452 		    "invalid block descriptor length\n");
3453 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3454 		return;
3455 	}
3456 
3457 	/* See if read CDDA is supported */
3458 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3459 	    bd_len);
3460 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3461 
3462 	/* See if writing DVD RAM is supported. */
3463 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3464 	if (un->un_f_dvdram_writable_device == TRUE) {
3465 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3466 		return;
3467 	}
3468 
3469 	/*
3470 	 * If the device presents DVD or CD capabilities in the mode
3471 	 * page, we can return here since a RRD will not have
3472 	 * these capabilities.
3473 	 */
3474 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3475 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3476 		return;
3477 	}
3478 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3479 
3480 	/*
3481 	 * If un->un_f_dvdram_writable_device is still FALSE,
3482 	 * check for a Removable Rigid Disk (RRD).  A RRD
3483 	 * device is identified by the features RANDOM_WRITABLE and
3484 	 * HARDWARE_DEFECT_MANAGEMENT.
3485 	 */
3486 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3487 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3488 
3489 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3490 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3491 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3492 
3493 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3494 
3495 	if (rtn != 0) {
3496 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3497 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3498 		return;
3499 	}
3500 
3501 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3502 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3503 
3504 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3505 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3506 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3507 
3508 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3509 
3510 	if (rtn == 0) {
3511 		/*
3512 		 * We have good information, check for random writable
3513 		 * and hardware defect features.
3514 		 */
3515 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3516 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3517 			un->un_f_dvdram_writable_device = TRUE;
3518 		}
3519 	}
3520 
3521 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3522 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3523 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3524 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3525 }
3526 
3527 /*
3528  *    Function: sd_check_for_writable_cd
3529  *
3530  * Description: This routine determines if the media in the device is
3531  *		writable or not. It uses the get configuration command (0x46)
3532  *		to determine if the media is writable
3533  *
3534  *   Arguments: un - driver soft state (unit) structure
3535  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3536  *                           chain and the normal command waitq, or
3537  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3538  *                           "direct" chain and bypass the normal command
3539  *                           waitq.
3540  *
3541  *     Context: Never called at interrupt context.
3542  */
3543 
3544 static void
3545 sd_check_for_writable_cd(sd_ssc_t *ssc, int path_flag)
3546 {
3547 	struct uscsi_cmd		com;
3548 	uchar_t				*out_data;
3549 	uchar_t				*rqbuf;
3550 	int				rtn;
3551 	uchar_t				*out_data_rw, *out_data_hd;
3552 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3553 	struct mode_header_grp2		*sense_mhp;
3554 	uchar_t				*sense_page;
3555 	caddr_t				buf;
3556 	int				bd_len;
3557 	int				status;
3558 	struct sd_lun			*un;
3559 
3560 	ASSERT(ssc != NULL);
3561 	un = ssc->ssc_un;
3562 	ASSERT(un != NULL);
3563 	ASSERT(mutex_owned(SD_MUTEX(un)));
3564 
3565 	/*
3566 	 * Initialize the writable media to false, if configuration info.
3567 	 * tells us otherwise then only we will set it.
3568 	 */
3569 	un->un_f_mmc_writable_media = FALSE;
3570 	mutex_exit(SD_MUTEX(un));
3571 
3572 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3573 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3574 
3575 	rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf, SENSE_LENGTH,
3576 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3577 
3578 	if (rtn != 0)
3579 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3580 
3581 	mutex_enter(SD_MUTEX(un));
3582 	if (rtn == 0) {
3583 		/*
3584 		 * We have good information, check for writable DVD.
3585 		 */
3586 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3587 			un->un_f_mmc_writable_media = TRUE;
3588 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3589 			kmem_free(rqbuf, SENSE_LENGTH);
3590 			return;
3591 		}
3592 	}
3593 
3594 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3595 	kmem_free(rqbuf, SENSE_LENGTH);
3596 
3597 	/*
3598 	 * Determine if this is a RRD type device.
3599 	 */
3600 	mutex_exit(SD_MUTEX(un));
3601 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3602 	status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, (uchar_t *)buf,
3603 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3604 
3605 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3606 
3607 	mutex_enter(SD_MUTEX(un));
3608 	if (status != 0) {
3609 		/* command failed; just return */
3610 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3611 		return;
3612 	}
3613 
3614 	/* Get to the page data */
3615 	sense_mhp = (struct mode_header_grp2 *)buf;
3616 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3617 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3618 		/*
3619 		 * We did not get back the expected block descriptor length so
3620 		 * we cannot check the mode page.
3621 		 */
3622 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3623 		    "sd_check_for_writable_cd: Mode Sense returned "
3624 		    "invalid block descriptor length\n");
3625 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3626 		return;
3627 	}
3628 
3629 	/*
3630 	 * If the device presents DVD or CD capabilities in the mode
3631 	 * page, we can return here since a RRD device will not have
3632 	 * these capabilities.
3633 	 */
3634 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3635 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3636 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3637 		return;
3638 	}
3639 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3640 
3641 	/*
3642 	 * If un->un_f_mmc_writable_media is still FALSE,
3643 	 * check for RRD type media.  A RRD device is identified
3644 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3645 	 */
3646 	mutex_exit(SD_MUTEX(un));
3647 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3648 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3649 
3650 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_rw,
3651 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3652 	    RANDOM_WRITABLE, path_flag);
3653 
3654 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3655 	if (rtn != 0) {
3656 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3657 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3658 		mutex_enter(SD_MUTEX(un));
3659 		return;
3660 	}
3661 
3662 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3663 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3664 
3665 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(ssc, &com, rqbuf_hd,
3666 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3667 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3668 
3669 	sd_ssc_assessment(ssc, SD_FMT_IGNORE);
3670 	mutex_enter(SD_MUTEX(un));
3671 	if (rtn == 0) {
3672 		/*
3673 		 * We have good information, check for random writable
3674 		 * and hardware defect features as current.
3675 		 */
3676 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3677 		    (out_data_rw[10] & 0x1) &&
3678 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3679 		    (out_data_hd[10] & 0x1)) {
3680 			un->un_f_mmc_writable_media = TRUE;
3681 		}
3682 	}
3683 
3684 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3685 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3686 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3687 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3688 }
3689 
3690 /*
3691  *    Function: sd_read_unit_properties
3692  *
3693  * Description: The following implements a property lookup mechanism.
3694  *		Properties for particular disks (keyed on vendor, model
3695  *		and rev numbers) are sought in the sd.conf file via
3696  *		sd_process_sdconf_file(), and if not found there, are
3697  *		looked for in a list hardcoded in this driver via
3698  *		sd_process_sdconf_table() Once located the properties
3699  *		are used to update the driver unit structure.
3700  *
3701  *   Arguments: un - driver soft state (unit) structure
3702  */
3703 
3704 static void
3705 sd_read_unit_properties(struct sd_lun *un)
3706 {
3707 	/*
3708 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3709 	 * the "sd-config-list" property (from the sd.conf file) or if
3710 	 * there was not a match for the inquiry vid/pid. If this event
3711 	 * occurs the static driver configuration table is searched for
3712 	 * a match.
3713 	 */
3714 	ASSERT(un != NULL);
3715 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3716 		sd_process_sdconf_table(un);
3717 	}
3718 }
3719 
3720 
3721 /*
3722  *    Function: sd_process_sdconf_file
3723  *
3724  * Description: Use ddi_prop_lookup(9F) to obtain the properties from the
3725  *		driver's config file (ie, sd.conf) and update the driver
3726  *		soft state structure accordingly.
3727  *
3728  *   Arguments: un - driver soft state (unit) structure
3729  *
3730  * Return Code: SD_SUCCESS - The properties were successfully set according
3731  *			     to the driver configuration file.
3732  *		SD_FAILURE - The driver config list was not obtained or
3733  *			     there was no vid/pid match. This indicates that
3734  *			     the static config table should be used.
3735  *
3736  * The config file has a property, "sd-config-list". Currently we support
3737  * two kinds of formats. For both formats, the value of this property
3738  * is a list of duplets:
3739  *
3740  *  sd-config-list=
3741  *	<duplet>,
3742  *	[,<duplet>]*;
3743  *
3744  * For the improved format, where
3745  *
3746  *     <duplet>:= "<vid+pid>","<tunable-list>"
3747  *
3748  * and
3749  *
3750  *     <tunable-list>:=   <tunable> [, <tunable> ]*;
3751  *     <tunable> =        <name> : <value>
3752  *
3753  * The <vid+pid> is the string that is returned by the target device on a
3754  * SCSI inquiry command, the <tunable-list> contains one or more tunables
3755  * to apply to all target devices with the specified <vid+pid>.
3756  *
3757  * Each <tunable> is a "<name> : <value>" pair.
3758  *
3759  * For the old format, the structure of each duplet is as follows:
3760  *
3761  *  <duplet>:= "<vid+pid>","<data-property-name_list>"
3762  *
3763  * The first entry of the duplet is the device ID string (the concatenated
3764  * vid & pid; not to be confused with a device_id).  This is defined in
3765  * the same way as in the sd_disk_table.
3766  *
3767  * The second part of the duplet is a string that identifies a
3768  * data-property-name-list. The data-property-name-list is defined as
3769  * follows:
3770  *
3771  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3772  *
3773  * The syntax of <data-property-name> depends on the <version> field.
3774  *
3775  * If version = SD_CONF_VERSION_1 we have the following syntax:
3776  *
3777  *	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3778  *
3779  * where the prop0 value will be used to set prop0 if bit0 set in the
3780  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3781  *
3782  */
3783 
3784 static int
3785 sd_process_sdconf_file(struct sd_lun *un)
3786 {
3787 	char	**config_list = NULL;
3788 	uint_t	nelements;
3789 	char	*vidptr;
3790 	int	vidlen;
3791 	char	*dnlist_ptr;
3792 	char	*dataname_ptr;
3793 	char	*dataname_lasts;
3794 	int	*data_list = NULL;
3795 	uint_t	data_list_len;
3796 	int	rval = SD_FAILURE;
3797 	int	i;
3798 
3799 	ASSERT(un != NULL);
3800 
3801 	/* Obtain the configuration list associated with the .conf file */
3802 	if (ddi_prop_lookup_string_array(DDI_DEV_T_ANY, SD_DEVINFO(un),
3803 	    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, sd_config_list,
3804 	    &config_list, &nelements) != DDI_PROP_SUCCESS) {
3805 		return (SD_FAILURE);
3806 	}
3807 
3808 	/*
3809 	 * Compare vids in each duplet to the inquiry vid - if a match is
3810 	 * made, get the data value and update the soft state structure
3811 	 * accordingly.
3812 	 *
3813 	 * Each duplet should show as a pair of strings, return SD_FAILURE
3814 	 * otherwise.
3815 	 */
3816 	if (nelements & 1) {
3817 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3818 		    "sd-config-list should show as pairs of strings.\n");
3819 		if (config_list)
3820 			ddi_prop_free(config_list);
3821 		return (SD_FAILURE);
3822 	}
3823 
3824 	for (i = 0; i < nelements; i += 2) {
3825 		/*
3826 		 * Note: The assumption here is that each vid entry is on
3827 		 * a unique line from its associated duplet.
3828 		 */
3829 		vidptr = config_list[i];
3830 		vidlen = (int)strlen(vidptr);
3831 		if (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS) {
3832 			continue;
3833 		}
3834 
3835 		/*
3836 		 * dnlist contains 1 or more blank separated
3837 		 * data-property-name entries
3838 		 */
3839 		dnlist_ptr = config_list[i + 1];
3840 
3841 		if (strchr(dnlist_ptr, ':') != NULL) {
3842 			/*
3843 			 * Decode the improved format sd-config-list.
3844 			 */
3845 			sd_nvpair_str_decode(un, dnlist_ptr);
3846 		} else {
3847 			/*
3848 			 * The old format sd-config-list, loop through all
3849 			 * data-property-name entries in the
3850 			 * data-property-name-list
3851 			 * setting the properties for each.
3852 			 */
3853 			for (dataname_ptr = strtok_r(dnlist_ptr, " \t",
3854 			    &dataname_lasts); dataname_ptr != NULL;
3855 			    dataname_ptr = strtok_r(NULL, " \t",
3856 			    &dataname_lasts)) {
3857 				int version;
3858 
3859 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3860 				    "sd_process_sdconf_file: disk:%s, "
3861 				    "data:%s\n", vidptr, dataname_ptr);
3862 
3863 				/* Get the data list */
3864 				if (ddi_prop_lookup_int_array(DDI_DEV_T_ANY,
3865 				    SD_DEVINFO(un), 0, dataname_ptr, &data_list,
3866 				    &data_list_len) != DDI_PROP_SUCCESS) {
3867 					SD_INFO(SD_LOG_ATTACH_DETACH, un,
3868 					    "sd_process_sdconf_file: data "
3869 					    "property (%s) has no value\n",
3870 					    dataname_ptr);
3871 					continue;
3872 				}
3873 
3874 				version = data_list[0];
3875 
3876 				if (version == SD_CONF_VERSION_1) {
3877 					sd_tunables values;
3878 
3879 					/* Set the properties */
3880 					if (sd_chk_vers1_data(un, data_list[1],
3881 					    &data_list[2], data_list_len,
3882 					    dataname_ptr) == SD_SUCCESS) {
3883 						sd_get_tunables_from_conf(un,
3884 						    data_list[1], &data_list[2],
3885 						    &values);
3886 						sd_set_vers1_properties(un,
3887 						    data_list[1], &values);
3888 						rval = SD_SUCCESS;
3889 					} else {
3890 						rval = SD_FAILURE;
3891 					}
3892 				} else {
3893 					scsi_log(SD_DEVINFO(un), sd_label,
3894 					    CE_WARN, "data property %s version "
3895 					    "0x%x is invalid.",
3896 					    dataname_ptr, version);
3897 					rval = SD_FAILURE;
3898 				}
3899 				if (data_list)
3900 					ddi_prop_free(data_list);
3901 			}
3902 		}
3903 	}
3904 
3905 	/* free up the memory allocated by ddi_prop_lookup_string_array(). */
3906 	if (config_list) {
3907 		ddi_prop_free(config_list);
3908 	}
3909 
3910 	return (rval);
3911 }
3912 
3913 /*
3914  *    Function: sd_nvpair_str_decode()
3915  *
3916  * Description: Parse the improved format sd-config-list to get
3917  *    each entry of tunable, which includes a name-value pair.
3918  *    Then call sd_set_properties() to set the property.
3919  *
3920  *   Arguments: un - driver soft state (unit) structure
3921  *    nvpair_str - the tunable list
3922  */
3923 static void
3924 sd_nvpair_str_decode(struct sd_lun *un, char *nvpair_str)
3925 {
3926 	char	*nv, *name, *value, *token;
3927 	char	*nv_lasts, *v_lasts, *x_lasts;
3928 
3929 	for (nv = strtok_r(nvpair_str, ",", &nv_lasts); nv != NULL;
3930 	    nv = strtok_r(NULL, ",", &nv_lasts)) {
3931 		token = strtok_r(nv, ":", &v_lasts);
3932 		name  = strtok_r(token, " \t", &x_lasts);
3933 		token = strtok_r(NULL, ":", &v_lasts);
3934 		value = strtok_r(token, " \t", &x_lasts);
3935 		if (name == NULL || value == NULL) {
3936 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3937 			    "sd_nvpair_str_decode: "
3938 			    "name or value is not valid!\n");
3939 		} else {
3940 			sd_set_properties(un, name, value);
3941 		}
3942 	}
3943 }
3944 
3945 /*
3946  *    Function: sd_set_properties()
3947  *
3948  * Description: Set device properties based on the improved
3949  *    format sd-config-list.
3950  *
3951  *   Arguments: un - driver soft state (unit) structure
3952  *    name  - supported tunable name
3953  *    value - tunable value
3954  */
3955 static void
3956 sd_set_properties(struct sd_lun *un, char *name, char *value)
3957 {
3958 	char	*endptr = NULL;
3959 	long	val = 0;
3960 
3961 	if (strcasecmp(name, "cache-nonvolatile") == 0) {
3962 		if (strcasecmp(value, "true") == 0) {
3963 			un->un_f_suppress_cache_flush = TRUE;
3964 		} else if (strcasecmp(value, "false") == 0) {
3965 			un->un_f_suppress_cache_flush = FALSE;
3966 		} else {
3967 			goto value_invalid;
3968 		}
3969 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3970 		    "suppress_cache_flush flag set to %d\n",
3971 		    un->un_f_suppress_cache_flush);
3972 		return;
3973 	}
3974 
3975 	if (strcasecmp(name, "controller-type") == 0) {
3976 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3977 			un->un_ctype = val;
3978 		} else {
3979 			goto value_invalid;
3980 		}
3981 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3982 		    "ctype set to %d\n", un->un_ctype);
3983 		return;
3984 	}
3985 
3986 	if (strcasecmp(name, "delay-busy") == 0) {
3987 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
3988 			un->un_busy_timeout = drv_usectohz(val / 1000);
3989 		} else {
3990 			goto value_invalid;
3991 		}
3992 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
3993 		    "busy_timeout set to %d\n", un->un_busy_timeout);
3994 		return;
3995 	}
3996 
3997 	if (strcasecmp(name, "disksort") == 0) {
3998 		if (strcasecmp(value, "true") == 0) {
3999 			un->un_f_disksort_disabled = FALSE;
4000 		} else if (strcasecmp(value, "false") == 0) {
4001 			un->un_f_disksort_disabled = TRUE;
4002 		} else {
4003 			goto value_invalid;
4004 		}
4005 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4006 		    "disksort disabled flag set to %d\n",
4007 		    un->un_f_disksort_disabled);
4008 		return;
4009 	}
4010 
4011 	if (strcasecmp(name, "power-condition") == 0) {
4012 		if (strcasecmp(value, "true") == 0) {
4013 			un->un_f_power_condition_disabled = FALSE;
4014 		} else if (strcasecmp(value, "false") == 0) {
4015 			un->un_f_power_condition_disabled = TRUE;
4016 		} else {
4017 			goto value_invalid;
4018 		}
4019 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4020 		    "power condition disabled flag set to %d\n",
4021 		    un->un_f_power_condition_disabled);
4022 		return;
4023 	}
4024 
4025 	if (strcasecmp(name, "timeout-releasereservation") == 0) {
4026 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4027 			un->un_reserve_release_time = val;
4028 		} else {
4029 			goto value_invalid;
4030 		}
4031 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4032 		    "reservation release timeout set to %d\n",
4033 		    un->un_reserve_release_time);
4034 		return;
4035 	}
4036 
4037 	if (strcasecmp(name, "reset-lun") == 0) {
4038 		if (strcasecmp(value, "true") == 0) {
4039 			un->un_f_lun_reset_enabled = TRUE;
4040 		} else if (strcasecmp(value, "false") == 0) {
4041 			un->un_f_lun_reset_enabled = FALSE;
4042 		} else {
4043 			goto value_invalid;
4044 		}
4045 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4046 		    "lun reset enabled flag set to %d\n",
4047 		    un->un_f_lun_reset_enabled);
4048 		return;
4049 	}
4050 
4051 	if (strcasecmp(name, "retries-busy") == 0) {
4052 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4053 			un->un_busy_retry_count = val;
4054 		} else {
4055 			goto value_invalid;
4056 		}
4057 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4058 		    "busy retry count set to %d\n", un->un_busy_retry_count);
4059 		return;
4060 	}
4061 
4062 	if (strcasecmp(name, "retries-timeout") == 0) {
4063 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4064 			un->un_retry_count = val;
4065 		} else {
4066 			goto value_invalid;
4067 		}
4068 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4069 		    "timeout retry count set to %d\n", un->un_retry_count);
4070 		return;
4071 	}
4072 
4073 	if (strcasecmp(name, "retries-notready") == 0) {
4074 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4075 			un->un_notready_retry_count = val;
4076 		} else {
4077 			goto value_invalid;
4078 		}
4079 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4080 		    "notready retry count set to %d\n",
4081 		    un->un_notready_retry_count);
4082 		return;
4083 	}
4084 
4085 	if (strcasecmp(name, "retries-reset") == 0) {
4086 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4087 			un->un_reset_retry_count = val;
4088 		} else {
4089 			goto value_invalid;
4090 		}
4091 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4092 		    "reset retry count set to %d\n",
4093 		    un->un_reset_retry_count);
4094 		return;
4095 	}
4096 
4097 	if (strcasecmp(name, "throttle-max") == 0) {
4098 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4099 			un->un_saved_throttle = un->un_throttle = val;
4100 		} else {
4101 			goto value_invalid;
4102 		}
4103 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4104 		    "throttle set to %d\n", un->un_throttle);
4105 	}
4106 
4107 	if (strcasecmp(name, "throttle-min") == 0) {
4108 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4109 			un->un_min_throttle = val;
4110 		} else {
4111 			goto value_invalid;
4112 		}
4113 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4114 		    "min throttle set to %d\n", un->un_min_throttle);
4115 	}
4116 
4117 	if (strcasecmp(name, "rmw-type") == 0) {
4118 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4119 			un->un_f_rmw_type = val;
4120 		} else {
4121 			goto value_invalid;
4122 		}
4123 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4124 		    "RMW type set to %d\n", un->un_f_rmw_type);
4125 	}
4126 
4127 	if (strcasecmp(name, "physical-block-size") == 0) {
4128 		if (ddi_strtol(value, &endptr, 0, &val) == 0 &&
4129 		    ISP2(val) && val >= un->un_tgt_blocksize &&
4130 		    val >= un->un_sys_blocksize) {
4131 			un->un_phy_blocksize = val;
4132 		} else {
4133 			goto value_invalid;
4134 		}
4135 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4136 		    "physical block size set to %d\n", un->un_phy_blocksize);
4137 	}
4138 
4139 	if (strcasecmp(name, "retries-victim") == 0) {
4140 		if (ddi_strtol(value, &endptr, 0, &val) == 0) {
4141 			un->un_victim_retry_count = val;
4142 		} else {
4143 			goto value_invalid;
4144 		}
4145 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4146 		    "victim retry count set to %d\n",
4147 		    un->un_victim_retry_count);
4148 		return;
4149 	}
4150 
4151 	/*
4152 	 * Validate the throttle values.
4153 	 * If any of the numbers are invalid, set everything to defaults.
4154 	 */
4155 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4156 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4157 	    (un->un_min_throttle > un->un_throttle)) {
4158 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4159 		un->un_min_throttle = sd_min_throttle;
4160 	}
4161 
4162 	if (strcasecmp(name, "mmc-gesn-polling") == 0) {
4163 		if (strcasecmp(value, "true") == 0) {
4164 			un->un_f_mmc_gesn_polling = TRUE;
4165 		} else if (strcasecmp(value, "false") == 0) {
4166 			un->un_f_mmc_gesn_polling = FALSE;
4167 		} else {
4168 			goto value_invalid;
4169 		}
4170 		SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4171 		    "mmc-gesn-polling set to %d\n",
4172 		    un->un_f_mmc_gesn_polling);
4173 	}
4174 
4175 	return;
4176 
4177 value_invalid:
4178 	SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_set_properties: "
4179 	    "value of prop %s is invalid\n", name);
4180 }
4181 
4182 /*
4183  *    Function: sd_get_tunables_from_conf()
4184  *
4185  *
4186  *    This function reads the data list from the sd.conf file and pulls
4187  *    the values that can have numeric values as arguments and places
4188  *    the values in the appropriate sd_tunables member.
4189  *    Since the order of the data list members varies across platforms
4190  *    This function reads them from the data list in a platform specific
4191  *    order and places them into the correct sd_tunable member that is
4192  *    consistent across all platforms.
4193  */
4194 static void
4195 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
4196     sd_tunables *values)
4197 {
4198 	int i;
4199 	int mask;
4200 
4201 	bzero(values, sizeof (sd_tunables));
4202 
4203 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4204 
4205 		mask = 1 << i;
4206 		if (mask > flags) {
4207 			break;
4208 		}
4209 
4210 		switch (mask & flags) {
4211 		case 0:	/* This mask bit not set in flags */
4212 			continue;
4213 		case SD_CONF_BSET_THROTTLE:
4214 			values->sdt_throttle = data_list[i];
4215 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4216 			    "sd_get_tunables_from_conf: throttle = %d\n",
4217 			    values->sdt_throttle);
4218 			break;
4219 		case SD_CONF_BSET_CTYPE:
4220 			values->sdt_ctype = data_list[i];
4221 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4222 			    "sd_get_tunables_from_conf: ctype = %d\n",
4223 			    values->sdt_ctype);
4224 			break;
4225 		case SD_CONF_BSET_NRR_COUNT:
4226 			values->sdt_not_rdy_retries = data_list[i];
4227 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4228 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
4229 			    values->sdt_not_rdy_retries);
4230 			break;
4231 		case SD_CONF_BSET_BSY_RETRY_COUNT:
4232 			values->sdt_busy_retries = data_list[i];
4233 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4234 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
4235 			    values->sdt_busy_retries);
4236 			break;
4237 		case SD_CONF_BSET_RST_RETRIES:
4238 			values->sdt_reset_retries = data_list[i];
4239 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4240 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
4241 			    values->sdt_reset_retries);
4242 			break;
4243 		case SD_CONF_BSET_RSV_REL_TIME:
4244 			values->sdt_reserv_rel_time = data_list[i];
4245 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4246 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
4247 			    values->sdt_reserv_rel_time);
4248 			break;
4249 		case SD_CONF_BSET_MIN_THROTTLE:
4250 			values->sdt_min_throttle = data_list[i];
4251 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4252 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
4253 			    values->sdt_min_throttle);
4254 			break;
4255 		case SD_CONF_BSET_DISKSORT_DISABLED:
4256 			values->sdt_disk_sort_dis = data_list[i];
4257 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4258 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
4259 			    values->sdt_disk_sort_dis);
4260 			break;
4261 		case SD_CONF_BSET_LUN_RESET_ENABLED:
4262 			values->sdt_lun_reset_enable = data_list[i];
4263 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4264 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
4265 			    "\n", values->sdt_lun_reset_enable);
4266 			break;
4267 		case SD_CONF_BSET_CACHE_IS_NV:
4268 			values->sdt_suppress_cache_flush = data_list[i];
4269 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4270 			    "sd_get_tunables_from_conf: \
4271 			    suppress_cache_flush = %d"
4272 			    "\n", values->sdt_suppress_cache_flush);
4273 			break;
4274 		case SD_CONF_BSET_PC_DISABLED:
4275 			values->sdt_disk_sort_dis = data_list[i];
4276 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4277 			    "sd_get_tunables_from_conf: power_condition_dis = "
4278 			    "%d\n", values->sdt_power_condition_dis);
4279 			break;
4280 		}
4281 	}
4282 }
4283 
4284 /*
4285  *    Function: sd_process_sdconf_table
4286  *
4287  * Description: Search the static configuration table for a match on the
4288  *		inquiry vid/pid and update the driver soft state structure
4289  *		according to the table property values for the device.
4290  *
4291  *		The form of a configuration table entry is:
4292  *		  <vid+pid>,<flags>,<property-data>
4293  *		  "SEAGATE ST42400N",1,0x40000,
4294  *		  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1;
4295  *
4296  *   Arguments: un - driver soft state (unit) structure
4297  */
4298 
4299 static void
4300 sd_process_sdconf_table(struct sd_lun *un)
4301 {
4302 	char	*id = NULL;
4303 	int	table_index;
4304 	int	idlen;
4305 
4306 	ASSERT(un != NULL);
4307 	for (table_index = 0; table_index < sd_disk_table_size;
4308 	    table_index++) {
4309 		id = sd_disk_table[table_index].device_id;
4310 		idlen = strlen(id);
4311 
4312 		/*
4313 		 * The static configuration table currently does not
4314 		 * implement version 10 properties. Additionally,
4315 		 * multiple data-property-name entries are not
4316 		 * implemented in the static configuration table.
4317 		 */
4318 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4319 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4320 			    "sd_process_sdconf_table: disk %s\n", id);
4321 			sd_set_vers1_properties(un,
4322 			    sd_disk_table[table_index].flags,
4323 			    sd_disk_table[table_index].properties);
4324 			break;
4325 		}
4326 	}
4327 }
4328 
4329 
4330 /*
4331  *    Function: sd_sdconf_id_match
4332  *
4333  * Description: This local function implements a case sensitive vid/pid
4334  *		comparison as well as the boundary cases of wild card and
4335  *		multiple blanks.
4336  *
4337  *		Note: An implicit assumption made here is that the scsi
4338  *		inquiry structure will always keep the vid, pid and
4339  *		revision strings in consecutive sequence, so they can be
4340  *		read as a single string. If this assumption is not the
4341  *		case, a separate string, to be used for the check, needs
4342  *		to be built with these strings concatenated.
4343  *
4344  *   Arguments: un - driver soft state (unit) structure
4345  *		id - table or config file vid/pid
4346  *		idlen  - length of the vid/pid (bytes)
4347  *
4348  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4349  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4350  */
4351 
4352 static int
4353 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
4354 {
4355 	struct scsi_inquiry	*sd_inq;
4356 	int			rval = SD_SUCCESS;
4357 
4358 	ASSERT(un != NULL);
4359 	sd_inq = un->un_sd->sd_inq;
4360 	ASSERT(id != NULL);
4361 
4362 	/*
4363 	 * We use the inq_vid as a pointer to a buffer containing the
4364 	 * vid and pid and use the entire vid/pid length of the table
4365 	 * entry for the comparison. This works because the inq_pid
4366 	 * data member follows inq_vid in the scsi_inquiry structure.
4367 	 */
4368 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
4369 		/*
4370 		 * The user id string is compared to the inquiry vid/pid
4371 		 * using a case insensitive comparison and ignoring
4372 		 * multiple spaces.
4373 		 */
4374 		rval = sd_blank_cmp(un, id, idlen);
4375 		if (rval != SD_SUCCESS) {
4376 			/*
4377 			 * User id strings that start and end with a "*"
4378 			 * are a special case. These do not have a
4379 			 * specific vendor, and the product string can
4380 			 * appear anywhere in the 16 byte PID portion of
4381 			 * the inquiry data. This is a simple strstr()
4382 			 * type search for the user id in the inquiry data.
4383 			 */
4384 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
4385 				char	*pidptr = &id[1];
4386 				int	i;
4387 				int	j;
4388 				int	pidstrlen = idlen - 2;
4389 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
4390 				    pidstrlen;
4391 
4392 				if (j < 0) {
4393 					return (SD_FAILURE);
4394 				}
4395 				for (i = 0; i < j; i++) {
4396 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
4397 					    pidptr, pidstrlen) == 0) {
4398 						rval = SD_SUCCESS;
4399 						break;
4400 					}
4401 				}
4402 			}
4403 		}
4404 	}
4405 	return (rval);
4406 }
4407 
4408 
4409 /*
4410  *    Function: sd_blank_cmp
4411  *
4412  * Description: If the id string starts and ends with a space, treat
4413  *		multiple consecutive spaces as equivalent to a single
4414  *		space. For example, this causes a sd_disk_table entry
4415  *		of " NEC CDROM " to match a device's id string of
4416  *		"NEC       CDROM".
4417  *
4418  *		Note: The success exit condition for this routine is if
4419  *		the pointer to the table entry is '\0' and the cnt of
4420  *		the inquiry length is zero. This will happen if the inquiry
4421  *		string returned by the device is padded with spaces to be
4422  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
4423  *		SCSI spec states that the inquiry string is to be padded with
4424  *		spaces.
4425  *
4426  *   Arguments: un - driver soft state (unit) structure
4427  *		id - table or config file vid/pid
4428  *		idlen  - length of the vid/pid (bytes)
4429  *
4430  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
4431  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
4432  */
4433 
4434 static int
4435 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
4436 {
4437 	char		*p1;
4438 	char		*p2;
4439 	int		cnt;
4440 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
4441 	    sizeof (SD_INQUIRY(un)->inq_pid);
4442 
4443 	ASSERT(un != NULL);
4444 	p2 = un->un_sd->sd_inq->inq_vid;
4445 	ASSERT(id != NULL);
4446 	p1 = id;
4447 
4448 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
4449 		/*
4450 		 * Note: string p1 is terminated by a NUL but string p2
4451 		 * isn't.  The end of p2 is determined by cnt.
4452 		 */
4453 		for (;;) {
4454 			/* skip over any extra blanks in both strings */
4455 			while ((*p1 != '\0') && (*p1 == ' ')) {
4456 				p1++;
4457 			}
4458 			while ((cnt != 0) && (*p2 == ' ')) {
4459 				p2++;
4460 				cnt--;
4461 			}
4462 
4463 			/* compare the two strings */
4464 			if ((cnt == 0) ||
4465 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
4466 				break;
4467 			}
4468 			while ((cnt > 0) &&
4469 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
4470 				p1++;
4471 				p2++;
4472 				cnt--;
4473 			}
4474 		}
4475 	}
4476 
4477 	/* return SD_SUCCESS if both strings match */
4478 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
4479 }
4480 
4481 
4482 /*
4483  *    Function: sd_chk_vers1_data
4484  *
4485  * Description: Verify the version 1 device properties provided by the
4486  *		user via the configuration file
4487  *
4488  *   Arguments: un	     - driver soft state (unit) structure
4489  *		flags	     - integer mask indicating properties to be set
4490  *		prop_list    - integer list of property values
4491  *		list_len     - number of the elements
4492  *
4493  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
4494  *		SD_FAILURE - Indicates the user provided data is invalid
4495  */
4496 
4497 static int
4498 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
4499     int list_len, char *dataname_ptr)
4500 {
4501 	int i;
4502 	int mask = 1;
4503 	int index = 0;
4504 
4505 	ASSERT(un != NULL);
4506 
4507 	/* Check for a NULL property name and list */
4508 	if (dataname_ptr == NULL) {
4509 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4510 		    "sd_chk_vers1_data: NULL data property name.");
4511 		return (SD_FAILURE);
4512 	}
4513 	if (prop_list == NULL) {
4514 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4515 		    "sd_chk_vers1_data: %s NULL data property list.",
4516 		    dataname_ptr);
4517 		return (SD_FAILURE);
4518 	}
4519 
4520 	/* Display a warning if undefined bits are set in the flags */
4521 	if (flags & ~SD_CONF_BIT_MASK) {
4522 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4523 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
4524 		    "Properties not set.",
4525 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
4526 		return (SD_FAILURE);
4527 	}
4528 
4529 	/*
4530 	 * Verify the length of the list by identifying the highest bit set
4531 	 * in the flags and validating that the property list has a length
4532 	 * up to the index of this bit.
4533 	 */
4534 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
4535 		if (flags & mask) {
4536 			index++;
4537 		}
4538 		mask = 1 << i;
4539 	}
4540 	if (list_len < (index + 2)) {
4541 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4542 		    "sd_chk_vers1_data: "
4543 		    "Data property list %s size is incorrect. "
4544 		    "Properties not set.", dataname_ptr);
4545 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
4546 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
4547 		return (SD_FAILURE);
4548 	}
4549 	return (SD_SUCCESS);
4550 }
4551 
4552 
4553 /*
4554  *    Function: sd_set_vers1_properties
4555  *
4556  * Description: Set version 1 device properties based on a property list
4557  *		retrieved from the driver configuration file or static
4558  *		configuration table. Version 1 properties have the format:
4559  *
4560  *	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
4561  *
4562  *		where the prop0 value will be used to set prop0 if bit0
4563  *		is set in the flags
4564  *
4565  *   Arguments: un	     - driver soft state (unit) structure
4566  *		flags	     - integer mask indicating properties to be set
4567  *		prop_list    - integer list of property values
4568  */
4569 
4570 static void
4571 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
4572 {
4573 	ASSERT(un != NULL);
4574 
4575 	/*
4576 	 * Set the flag to indicate cache is to be disabled. An attempt
4577 	 * to disable the cache via sd_cache_control() will be made
4578 	 * later during attach once the basic initialization is complete.
4579 	 */
4580 	if (flags & SD_CONF_BSET_NOCACHE) {
4581 		un->un_f_opt_disable_cache = TRUE;
4582 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4583 		    "sd_set_vers1_properties: caching disabled flag set\n");
4584 	}
4585 
4586 	/* CD-specific configuration parameters */
4587 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4588 		un->un_f_cfg_playmsf_bcd = TRUE;
4589 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4590 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4591 	}
4592 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4593 		un->un_f_cfg_readsub_bcd = TRUE;
4594 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4595 		    "sd_set_vers1_properties: readsub_bcd set\n");
4596 	}
4597 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4598 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4599 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4600 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4601 	}
4602 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4603 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4604 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4605 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4606 	}
4607 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4608 		un->un_f_cfg_no_read_header = TRUE;
4609 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4610 		    "sd_set_vers1_properties: no_read_header set\n");
4611 	}
4612 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4613 		un->un_f_cfg_read_cd_xd4 = TRUE;
4614 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4615 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4616 	}
4617 
4618 	/* Support for devices which do not have valid/unique serial numbers */
4619 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4620 		un->un_f_opt_fab_devid = TRUE;
4621 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4622 		    "sd_set_vers1_properties: fab_devid bit set\n");
4623 	}
4624 
4625 	/* Support for user throttle configuration */
4626 	if (flags & SD_CONF_BSET_THROTTLE) {
4627 		ASSERT(prop_list != NULL);
4628 		un->un_saved_throttle = un->un_throttle =
4629 		    prop_list->sdt_throttle;
4630 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4631 		    "sd_set_vers1_properties: throttle set to %d\n",
4632 		    prop_list->sdt_throttle);
4633 	}
4634 
4635 	/* Set the per disk retry count according to the conf file or table. */
4636 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4637 		ASSERT(prop_list != NULL);
4638 		if (prop_list->sdt_not_rdy_retries) {
4639 			un->un_notready_retry_count =
4640 			    prop_list->sdt_not_rdy_retries;
4641 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4642 			    "sd_set_vers1_properties: not ready retry count"
4643 			    " set to %d\n", un->un_notready_retry_count);
4644 		}
4645 	}
4646 
4647 	/* The controller type is reported for generic disk driver ioctls */
4648 	if (flags & SD_CONF_BSET_CTYPE) {
4649 		ASSERT(prop_list != NULL);
4650 		switch (prop_list->sdt_ctype) {
4651 		case CTYPE_CDROM:
4652 			un->un_ctype = prop_list->sdt_ctype;
4653 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4654 			    "sd_set_vers1_properties: ctype set to "
4655 			    "CTYPE_CDROM\n");
4656 			break;
4657 		case CTYPE_CCS:
4658 			un->un_ctype = prop_list->sdt_ctype;
4659 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4660 			    "sd_set_vers1_properties: ctype set to "
4661 			    "CTYPE_CCS\n");
4662 			break;
4663 		case CTYPE_ROD:		/* RW optical */
4664 			un->un_ctype = prop_list->sdt_ctype;
4665 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4666 			    "sd_set_vers1_properties: ctype set to "
4667 			    "CTYPE_ROD\n");
4668 			break;
4669 		default:
4670 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4671 			    "sd_set_vers1_properties: Could not set "
4672 			    "invalid ctype value (%d)",
4673 			    prop_list->sdt_ctype);
4674 		}
4675 	}
4676 
4677 	/* Purple failover timeout */
4678 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4679 		ASSERT(prop_list != NULL);
4680 		un->un_busy_retry_count =
4681 		    prop_list->sdt_busy_retries;
4682 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4683 		    "sd_set_vers1_properties: "
4684 		    "busy retry count set to %d\n",
4685 		    un->un_busy_retry_count);
4686 	}
4687 
4688 	/* Purple reset retry count */
4689 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4690 		ASSERT(prop_list != NULL);
4691 		un->un_reset_retry_count =
4692 		    prop_list->sdt_reset_retries;
4693 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4694 		    "sd_set_vers1_properties: "
4695 		    "reset retry count set to %d\n",
4696 		    un->un_reset_retry_count);
4697 	}
4698 
4699 	/* Purple reservation release timeout */
4700 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4701 		ASSERT(prop_list != NULL);
4702 		un->un_reserve_release_time =
4703 		    prop_list->sdt_reserv_rel_time;
4704 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4705 		    "sd_set_vers1_properties: "
4706 		    "reservation release timeout set to %d\n",
4707 		    un->un_reserve_release_time);
4708 	}
4709 
4710 	/*
4711 	 * Driver flag telling the driver to verify that no commands are pending
4712 	 * for a device before issuing a Test Unit Ready. This is a workaround
4713 	 * for a firmware bug in some Seagate eliteI drives.
4714 	 */
4715 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4716 		un->un_f_cfg_tur_check = TRUE;
4717 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4718 		    "sd_set_vers1_properties: tur queue check set\n");
4719 	}
4720 
4721 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4722 		un->un_min_throttle = prop_list->sdt_min_throttle;
4723 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4724 		    "sd_set_vers1_properties: min throttle set to %d\n",
4725 		    un->un_min_throttle);
4726 	}
4727 
4728 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4729 		un->un_f_disksort_disabled =
4730 		    (prop_list->sdt_disk_sort_dis != 0) ?
4731 		    TRUE : FALSE;
4732 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4733 		    "sd_set_vers1_properties: disksort disabled "
4734 		    "flag set to %d\n",
4735 		    prop_list->sdt_disk_sort_dis);
4736 	}
4737 
4738 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4739 		un->un_f_lun_reset_enabled =
4740 		    (prop_list->sdt_lun_reset_enable != 0) ?
4741 		    TRUE : FALSE;
4742 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4743 		    "sd_set_vers1_properties: lun reset enabled "
4744 		    "flag set to %d\n",
4745 		    prop_list->sdt_lun_reset_enable);
4746 	}
4747 
4748 	if (flags & SD_CONF_BSET_CACHE_IS_NV) {
4749 		un->un_f_suppress_cache_flush =
4750 		    (prop_list->sdt_suppress_cache_flush != 0) ?
4751 		    TRUE : FALSE;
4752 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4753 		    "sd_set_vers1_properties: suppress_cache_flush "
4754 		    "flag set to %d\n",
4755 		    prop_list->sdt_suppress_cache_flush);
4756 	}
4757 
4758 	if (flags & SD_CONF_BSET_PC_DISABLED) {
4759 		un->un_f_power_condition_disabled =
4760 		    (prop_list->sdt_power_condition_dis != 0) ?
4761 		    TRUE : FALSE;
4762 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4763 		    "sd_set_vers1_properties: power_condition_disabled "
4764 		    "flag set to %d\n",
4765 		    prop_list->sdt_power_condition_dis);
4766 	}
4767 
4768 	/*
4769 	 * Validate the throttle values.
4770 	 * If any of the numbers are invalid, set everything to defaults.
4771 	 */
4772 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4773 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4774 	    (un->un_min_throttle > un->un_throttle)) {
4775 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4776 		un->un_min_throttle = sd_min_throttle;
4777 	}
4778 }
4779 
4780 /*
4781  *    Function: sd_get_physical_geometry
4782  *
4783  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4784  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4785  *		target, and use this information to initialize the physical
4786  *		geometry cache specified by pgeom_p.
4787  *
4788  *		MODE SENSE is an optional command, so failure in this case
4789  *		does not necessarily denote an error. We want to use the
4790  *		MODE SENSE commands to derive the physical geometry of the
4791  *		device, but if either command fails, the logical geometry is
4792  *		used as the fallback for disk label geometry in cmlb.
4793  *
4794  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4795  *		have already been initialized for the current target and
4796  *		that the current values be passed as args so that we don't
4797  *		end up ever trying to use -1 as a valid value. This could
4798  *		happen if either value is reset while we're not holding
4799  *		the mutex.
4800  *
4801  *   Arguments: un - driver soft state (unit) structure
4802  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4803  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4804  *			to use the USCSI "direct" chain and bypass the normal
4805  *			command waitq.
4806  *
4807  *     Context: Kernel thread only (can sleep).
4808  */
4809 
4810 static int
4811 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4812     diskaddr_t capacity, int lbasize, int path_flag)
4813 {
4814 	struct	mode_format	*page3p;
4815 	struct	mode_geometry	*page4p;
4816 	struct	mode_header	*headerp;
4817 	int	sector_size;
4818 	int	nsect;
4819 	int	nhead;
4820 	int	ncyl;
4821 	int	intrlv;
4822 	int	spc;
4823 	diskaddr_t	modesense_capacity;
4824 	int	rpm;
4825 	int	bd_len;
4826 	int	mode_header_length;
4827 	uchar_t	*p3bufp;
4828 	uchar_t	*p4bufp;
4829 	int	cdbsize;
4830 	int	ret = EIO;
4831 	sd_ssc_t *ssc;
4832 	int	status;
4833 
4834 	ASSERT(un != NULL);
4835 
4836 	if (lbasize == 0) {
4837 		if (ISCD(un)) {
4838 			lbasize = 2048;
4839 		} else {
4840 			lbasize = un->un_sys_blocksize;
4841 		}
4842 	}
4843 	pgeom_p->g_secsize = (unsigned short)lbasize;
4844 
4845 	/*
4846 	 * If the unit is a cd/dvd drive MODE SENSE page three
4847 	 * and MODE SENSE page four are reserved (see SBC spec
4848 	 * and MMC spec). To prevent soft errors just return
4849 	 * using the default LBA size.
4850 	 *
4851 	 * Since SATA MODE SENSE function (sata_txlt_mode_sense()) does not
4852 	 * implement support for mode pages 3 and 4 return here to prevent
4853 	 * illegal requests on SATA drives.
4854 	 *
4855 	 * These pages are also reserved in SBC-2 and later.  We assume SBC-2
4856 	 * or later for a direct-attached block device if the SCSI version is
4857 	 * at least SPC-3.
4858 	 */
4859 
4860 	if (ISCD(un) ||
4861 	    un->un_interconnect_type == SD_INTERCONNECT_SATA ||
4862 	    (un->un_ctype == CTYPE_CCS && SD_INQUIRY(un)->inq_ansi >= 5))
4863 		return (ret);
4864 
4865 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4866 
4867 	/*
4868 	 * Retrieve MODE SENSE page 3 - Format Device Page
4869 	 */
4870 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4871 	ssc = sd_ssc_init(un);
4872 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p3bufp,
4873 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag);
4874 	if (status != 0) {
4875 		SD_ERROR(SD_LOG_COMMON, un,
4876 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4877 		goto page3_exit;
4878 	}
4879 
4880 	/*
4881 	 * Determine size of Block Descriptors in order to locate the mode
4882 	 * page data.  ATAPI devices return 0, SCSI devices should return
4883 	 * MODE_BLK_DESC_LENGTH.
4884 	 */
4885 	headerp = (struct mode_header *)p3bufp;
4886 	if (un->un_f_cfg_is_atapi == TRUE) {
4887 		struct mode_header_grp2 *mhp =
4888 		    (struct mode_header_grp2 *)headerp;
4889 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4890 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4891 	} else {
4892 		mode_header_length = MODE_HEADER_LENGTH;
4893 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4894 	}
4895 
4896 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4897 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4898 		    "sd_get_physical_geometry: received unexpected bd_len "
4899 		    "of %d, page3\n", bd_len);
4900 		status = EIO;
4901 		goto page3_exit;
4902 	}
4903 
4904 	page3p = (struct mode_format *)
4905 	    ((caddr_t)headerp + mode_header_length + bd_len);
4906 
4907 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4908 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4909 		    "sd_get_physical_geometry: mode sense pg3 code mismatch "
4910 		    "%d\n", page3p->mode_page.code);
4911 		status = EIO;
4912 		goto page3_exit;
4913 	}
4914 
4915 	/*
4916 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4917 	 * complete successfully; otherwise, revert to the logical geometry.
4918 	 * So, we need to save everything in temporary variables.
4919 	 */
4920 	sector_size = BE_16(page3p->data_bytes_sect);
4921 
4922 	/*
4923 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4924 	 */
4925 	if (sector_size == 0) {
4926 		sector_size = un->un_sys_blocksize;
4927 	} else {
4928 		sector_size &= ~(un->un_sys_blocksize - 1);
4929 	}
4930 
4931 	nsect  = BE_16(page3p->sect_track);
4932 	intrlv = BE_16(page3p->interleave);
4933 
4934 	SD_INFO(SD_LOG_COMMON, un,
4935 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
4936 	SD_INFO(SD_LOG_COMMON, un,
4937 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
4938 	    page3p->mode_page.code, nsect, sector_size);
4939 	SD_INFO(SD_LOG_COMMON, un,
4940 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
4941 	    BE_16(page3p->track_skew),
4942 	    BE_16(page3p->cylinder_skew));
4943 
4944 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
4945 
4946 	/*
4947 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
4948 	 */
4949 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
4950 	status = sd_send_scsi_MODE_SENSE(ssc, cdbsize, p4bufp,
4951 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag);
4952 	if (status != 0) {
4953 		SD_ERROR(SD_LOG_COMMON, un,
4954 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
4955 		goto page4_exit;
4956 	}
4957 
4958 	/*
4959 	 * Determine size of Block Descriptors in order to locate the mode
4960 	 * page data.  ATAPI devices return 0, SCSI devices should return
4961 	 * MODE_BLK_DESC_LENGTH.
4962 	 */
4963 	headerp = (struct mode_header *)p4bufp;
4964 	if (un->un_f_cfg_is_atapi == TRUE) {
4965 		struct mode_header_grp2 *mhp =
4966 		    (struct mode_header_grp2 *)headerp;
4967 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4968 	} else {
4969 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4970 	}
4971 
4972 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4973 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4974 		    "sd_get_physical_geometry: received unexpected bd_len of "
4975 		    "%d, page4\n", bd_len);
4976 		status = EIO;
4977 		goto page4_exit;
4978 	}
4979 
4980 	page4p = (struct mode_geometry *)
4981 	    ((caddr_t)headerp + mode_header_length + bd_len);
4982 
4983 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
4984 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
4985 		    "sd_get_physical_geometry: mode sense pg4 code mismatch "
4986 		    "%d\n", page4p->mode_page.code);
4987 		status = EIO;
4988 		goto page4_exit;
4989 	}
4990 
4991 	/*
4992 	 * Stash the data now, after we know that both commands completed.
4993 	 */
4994 
4995 
4996 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
4997 	spc   = nhead * nsect;
4998 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
4999 	rpm   = BE_16(page4p->rpm);
5000 
5001 	modesense_capacity = spc * ncyl;
5002 
5003 	SD_INFO(SD_LOG_COMMON, un,
5004 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
5005 	SD_INFO(SD_LOG_COMMON, un,
5006 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
5007 	SD_INFO(SD_LOG_COMMON, un,
5008 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
5009 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
5010 	    (void *)pgeom_p, capacity);
5011 
5012 	/*
5013 	 * Compensate if the drive's geometry is not rectangular, i.e.,
5014 	 * the product of C * H * S returned by MODE SENSE >= that returned
5015 	 * by read capacity. This is an idiosyncrasy of the original x86
5016 	 * disk subsystem.
5017 	 */
5018 	if (modesense_capacity >= capacity) {
5019 		SD_INFO(SD_LOG_COMMON, un,
5020 		    "sd_get_physical_geometry: adjusting acyl; "
5021 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
5022 		    (modesense_capacity - capacity + spc - 1) / spc);
5023 		if (sector_size != 0) {
5024 			/* 1243403: NEC D38x7 drives don't support sec size */
5025 			pgeom_p->g_secsize = (unsigned short)sector_size;
5026 		}
5027 		pgeom_p->g_nsect    = (unsigned short)nsect;
5028 		pgeom_p->g_nhead    = (unsigned short)nhead;
5029 		pgeom_p->g_capacity = capacity;
5030 		pgeom_p->g_acyl	    =
5031 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
5032 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
5033 	}
5034 
5035 	pgeom_p->g_rpm    = (unsigned short)rpm;
5036 	pgeom_p->g_intrlv = (unsigned short)intrlv;
5037 	ret = 0;
5038 
5039 	SD_INFO(SD_LOG_COMMON, un,
5040 	    "sd_get_physical_geometry: mode sense geometry:\n");
5041 	SD_INFO(SD_LOG_COMMON, un,
5042 	    "   nsect: %d; sector size: %d; interlv: %d\n",
5043 	    nsect, sector_size, intrlv);
5044 	SD_INFO(SD_LOG_COMMON, un,
5045 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
5046 	    nhead, ncyl, rpm, modesense_capacity);
5047 	SD_INFO(SD_LOG_COMMON, un,
5048 	    "sd_get_physical_geometry: (cached)\n");
5049 	SD_INFO(SD_LOG_COMMON, un,
5050 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
5051 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
5052 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
5053 	SD_INFO(SD_LOG_COMMON, un,
5054 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
5055 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
5056 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
5057 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
5058 
5059 page4_exit:
5060 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
5061 
5062 page3_exit:
5063 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
5064 
5065 	if (status != 0) {
5066 		if (status == EIO) {
5067 			/*
5068 			 * Some disks do not support mode sense(6), we
5069 			 * should ignore this kind of error(sense key is
5070 			 * 0x5 - illegal request).
5071 			 */
5072 			uint8_t *sensep;
5073 			int senlen;
5074 
5075 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
5076 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
5077 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
5078 
5079 			if (senlen > 0 &&
5080 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
5081 				sd_ssc_assessment(ssc,
5082 				    SD_FMT_IGNORE_COMPROMISE);
5083 			} else {
5084 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
5085 			}
5086 		} else {
5087 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5088 		}
5089 	}
5090 	sd_ssc_fini(ssc);
5091 	return (ret);
5092 }
5093 
5094 /*
5095  *    Function: sd_get_virtual_geometry
5096  *
5097  * Description: Ask the controller to tell us about the target device.
5098  *
5099  *   Arguments: un - pointer to softstate
5100  *		capacity - disk capacity in #blocks
5101  *		lbasize - disk block size in bytes
5102  *
5103  *     Context: Kernel thread only
5104  */
5105 
5106 static int
5107 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
5108     diskaddr_t capacity, int lbasize)
5109 {
5110 	uint_t	geombuf;
5111 	int	spc;
5112 
5113 	ASSERT(un != NULL);
5114 
5115 	/* Set sector size, and total number of sectors */
5116 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
5117 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
5118 
5119 	/* Let the HBA tell us its geometry */
5120 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
5121 
5122 	/* A value of -1 indicates an undefined "geometry" property */
5123 	if (geombuf == (-1)) {
5124 		return (EINVAL);
5125 	}
5126 
5127 	/* Initialize the logical geometry cache. */
5128 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
5129 	lgeom_p->g_nsect   = geombuf & 0xffff;
5130 	lgeom_p->g_secsize = un->un_sys_blocksize;
5131 
5132 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
5133 
5134 	/*
5135 	 * Note: The driver originally converted the capacity value from
5136 	 * target blocks to system blocks. However, the capacity value passed
5137 	 * to this routine is already in terms of system blocks (this scaling
5138 	 * is done when the READ CAPACITY command is issued and processed).
5139 	 * This 'error' may have gone undetected because the usage of g_ncyl
5140 	 * (which is based upon g_capacity) is very limited within the driver
5141 	 */
5142 	lgeom_p->g_capacity = capacity;
5143 
5144 	/*
5145 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
5146 	 * hba may return zero values if the device has been removed.
5147 	 */
5148 	if (spc == 0) {
5149 		lgeom_p->g_ncyl = 0;
5150 	} else {
5151 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
5152 	}
5153 	lgeom_p->g_acyl = 0;
5154 
5155 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
5156 	return (0);
5157 
5158 }
5159 /*
5160  *    Function: sd_update_block_info
5161  *
5162  * Description: Calculate a byte count to sector count bitshift value
5163  *		from sector size.
5164  *
5165  *   Arguments: un: unit struct.
5166  *		lbasize: new target sector size
5167  *		capacity: new target capacity, ie. block count
5168  *
5169  *     Context: Kernel thread context
5170  */
5171 
5172 static void
5173 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
5174 {
5175 	if (lbasize != 0) {
5176 		un->un_tgt_blocksize = lbasize;
5177 		un->un_f_tgt_blocksize_is_valid = TRUE;
5178 		if (!un->un_f_has_removable_media) {
5179 			un->un_sys_blocksize = lbasize;
5180 		}
5181 	}
5182 
5183 	if (capacity != 0) {
5184 		un->un_blockcount		= capacity;
5185 		un->un_f_blockcount_is_valid	= TRUE;
5186 
5187 		/*
5188 		 * The capacity has changed so update the errstats.
5189 		 */
5190 		if (un->un_errstats != NULL) {
5191 			struct sd_errstats *stp;
5192 
5193 			capacity *= un->un_sys_blocksize;
5194 			stp = (struct sd_errstats *)un->un_errstats->ks_data;
5195 			if (stp->sd_capacity.value.ui64 < capacity)
5196 				stp->sd_capacity.value.ui64 = capacity;
5197 		}
5198 	}
5199 }
5200 
5201 /*
5202  * Parses the SCSI Block Limits VPD page (0xB0). It's legal to pass NULL for
5203  * vpd_pg, in which case all the block limits will be reset to the defaults.
5204  */
5205 static void
5206 sd_parse_blk_limits_vpd(struct sd_lun *un, uchar_t *vpd_pg)
5207 {
5208 	sd_blk_limits_t *lim = &un->un_blk_lim;
5209 	unsigned pg_len;
5210 
5211 	if (vpd_pg != NULL)
5212 		pg_len = BE_IN16(&vpd_pg[2]);
5213 	else
5214 		pg_len = 0;
5215 
5216 	/* Block Limits VPD can be 16 bytes or 64 bytes long - support both */
5217 	if (pg_len >= 0x10) {
5218 		lim->lim_opt_xfer_len_gran = BE_IN16(&vpd_pg[6]);
5219 		lim->lim_max_xfer_len = BE_IN32(&vpd_pg[8]);
5220 		lim->lim_opt_xfer_len = BE_IN32(&vpd_pg[12]);
5221 
5222 		/* Zero means not reported, so use "unlimited" */
5223 		if (lim->lim_max_xfer_len == 0)
5224 			lim->lim_max_xfer_len = UINT32_MAX;
5225 		if (lim->lim_opt_xfer_len == 0)
5226 			lim->lim_opt_xfer_len = UINT32_MAX;
5227 	} else {
5228 		lim->lim_opt_xfer_len_gran = 0;
5229 		lim->lim_max_xfer_len = UINT32_MAX;
5230 		lim->lim_opt_xfer_len = UINT32_MAX;
5231 	}
5232 	if (pg_len >= 0x3c) {
5233 		lim->lim_max_pfetch_len = BE_IN32(&vpd_pg[16]);
5234 		/*
5235 		 * A zero in either of the following two fields indicates lack
5236 		 * of UNMAP support.
5237 		 */
5238 		lim->lim_max_unmap_lba_cnt = BE_IN32(&vpd_pg[20]);
5239 		lim->lim_max_unmap_descr_cnt = BE_IN32(&vpd_pg[24]);
5240 		lim->lim_opt_unmap_gran = BE_IN32(&vpd_pg[28]);
5241 		if ((vpd_pg[32] >> 7) == 1) {
5242 			lim->lim_unmap_gran_align =
5243 			    ((vpd_pg[32] & 0x7f) << 24) | (vpd_pg[33] << 16) |
5244 			    (vpd_pg[34] << 8) | vpd_pg[35];
5245 		} else {
5246 			lim->lim_unmap_gran_align = 0;
5247 		}
5248 		lim->lim_max_write_same_len = BE_IN64(&vpd_pg[36]);
5249 	} else {
5250 		lim->lim_max_pfetch_len = UINT32_MAX;
5251 		lim->lim_max_unmap_lba_cnt = UINT32_MAX;
5252 		lim->lim_max_unmap_descr_cnt = SD_UNMAP_MAX_DESCR;
5253 		lim->lim_opt_unmap_gran = 0;
5254 		lim->lim_unmap_gran_align = 0;
5255 		lim->lim_max_write_same_len = UINT64_MAX;
5256 	}
5257 }
5258 
5259 /*
5260  * Collects VPD page B0 data if available (block limits). If the data is
5261  * not available or querying the device failed, we revert to the defaults.
5262  */
5263 static void
5264 sd_setup_blk_limits(sd_ssc_t *ssc)
5265 {
5266 	struct sd_lun	*un		= ssc->ssc_un;
5267 	uchar_t		*inqB0		= NULL;
5268 	size_t		inqB0_resid	= 0;
5269 	int		rval;
5270 
5271 	if (un->un_vpd_page_mask & SD_VPD_BLK_LIMITS_PG) {
5272 		inqB0 = kmem_zalloc(MAX_INQUIRY_SIZE, KM_SLEEP);
5273 		rval = sd_send_scsi_INQUIRY(ssc, inqB0, MAX_INQUIRY_SIZE, 0x01,
5274 		    0xB0, &inqB0_resid);
5275 		if (rval != 0) {
5276 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5277 			kmem_free(inqB0, MAX_INQUIRY_SIZE);
5278 			inqB0 = NULL;
5279 		}
5280 	}
5281 	/* passing NULL inqB0 will reset to defaults */
5282 	sd_parse_blk_limits_vpd(ssc->ssc_un, inqB0);
5283 	if (inqB0)
5284 		kmem_free(inqB0, MAX_INQUIRY_SIZE);
5285 }
5286 
5287 /*
5288  *    Function: sd_register_devid
5289  *
5290  * Description: This routine will obtain the device id information from the
5291  *		target, obtain the serial number, and register the device
5292  *		id with the ddi framework.
5293  *
5294  *   Arguments: devi - the system's dev_info_t for the device.
5295  *		un - driver soft state (unit) structure
5296  *		reservation_flag - indicates if a reservation conflict
5297  *		occurred during attach
5298  *
5299  *     Context: Kernel Thread
5300  */
5301 static void
5302 sd_register_devid(sd_ssc_t *ssc, dev_info_t *devi, int reservation_flag)
5303 {
5304 	int		rval		= 0;
5305 	uchar_t		*inq80		= NULL;
5306 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
5307 	size_t		inq80_resid	= 0;
5308 	uchar_t		*inq83		= NULL;
5309 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
5310 	size_t		inq83_resid	= 0;
5311 	int		dlen, len;
5312 	char		*sn;
5313 	struct sd_lun	*un;
5314 
5315 	ASSERT(ssc != NULL);
5316 	un = ssc->ssc_un;
5317 	ASSERT(un != NULL);
5318 	ASSERT(mutex_owned(SD_MUTEX(un)));
5319 	ASSERT((SD_DEVINFO(un)) == devi);
5320 
5321 
5322 	/*
5323 	 * We check the availability of the World Wide Name (0x83) and Unit
5324 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
5325 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
5326 	 * 0x83 is available, that is the best choice.  Our next choice is
5327 	 * 0x80.  If neither are available, we munge the devid from the device
5328 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
5329 	 * to fabricate a devid for non-Sun qualified disks.
5330 	 */
5331 	if (sd_check_vpd_page_support(ssc) == 0) {
5332 		/* collect page 80 data if available */
5333 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
5334 
5335 			mutex_exit(SD_MUTEX(un));
5336 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
5337 
5338 			rval = sd_send_scsi_INQUIRY(ssc, inq80, inq80_len,
5339 			    0x01, 0x80, &inq80_resid);
5340 
5341 			if (rval != 0) {
5342 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5343 				kmem_free(inq80, inq80_len);
5344 				inq80 = NULL;
5345 				inq80_len = 0;
5346 			} else if (ddi_prop_exists(
5347 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
5348 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
5349 			    INQUIRY_SERIAL_NO) == 0) {
5350 				/*
5351 				 * If we don't already have a serial number
5352 				 * property, do quick verify of data returned
5353 				 * and define property.
5354 				 */
5355 				dlen = inq80_len - inq80_resid;
5356 				len = (size_t)inq80[3];
5357 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
5358 					/*
5359 					 * Ensure sn termination, skip leading
5360 					 * blanks, and create property
5361 					 * 'inquiry-serial-no'.
5362 					 */
5363 					sn = (char *)&inq80[4];
5364 					sn[len] = 0;
5365 					while (*sn && (*sn == ' '))
5366 						sn++;
5367 					if (*sn) {
5368 						(void) ddi_prop_update_string(
5369 						    DDI_DEV_T_NONE,
5370 						    SD_DEVINFO(un),
5371 						    INQUIRY_SERIAL_NO, sn);
5372 					}
5373 				}
5374 			}
5375 			mutex_enter(SD_MUTEX(un));
5376 		}
5377 
5378 		/* collect page 83 data if available */
5379 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
5380 			mutex_exit(SD_MUTEX(un));
5381 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
5382 
5383 			rval = sd_send_scsi_INQUIRY(ssc, inq83, inq83_len,
5384 			    0x01, 0x83, &inq83_resid);
5385 
5386 			if (rval != 0) {
5387 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5388 				kmem_free(inq83, inq83_len);
5389 				inq83 = NULL;
5390 				inq83_len = 0;
5391 			}
5392 			mutex_enter(SD_MUTEX(un));
5393 		}
5394 	}
5395 
5396 	/*
5397 	 * If transport has already registered a devid for this target
5398 	 * then that takes precedence over the driver's determination
5399 	 * of the devid.
5400 	 *
5401 	 * NOTE: The reason this check is done here instead of at the beginning
5402 	 * of the function is to allow the code above to create the
5403 	 * 'inquiry-serial-no' property.
5404 	 */
5405 	if (ddi_devid_get(SD_DEVINFO(un), &un->un_devid) == DDI_SUCCESS) {
5406 		ASSERT(un->un_devid);
5407 		un->un_f_devid_transport_defined = TRUE;
5408 		goto cleanup; /* use devid registered by the transport */
5409 	}
5410 
5411 	/*
5412 	 * This is the case of antiquated Sun disk drives that have the
5413 	 * FAB_DEVID property set in the disk_table.  These drives
5414 	 * manage the devid's by storing them in last 2 available sectors
5415 	 * on the drive and have them fabricated by the ddi layer by calling
5416 	 * ddi_devid_init and passing the DEVID_FAB flag.
5417 	 */
5418 	if (un->un_f_opt_fab_devid == TRUE) {
5419 		/*
5420 		 * Depending on EINVAL isn't reliable, since a reserved disk
5421 		 * may result in invalid geometry, so check to make sure a
5422 		 * reservation conflict did not occur during attach.
5423 		 */
5424 		if ((sd_get_devid(ssc) == EINVAL) &&
5425 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
5426 			/*
5427 			 * The devid is invalid AND there is no reservation
5428 			 * conflict.  Fabricate a new devid.
5429 			 */
5430 			(void) sd_create_devid(ssc);
5431 		}
5432 
5433 		/* Register the devid if it exists */
5434 		if (un->un_devid != NULL) {
5435 			(void) ddi_devid_register(SD_DEVINFO(un),
5436 			    un->un_devid);
5437 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5438 			    "sd_register_devid: Devid Fabricated\n");
5439 		}
5440 		goto cleanup;
5441 	}
5442 
5443 	/* encode best devid possible based on data available */
5444 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
5445 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
5446 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
5447 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
5448 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
5449 
5450 		/* devid successfully encoded, register devid */
5451 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
5452 
5453 	} else {
5454 		/*
5455 		 * Unable to encode a devid based on data available.
5456 		 * This is not a Sun qualified disk.  Older Sun disk
5457 		 * drives that have the SD_FAB_DEVID property
5458 		 * set in the disk_table and non Sun qualified
5459 		 * disks are treated in the same manner.  These
5460 		 * drives manage the devid's by storing them in
5461 		 * last 2 available sectors on the drive and
5462 		 * have them fabricated by the ddi layer by
5463 		 * calling ddi_devid_init and passing the
5464 		 * DEVID_FAB flag.
5465 		 * Create a fabricate devid only if there's no
5466 		 * fabricate devid existed.
5467 		 */
5468 		if (sd_get_devid(ssc) == EINVAL) {
5469 			(void) sd_create_devid(ssc);
5470 		}
5471 		un->un_f_opt_fab_devid = TRUE;
5472 
5473 		/* Register the devid if it exists */
5474 		if (un->un_devid != NULL) {
5475 			(void) ddi_devid_register(SD_DEVINFO(un),
5476 			    un->un_devid);
5477 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
5478 			    "sd_register_devid: devid fabricated using "
5479 			    "ddi framework\n");
5480 		}
5481 	}
5482 
5483 cleanup:
5484 	/* clean up resources */
5485 	if (inq80 != NULL) {
5486 		kmem_free(inq80, inq80_len);
5487 	}
5488 	if (inq83 != NULL) {
5489 		kmem_free(inq83, inq83_len);
5490 	}
5491 }
5492 
5493 
5494 
5495 /*
5496  *    Function: sd_get_devid
5497  *
5498  * Description: This routine will return 0 if a valid device id has been
5499  *		obtained from the target and stored in the soft state. If a
5500  *		valid device id has not been previously read and stored, a
5501  *		read attempt will be made.
5502  *
5503  *   Arguments: un - driver soft state (unit) structure
5504  *
5505  * Return Code: 0 if we successfully get the device id
5506  *
5507  *     Context: Kernel Thread
5508  */
5509 
5510 static int
5511 sd_get_devid(sd_ssc_t *ssc)
5512 {
5513 	struct dk_devid		*dkdevid;
5514 	ddi_devid_t		tmpid;
5515 	uint_t			*ip;
5516 	size_t			sz;
5517 	diskaddr_t		blk;
5518 	int			status;
5519 	int			chksum;
5520 	int			i;
5521 	size_t			buffer_size;
5522 	struct sd_lun		*un;
5523 
5524 	ASSERT(ssc != NULL);
5525 	un = ssc->ssc_un;
5526 	ASSERT(un != NULL);
5527 	ASSERT(mutex_owned(SD_MUTEX(un)));
5528 
5529 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
5530 	    un);
5531 
5532 	if (un->un_devid != NULL) {
5533 		return (0);
5534 	}
5535 
5536 	mutex_exit(SD_MUTEX(un));
5537 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5538 	    (void *)SD_PATH_DIRECT) != 0) {
5539 		mutex_enter(SD_MUTEX(un));
5540 		return (EINVAL);
5541 	}
5542 
5543 	/*
5544 	 * Read and verify device id, stored in the reserved cylinders at the
5545 	 * end of the disk. Backup label is on the odd sectors of the last
5546 	 * track of the last cylinder. Device id will be on track of the next
5547 	 * to last cylinder.
5548 	 */
5549 	mutex_enter(SD_MUTEX(un));
5550 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
5551 	mutex_exit(SD_MUTEX(un));
5552 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
5553 	status = sd_send_scsi_READ(ssc, dkdevid, buffer_size, blk,
5554 	    SD_PATH_DIRECT);
5555 
5556 	if (status != 0) {
5557 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5558 		goto error;
5559 	}
5560 
5561 	/* Validate the revision */
5562 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
5563 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
5564 		status = EINVAL;
5565 		goto error;
5566 	}
5567 
5568 	/* Calculate the checksum */
5569 	chksum = 0;
5570 	ip = (uint_t *)dkdevid;
5571 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5572 	    i++) {
5573 		chksum ^= ip[i];
5574 	}
5575 
5576 	/* Compare the checksums */
5577 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
5578 		status = EINVAL;
5579 		goto error;
5580 	}
5581 
5582 	/* Validate the device id */
5583 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
5584 		status = EINVAL;
5585 		goto error;
5586 	}
5587 
5588 	/*
5589 	 * Store the device id in the driver soft state
5590 	 */
5591 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
5592 	tmpid = kmem_alloc(sz, KM_SLEEP);
5593 
5594 	mutex_enter(SD_MUTEX(un));
5595 
5596 	un->un_devid = tmpid;
5597 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
5598 
5599 	kmem_free(dkdevid, buffer_size);
5600 
5601 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
5602 
5603 	return (status);
5604 error:
5605 	mutex_enter(SD_MUTEX(un));
5606 	kmem_free(dkdevid, buffer_size);
5607 	return (status);
5608 }
5609 
5610 
5611 /*
5612  *    Function: sd_create_devid
5613  *
5614  * Description: This routine will fabricate the device id and write it
5615  *		to the disk.
5616  *
5617  *   Arguments: un - driver soft state (unit) structure
5618  *
5619  * Return Code: value of the fabricated device id
5620  *
5621  *     Context: Kernel Thread
5622  */
5623 
5624 static ddi_devid_t
5625 sd_create_devid(sd_ssc_t *ssc)
5626 {
5627 	struct sd_lun	*un;
5628 
5629 	ASSERT(ssc != NULL);
5630 	un = ssc->ssc_un;
5631 	ASSERT(un != NULL);
5632 
5633 	/* Fabricate the devid */
5634 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
5635 	    == DDI_FAILURE) {
5636 		return (NULL);
5637 	}
5638 
5639 	/* Write the devid to disk */
5640 	if (sd_write_deviceid(ssc) != 0) {
5641 		ddi_devid_free(un->un_devid);
5642 		un->un_devid = NULL;
5643 	}
5644 
5645 	return (un->un_devid);
5646 }
5647 
5648 
5649 /*
5650  *    Function: sd_write_deviceid
5651  *
5652  * Description: This routine will write the device id to the disk
5653  *		reserved sector.
5654  *
5655  *   Arguments: un - driver soft state (unit) structure
5656  *
5657  * Return Code: EINVAL
5658  *		value returned by sd_send_scsi_cmd
5659  *
5660  *     Context: Kernel Thread
5661  */
5662 
5663 static int
5664 sd_write_deviceid(sd_ssc_t *ssc)
5665 {
5666 	struct dk_devid		*dkdevid;
5667 	uchar_t			*buf;
5668 	diskaddr_t		blk;
5669 	uint_t			*ip, chksum;
5670 	int			status;
5671 	int			i;
5672 	struct sd_lun		*un;
5673 
5674 	ASSERT(ssc != NULL);
5675 	un = ssc->ssc_un;
5676 	ASSERT(un != NULL);
5677 	ASSERT(mutex_owned(SD_MUTEX(un)));
5678 
5679 	mutex_exit(SD_MUTEX(un));
5680 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5681 	    (void *)SD_PATH_DIRECT) != 0) {
5682 		mutex_enter(SD_MUTEX(un));
5683 		return (-1);
5684 	}
5685 
5686 
5687 	/* Allocate the buffer */
5688 	buf = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
5689 	dkdevid = (struct dk_devid *)buf;
5690 
5691 	/* Fill in the revision */
5692 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
5693 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
5694 
5695 	/* Copy in the device id */
5696 	mutex_enter(SD_MUTEX(un));
5697 	bcopy(un->un_devid, &dkdevid->dkd_devid,
5698 	    ddi_devid_sizeof(un->un_devid));
5699 	mutex_exit(SD_MUTEX(un));
5700 
5701 	/* Calculate the checksum */
5702 	chksum = 0;
5703 	ip = (uint_t *)dkdevid;
5704 	for (i = 0; i < ((DEV_BSIZE - sizeof (int)) / sizeof (int));
5705 	    i++) {
5706 		chksum ^= ip[i];
5707 	}
5708 
5709 	/* Fill-in checksum */
5710 	DKD_FORMCHKSUM(chksum, dkdevid);
5711 
5712 	/* Write the reserved sector */
5713 	status = sd_send_scsi_WRITE(ssc, buf, un->un_sys_blocksize, blk,
5714 	    SD_PATH_DIRECT);
5715 	if (status != 0)
5716 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5717 
5718 	kmem_free(buf, un->un_sys_blocksize);
5719 
5720 	mutex_enter(SD_MUTEX(un));
5721 	return (status);
5722 }
5723 
5724 
5725 /*
5726  *    Function: sd_check_vpd_page_support
5727  *
5728  * Description: This routine sends an inquiry command with the EVPD bit set and
5729  *		a page code of 0x00 to the device. It is used to determine which
5730  *		vital product pages are available to find the devid. We are
5731  *		looking for pages 0x83 0x80 or 0xB1.  If we return a negative 1,
5732  *		the device does not support that command.
5733  *
5734  *   Arguments: un  - driver soft state (unit) structure
5735  *
5736  * Return Code: 0 - success
5737  *		1 - check condition
5738  *
5739  *     Context: This routine can sleep.
5740  */
5741 
5742 static int
5743 sd_check_vpd_page_support(sd_ssc_t *ssc)
5744 {
5745 	uchar_t	*page_list	= NULL;
5746 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5747 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5748 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5749 	int	rval		= 0;
5750 	int	counter;
5751 	struct sd_lun		*un;
5752 
5753 	ASSERT(ssc != NULL);
5754 	un = ssc->ssc_un;
5755 	ASSERT(un != NULL);
5756 	ASSERT(mutex_owned(SD_MUTEX(un)));
5757 
5758 	mutex_exit(SD_MUTEX(un));
5759 
5760 	/*
5761 	 * We'll set the page length to the maximum to save figuring it out
5762 	 * with an additional call.
5763 	 */
5764 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5765 
5766 	rval = sd_send_scsi_INQUIRY(ssc, page_list, page_length, evpd,
5767 	    page_code, NULL);
5768 
5769 	if (rval != 0)
5770 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5771 
5772 	mutex_enter(SD_MUTEX(un));
5773 
5774 	/*
5775 	 * Now we must validate that the device accepted the command, as some
5776 	 * drives do not support it.  If the drive does support it, we will
5777 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5778 	 * not, we return -1.
5779 	 */
5780 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5781 		/* Loop to find one of the 2 pages we need */
5782 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5783 
5784 		/*
5785 		 * Pages are returned in ascending order, and 0x83 is what we
5786 		 * are hoping for.
5787 		 */
5788 		while ((page_list[counter] <= 0xB1) &&
5789 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5790 		    VPD_HEAD_OFFSET))) {
5791 			/*
5792 			 * Add 3 because page_list[3] is the number of
5793 			 * pages minus 3
5794 			 */
5795 
5796 			switch (page_list[counter]) {
5797 			case 0x00:
5798 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5799 				break;
5800 			case 0x80:
5801 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5802 				break;
5803 			case 0x81:
5804 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5805 				break;
5806 			case 0x82:
5807 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5808 				break;
5809 			case 0x83:
5810 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5811 				break;
5812 			case 0x86:
5813 				un->un_vpd_page_mask |= SD_VPD_EXTENDED_DATA_PG;
5814 				break;
5815 			case 0xB0:
5816 				un->un_vpd_page_mask |= SD_VPD_BLK_LIMITS_PG;
5817 				break;
5818 			case 0xB1:
5819 				un->un_vpd_page_mask |= SD_VPD_DEV_CHARACTER_PG;
5820 				break;
5821 			}
5822 			counter++;
5823 		}
5824 
5825 	} else {
5826 		rval = -1;
5827 
5828 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5829 		    "sd_check_vpd_page_support: This drive does not implement "
5830 		    "VPD pages.\n");
5831 	}
5832 
5833 	kmem_free(page_list, page_length);
5834 
5835 	return (rval);
5836 }
5837 
5838 
5839 /*
5840  *    Function: sd_setup_pm
5841  *
5842  * Description: Initialize Power Management on the device
5843  *
5844  *     Context: Kernel Thread
5845  */
5846 
5847 static void
5848 sd_setup_pm(sd_ssc_t *ssc, dev_info_t *devi)
5849 {
5850 	uint_t		log_page_size;
5851 	uchar_t		*log_page_data;
5852 	int		rval = 0;
5853 	struct sd_lun	*un;
5854 
5855 	ASSERT(ssc != NULL);
5856 	un = ssc->ssc_un;
5857 	ASSERT(un != NULL);
5858 
5859 	/*
5860 	 * Since we are called from attach, holding a mutex for
5861 	 * un is unnecessary. Because some of the routines called
5862 	 * from here require SD_MUTEX to not be held, assert this
5863 	 * right up front.
5864 	 */
5865 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5866 	/*
5867 	 * Since the sd device does not have the 'reg' property,
5868 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5869 	 * The following code is to tell cpr that this device
5870 	 * DOES need to be suspended and resumed.
5871 	 */
5872 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5873 	    "pm-hardware-state", "needs-suspend-resume");
5874 
5875 	/*
5876 	 * This complies with the new power management framework
5877 	 * for certain desktop machines. Create the pm_components
5878 	 * property as a string array property.
5879 	 * If un_f_pm_supported is TRUE, that means the disk
5880 	 * attached HBA has set the "pm-capable" property and
5881 	 * the value of this property is bigger than 0.
5882 	 */
5883 	if (un->un_f_pm_supported) {
5884 		/*
5885 		 * not all devices have a motor, try it first.
5886 		 * some devices may return ILLEGAL REQUEST, some
5887 		 * will hang
5888 		 * The following START_STOP_UNIT is used to check if target
5889 		 * device has a motor.
5890 		 */
5891 		un->un_f_start_stop_supported = TRUE;
5892 
5893 		if (un->un_f_power_condition_supported) {
5894 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5895 			    SD_POWER_CONDITION, SD_TARGET_ACTIVE,
5896 			    SD_PATH_DIRECT);
5897 			if (rval != 0) {
5898 				un->un_f_power_condition_supported = FALSE;
5899 			}
5900 		}
5901 		if (!un->un_f_power_condition_supported) {
5902 			rval = sd_send_scsi_START_STOP_UNIT(ssc,
5903 			    SD_START_STOP, SD_TARGET_START, SD_PATH_DIRECT);
5904 		}
5905 		if (rval != 0) {
5906 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
5907 			un->un_f_start_stop_supported = FALSE;
5908 		}
5909 
5910 		/*
5911 		 * create pm properties anyways otherwise the parent can't
5912 		 * go to sleep
5913 		 */
5914 		un->un_f_pm_is_enabled = TRUE;
5915 		(void) sd_create_pm_components(devi, un);
5916 
5917 		/*
5918 		 * If it claims that log sense is supported, check it out.
5919 		 */
5920 		if (un->un_f_log_sense_supported) {
5921 			rval = sd_log_page_supported(ssc,
5922 			    START_STOP_CYCLE_PAGE);
5923 			if (rval == 1) {
5924 				/* Page found, use it. */
5925 				un->un_start_stop_cycle_page =
5926 				    START_STOP_CYCLE_PAGE;
5927 			} else {
5928 				/*
5929 				 * Page not found or log sense is not
5930 				 * supported.
5931 				 * Notice we do not check the old style
5932 				 * START_STOP_CYCLE_VU_PAGE because this
5933 				 * code path does not apply to old disks.
5934 				 */
5935 				un->un_f_log_sense_supported = FALSE;
5936 				un->un_f_pm_log_sense_smart = FALSE;
5937 			}
5938 		}
5939 
5940 		return;
5941 	}
5942 
5943 	/*
5944 	 * For the disk whose attached HBA has not set the "pm-capable"
5945 	 * property, check if it supports the power management.
5946 	 */
5947 	if (!un->un_f_log_sense_supported) {
5948 		un->un_power_level = SD_SPINDLE_ON;
5949 		un->un_f_pm_is_enabled = FALSE;
5950 		return;
5951 	}
5952 
5953 	rval = sd_log_page_supported(ssc, START_STOP_CYCLE_PAGE);
5954 
5955 #ifdef	SDDEBUG
5956 	if (sd_force_pm_supported) {
5957 		/* Force a successful result */
5958 		rval = 1;
5959 	}
5960 #endif
5961 
5962 	/*
5963 	 * If the start-stop cycle counter log page is not supported
5964 	 * or if the pm-capable property is set to be false (0),
5965 	 * then we should not create the pm_components property.
5966 	 */
5967 	if (rval == -1) {
5968 		/*
5969 		 * Error.
5970 		 * Reading log sense failed, most likely this is
5971 		 * an older drive that does not support log sense.
5972 		 * If this fails auto-pm is not supported.
5973 		 */
5974 		un->un_power_level = SD_SPINDLE_ON;
5975 		un->un_f_pm_is_enabled = FALSE;
5976 
5977 	} else if (rval == 0) {
5978 		/*
5979 		 * Page not found.
5980 		 * The start stop cycle counter is implemented as page
5981 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
5982 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
5983 		 */
5984 		if (sd_log_page_supported(ssc, START_STOP_CYCLE_VU_PAGE) == 1) {
5985 			/*
5986 			 * Page found, use this one.
5987 			 */
5988 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
5989 			un->un_f_pm_is_enabled = TRUE;
5990 		} else {
5991 			/*
5992 			 * Error or page not found.
5993 			 * auto-pm is not supported for this device.
5994 			 */
5995 			un->un_power_level = SD_SPINDLE_ON;
5996 			un->un_f_pm_is_enabled = FALSE;
5997 		}
5998 	} else {
5999 		/*
6000 		 * Page found, use it.
6001 		 */
6002 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
6003 		un->un_f_pm_is_enabled = TRUE;
6004 	}
6005 
6006 
6007 	if (un->un_f_pm_is_enabled == TRUE) {
6008 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6009 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6010 
6011 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6012 		    log_page_size, un->un_start_stop_cycle_page,
6013 		    0x01, 0, SD_PATH_DIRECT);
6014 
6015 		if (rval != 0) {
6016 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6017 		}
6018 
6019 #ifdef	SDDEBUG
6020 		if (sd_force_pm_supported) {
6021 			/* Force a successful result */
6022 			rval = 0;
6023 		}
6024 #endif
6025 
6026 		/*
6027 		 * If the Log sense for Page( Start/stop cycle counter page)
6028 		 * succeeds, then power management is supported and we can
6029 		 * enable auto-pm.
6030 		 */
6031 		if (rval == 0)  {
6032 			(void) sd_create_pm_components(devi, un);
6033 		} else {
6034 			un->un_power_level = SD_SPINDLE_ON;
6035 			un->un_f_pm_is_enabled = FALSE;
6036 		}
6037 
6038 		kmem_free(log_page_data, log_page_size);
6039 	}
6040 }
6041 
6042 
6043 /*
6044  *    Function: sd_create_pm_components
6045  *
6046  * Description: Initialize PM property.
6047  *
6048  *     Context: Kernel thread context
6049  */
6050 
6051 static void
6052 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
6053 {
6054 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6055 
6056 	if (un->un_f_power_condition_supported) {
6057 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6058 		    "pm-components", sd_pwr_pc.pm_comp, 5)
6059 		    != DDI_PROP_SUCCESS) {
6060 			un->un_power_level = SD_SPINDLE_ACTIVE;
6061 			un->un_f_pm_is_enabled = FALSE;
6062 			return;
6063 		}
6064 	} else {
6065 		if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
6066 		    "pm-components", sd_pwr_ss.pm_comp, 3)
6067 		    != DDI_PROP_SUCCESS) {
6068 			un->un_power_level = SD_SPINDLE_ON;
6069 			un->un_f_pm_is_enabled = FALSE;
6070 			return;
6071 		}
6072 	}
6073 	/*
6074 	 * When components are initially created they are idle,
6075 	 * power up any non-removables.
6076 	 * Note: the return value of pm_raise_power can't be used
6077 	 * for determining if PM should be enabled for this device.
6078 	 * Even if you check the return values and remove this
6079 	 * property created above, the PM framework will not honor the
6080 	 * change after the first call to pm_raise_power. Hence,
6081 	 * removal of that property does not help if pm_raise_power
6082 	 * fails. In the case of removable media, the start/stop
6083 	 * will fail if the media is not present.
6084 	 */
6085 	if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
6086 	    SD_PM_STATE_ACTIVE(un)) == DDI_SUCCESS)) {
6087 		mutex_enter(SD_MUTEX(un));
6088 		un->un_power_level = SD_PM_STATE_ACTIVE(un);
6089 		mutex_enter(&un->un_pm_mutex);
6090 		/* Set to on and not busy. */
6091 		un->un_pm_count = 0;
6092 	} else {
6093 		mutex_enter(SD_MUTEX(un));
6094 		un->un_power_level = SD_PM_STATE_STOPPED(un);
6095 		mutex_enter(&un->un_pm_mutex);
6096 		/* Set to off. */
6097 		un->un_pm_count = -1;
6098 	}
6099 	mutex_exit(&un->un_pm_mutex);
6100 	mutex_exit(SD_MUTEX(un));
6101 }
6102 
6103 
6104 /*
6105  *    Function: sd_ddi_suspend
6106  *
6107  * Description: Performs system power-down operations. This includes
6108  *		setting the drive state to indicate its suspended so
6109  *		that no new commands will be accepted. Also, wait for
6110  *		all commands that are in transport or queued to a timer
6111  *		for retry to complete. All timeout threads are cancelled.
6112  *
6113  * Return Code: DDI_FAILURE or DDI_SUCCESS
6114  *
6115  *     Context: Kernel thread context
6116  */
6117 
6118 static int
6119 sd_ddi_suspend(dev_info_t *devi)
6120 {
6121 	struct	sd_lun	*un;
6122 	clock_t		wait_cmds_complete;
6123 
6124 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6125 	if (un == NULL) {
6126 		return (DDI_FAILURE);
6127 	}
6128 
6129 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
6130 
6131 	mutex_enter(SD_MUTEX(un));
6132 
6133 	/* Return success if the device is already suspended. */
6134 	if (un->un_state == SD_STATE_SUSPENDED) {
6135 		mutex_exit(SD_MUTEX(un));
6136 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6137 		    "device already suspended, exiting\n");
6138 		return (DDI_SUCCESS);
6139 	}
6140 
6141 	/* Return failure if the device is being used by HA */
6142 	if (un->un_resvd_status &
6143 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
6144 		mutex_exit(SD_MUTEX(un));
6145 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6146 		    "device in use by HA, exiting\n");
6147 		return (DDI_FAILURE);
6148 	}
6149 
6150 	/*
6151 	 * Return failure if the device is in a resource wait
6152 	 * or power changing state.
6153 	 */
6154 	if ((un->un_state == SD_STATE_RWAIT) ||
6155 	    (un->un_state == SD_STATE_PM_CHANGING)) {
6156 		mutex_exit(SD_MUTEX(un));
6157 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
6158 		    "device in resource wait state, exiting\n");
6159 		return (DDI_FAILURE);
6160 	}
6161 
6162 
6163 	un->un_save_state = un->un_last_state;
6164 	New_state(un, SD_STATE_SUSPENDED);
6165 
6166 	/*
6167 	 * Wait for all commands that are in transport or queued to a timer
6168 	 * for retry to complete.
6169 	 *
6170 	 * While waiting, no new commands will be accepted or sent because of
6171 	 * the new state we set above.
6172 	 *
6173 	 * Wait till current operation has completed. If we are in the resource
6174 	 * wait state (with an intr outstanding) then we need to wait till the
6175 	 * intr completes and starts the next cmd. We want to wait for
6176 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
6177 	 */
6178 	wait_cmds_complete = ddi_get_lbolt() +
6179 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
6180 
6181 	while (un->un_ncmds_in_transport != 0) {
6182 		/*
6183 		 * Fail if commands do not finish in the specified time.
6184 		 */
6185 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
6186 		    wait_cmds_complete) == -1) {
6187 			/*
6188 			 * Undo the state changes made above. Everything
6189 			 * must go back to it's original value.
6190 			 */
6191 			Restore_state(un);
6192 			un->un_last_state = un->un_save_state;
6193 			/* Wake up any threads that might be waiting. */
6194 			cv_broadcast(&un->un_suspend_cv);
6195 			mutex_exit(SD_MUTEX(un));
6196 			SD_ERROR(SD_LOG_IO_PM, un,
6197 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
6198 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
6199 			return (DDI_FAILURE);
6200 		}
6201 	}
6202 
6203 	/*
6204 	 * Cancel SCSI watch thread and timeouts, if any are active
6205 	 */
6206 
6207 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
6208 		opaque_t temp_token = un->un_swr_token;
6209 		mutex_exit(SD_MUTEX(un));
6210 		scsi_watch_suspend(temp_token);
6211 		mutex_enter(SD_MUTEX(un));
6212 	}
6213 
6214 	if (un->un_reset_throttle_timeid != NULL) {
6215 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
6216 		un->un_reset_throttle_timeid = NULL;
6217 		mutex_exit(SD_MUTEX(un));
6218 		(void) untimeout(temp_id);
6219 		mutex_enter(SD_MUTEX(un));
6220 	}
6221 
6222 	if (un->un_dcvb_timeid != NULL) {
6223 		timeout_id_t temp_id = un->un_dcvb_timeid;
6224 		un->un_dcvb_timeid = NULL;
6225 		mutex_exit(SD_MUTEX(un));
6226 		(void) untimeout(temp_id);
6227 		mutex_enter(SD_MUTEX(un));
6228 	}
6229 
6230 	mutex_enter(&un->un_pm_mutex);
6231 	if (un->un_pm_timeid != NULL) {
6232 		timeout_id_t temp_id = un->un_pm_timeid;
6233 		un->un_pm_timeid = NULL;
6234 		mutex_exit(&un->un_pm_mutex);
6235 		mutex_exit(SD_MUTEX(un));
6236 		(void) untimeout(temp_id);
6237 		mutex_enter(SD_MUTEX(un));
6238 	} else {
6239 		mutex_exit(&un->un_pm_mutex);
6240 	}
6241 
6242 	if (un->un_rmw_msg_timeid != NULL) {
6243 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
6244 		un->un_rmw_msg_timeid = NULL;
6245 		mutex_exit(SD_MUTEX(un));
6246 		(void) untimeout(temp_id);
6247 		mutex_enter(SD_MUTEX(un));
6248 	}
6249 
6250 	if (un->un_retry_timeid != NULL) {
6251 		timeout_id_t temp_id = un->un_retry_timeid;
6252 		un->un_retry_timeid = NULL;
6253 		mutex_exit(SD_MUTEX(un));
6254 		(void) untimeout(temp_id);
6255 		mutex_enter(SD_MUTEX(un));
6256 
6257 		if (un->un_retry_bp != NULL) {
6258 			un->un_retry_bp->av_forw = un->un_waitq_headp;
6259 			un->un_waitq_headp = un->un_retry_bp;
6260 			if (un->un_waitq_tailp == NULL) {
6261 				un->un_waitq_tailp = un->un_retry_bp;
6262 			}
6263 			un->un_retry_bp = NULL;
6264 			un->un_retry_statp = NULL;
6265 		}
6266 	}
6267 
6268 	if (un->un_direct_priority_timeid != NULL) {
6269 		timeout_id_t temp_id = un->un_direct_priority_timeid;
6270 		un->un_direct_priority_timeid = NULL;
6271 		mutex_exit(SD_MUTEX(un));
6272 		(void) untimeout(temp_id);
6273 		mutex_enter(SD_MUTEX(un));
6274 	}
6275 
6276 	if (un->un_f_is_fibre == TRUE) {
6277 		/*
6278 		 * Remove callbacks for insert and remove events
6279 		 */
6280 		if (un->un_insert_event != NULL) {
6281 			mutex_exit(SD_MUTEX(un));
6282 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
6283 			mutex_enter(SD_MUTEX(un));
6284 			un->un_insert_event = NULL;
6285 		}
6286 
6287 		if (un->un_remove_event != NULL) {
6288 			mutex_exit(SD_MUTEX(un));
6289 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
6290 			mutex_enter(SD_MUTEX(un));
6291 			un->un_remove_event = NULL;
6292 		}
6293 	}
6294 
6295 	mutex_exit(SD_MUTEX(un));
6296 
6297 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
6298 
6299 	return (DDI_SUCCESS);
6300 }
6301 
6302 
6303 /*
6304  *    Function: sd_ddi_resume
6305  *
6306  * Description: Performs system power-up operations..
6307  *
6308  * Return Code: DDI_SUCCESS
6309  *		DDI_FAILURE
6310  *
6311  *     Context: Kernel thread context
6312  */
6313 
6314 static int
6315 sd_ddi_resume(dev_info_t *devi)
6316 {
6317 	struct	sd_lun	*un;
6318 
6319 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
6320 	if (un == NULL) {
6321 		return (DDI_FAILURE);
6322 	}
6323 
6324 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
6325 
6326 	mutex_enter(SD_MUTEX(un));
6327 	Restore_state(un);
6328 
6329 	/*
6330 	 * Restore the state which was saved to give the
6331 	 * the right state in un_last_state
6332 	 */
6333 	un->un_last_state = un->un_save_state;
6334 	/*
6335 	 * Note: throttle comes back at full.
6336 	 * Also note: this MUST be done before calling pm_raise_power
6337 	 * otherwise the system can get hung in biowait. The scenario where
6338 	 * this'll happen is under cpr suspend. Writing of the system
6339 	 * state goes through sddump, which writes 0 to un_throttle. If
6340 	 * writing the system state then fails, example if the partition is
6341 	 * too small, then cpr attempts a resume. If throttle isn't restored
6342 	 * from the saved value until after calling pm_raise_power then
6343 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
6344 	 * in biowait.
6345 	 */
6346 	un->un_throttle = un->un_saved_throttle;
6347 
6348 	/*
6349 	 * The chance of failure is very rare as the only command done in power
6350 	 * entry point is START command when you transition from 0->1 or
6351 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
6352 	 * which suspend was done. Ignore the return value as the resume should
6353 	 * not be failed. In the case of removable media the media need not be
6354 	 * inserted and hence there is a chance that raise power will fail with
6355 	 * media not present.
6356 	 */
6357 	if (un->un_f_attach_spinup) {
6358 		mutex_exit(SD_MUTEX(un));
6359 		(void) pm_raise_power(SD_DEVINFO(un), 0,
6360 		    SD_PM_STATE_ACTIVE(un));
6361 		mutex_enter(SD_MUTEX(un));
6362 	}
6363 
6364 	/*
6365 	 * Don't broadcast to the suspend cv and therefore possibly
6366 	 * start I/O until after power has been restored.
6367 	 */
6368 	cv_broadcast(&un->un_suspend_cv);
6369 	cv_broadcast(&un->un_state_cv);
6370 
6371 	/* restart thread */
6372 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
6373 		scsi_watch_resume(un->un_swr_token);
6374 	}
6375 
6376 #if (defined(__fibre))
6377 	if (un->un_f_is_fibre == TRUE) {
6378 		/*
6379 		 * Add callbacks for insert and remove events
6380 		 */
6381 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
6382 			sd_init_event_callbacks(un);
6383 		}
6384 	}
6385 #endif
6386 
6387 	/*
6388 	 * Transport any pending commands to the target.
6389 	 *
6390 	 * If this is a low-activity device commands in queue will have to wait
6391 	 * until new commands come in, which may take awhile. Also, we
6392 	 * specifically don't check un_ncmds_in_transport because we know that
6393 	 * there really are no commands in progress after the unit was
6394 	 * suspended and we could have reached the throttle level, been
6395 	 * suspended, and have no new commands coming in for awhile. Highly
6396 	 * unlikely, but so is the low-activity disk scenario.
6397 	 */
6398 	ddi_xbuf_dispatch(un->un_xbuf_attr);
6399 
6400 	sd_start_cmds(un, NULL);
6401 	mutex_exit(SD_MUTEX(un));
6402 
6403 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
6404 
6405 	return (DDI_SUCCESS);
6406 }
6407 
6408 
6409 /*
6410  *    Function: sd_pm_state_change
6411  *
6412  * Description: Change the driver power state.
6413  *		Someone else is required to actually change the driver
6414  *		power level.
6415  *
6416  *   Arguments: un - driver soft state (unit) structure
6417  *              level - the power level that is changed to
6418  *              flag - to decide how to change the power state
6419  *
6420  * Return Code: DDI_SUCCESS
6421  *
6422  *     Context: Kernel thread context
6423  */
6424 static int
6425 sd_pm_state_change(struct sd_lun *un, int level, int flag)
6426 {
6427 	ASSERT(un != NULL);
6428 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: entry\n");
6429 
6430 	ASSERT(!mutex_owned(SD_MUTEX(un)));
6431 	mutex_enter(SD_MUTEX(un));
6432 
6433 	if (flag == SD_PM_STATE_ROLLBACK || SD_PM_IS_IO_CAPABLE(un, level)) {
6434 		un->un_power_level = level;
6435 		ASSERT(!mutex_owned(&un->un_pm_mutex));
6436 		mutex_enter(&un->un_pm_mutex);
6437 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
6438 			un->un_pm_count++;
6439 			ASSERT(un->un_pm_count == 0);
6440 		}
6441 		mutex_exit(&un->un_pm_mutex);
6442 	} else {
6443 		/*
6444 		 * Exit if power management is not enabled for this device,
6445 		 * or if the device is being used by HA.
6446 		 */
6447 		if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
6448 		    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
6449 			mutex_exit(SD_MUTEX(un));
6450 			SD_TRACE(SD_LOG_POWER, un,
6451 			    "sd_pm_state_change: exiting\n");
6452 			return (DDI_FAILURE);
6453 		}
6454 
6455 		SD_INFO(SD_LOG_POWER, un, "sd_pm_state_change: "
6456 		    "un_ncmds_in_driver=%ld\n", un->un_ncmds_in_driver);
6457 
6458 		/*
6459 		 * See if the device is not busy, ie.:
6460 		 *    - we have no commands in the driver for this device
6461 		 *    - not waiting for resources
6462 		 */
6463 		if ((un->un_ncmds_in_driver == 0) &&
6464 		    (un->un_state != SD_STATE_RWAIT)) {
6465 			/*
6466 			 * The device is not busy, so it is OK to go to low
6467 			 * power state. Indicate low power, but rely on someone
6468 			 * else to actually change it.
6469 			 */
6470 			mutex_enter(&un->un_pm_mutex);
6471 			un->un_pm_count = -1;
6472 			mutex_exit(&un->un_pm_mutex);
6473 			un->un_power_level = level;
6474 		}
6475 	}
6476 
6477 	mutex_exit(SD_MUTEX(un));
6478 
6479 	SD_TRACE(SD_LOG_POWER, un, "sd_pm_state_change: exit\n");
6480 
6481 	return (DDI_SUCCESS);
6482 }
6483 
6484 
6485 /*
6486  *    Function: sd_pm_idletimeout_handler
6487  *
6488  * Description: A timer routine that's active only while a device is busy.
6489  *		The purpose is to extend slightly the pm framework's busy
6490  *		view of the device to prevent busy/idle thrashing for
6491  *		back-to-back commands. Do this by comparing the current time
6492  *		to the time at which the last command completed and when the
6493  *		difference is greater than sd_pm_idletime, call
6494  *		pm_idle_component. In addition to indicating idle to the pm
6495  *		framework, update the chain type to again use the internal pm
6496  *		layers of the driver.
6497  *
6498  *   Arguments: arg - driver soft state (unit) structure
6499  *
6500  *     Context: Executes in a timeout(9F) thread context
6501  */
6502 
6503 static void
6504 sd_pm_idletimeout_handler(void *arg)
6505 {
6506 	const hrtime_t idletime = sd_pm_idletime * NANOSEC;
6507 	struct sd_lun *un = arg;
6508 
6509 	/*
6510 	 * Grab both mutexes, in the proper order, since we're accessing
6511 	 * both PM and softstate variables.
6512 	 */
6513 	mutex_enter(SD_MUTEX(un));
6514 	mutex_enter(&un->un_pm_mutex);
6515 	/* if timeout id is NULL, we are being canceled via untimeout */
6516 	if (un->un_pm_idle_timeid == NULL) {
6517 		mutex_exit(&un->un_pm_mutex);
6518 		mutex_exit(SD_MUTEX(un));
6519 		return;
6520 	}
6521 	if (((gethrtime() - un->un_pm_idle_time) > idletime) &&
6522 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
6523 		/*
6524 		 * Update the chain types.
6525 		 * This takes affect on the next new command received.
6526 		 */
6527 		if (un->un_f_non_devbsize_supported) {
6528 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
6529 		} else {
6530 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
6531 		}
6532 		un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD;
6533 
6534 		SD_TRACE(SD_LOG_IO_PM, un,
6535 		    "sd_pm_idletimeout_handler: idling device\n");
6536 		(void) pm_idle_component(SD_DEVINFO(un), 0);
6537 		un->un_pm_idle_timeid = NULL;
6538 	} else {
6539 		un->un_pm_idle_timeid =
6540 		    timeout(sd_pm_idletimeout_handler, un,
6541 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
6542 	}
6543 	mutex_exit(&un->un_pm_mutex);
6544 	mutex_exit(SD_MUTEX(un));
6545 }
6546 
6547 
6548 /*
6549  *    Function: sd_pm_timeout_handler
6550  *
6551  * Description: Callback to tell framework we are idle.
6552  *
6553  *     Context: timeout(9f) thread context.
6554  */
6555 
6556 static void
6557 sd_pm_timeout_handler(void *arg)
6558 {
6559 	struct sd_lun *un = arg;
6560 
6561 	(void) pm_idle_component(SD_DEVINFO(un), 0);
6562 	mutex_enter(&un->un_pm_mutex);
6563 	un->un_pm_timeid = NULL;
6564 	mutex_exit(&un->un_pm_mutex);
6565 }
6566 
6567 
6568 /*
6569  *    Function: sdpower
6570  *
6571  * Description: PM entry point.
6572  *
6573  * Return Code: DDI_SUCCESS
6574  *		DDI_FAILURE
6575  *
6576  *     Context: Kernel thread context
6577  */
6578 
6579 static int
6580 sdpower(dev_info_t *devi, int component, int level)
6581 {
6582 	struct sd_lun	*un;
6583 	int		instance;
6584 	int		rval = DDI_SUCCESS;
6585 	uint_t		i, log_page_size, maxcycles, ncycles;
6586 	uchar_t		*log_page_data;
6587 	int		log_sense_page;
6588 	int		medium_present;
6589 	time_t		intvlp;
6590 	struct pm_trans_data	sd_pm_tran_data;
6591 	uchar_t		save_state = SD_STATE_NORMAL;
6592 	int		sval;
6593 	uchar_t		state_before_pm;
6594 	sd_ssc_t	*ssc;
6595 	int	last_power_level = SD_SPINDLE_UNINIT;
6596 
6597 	instance = ddi_get_instance(devi);
6598 
6599 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
6600 	    !SD_PM_IS_LEVEL_VALID(un, level) || component != 0) {
6601 		return (DDI_FAILURE);
6602 	}
6603 
6604 	ssc = sd_ssc_init(un);
6605 
6606 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
6607 
6608 	mutex_enter(SD_MUTEX(un));
6609 
6610 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
6611 	    un->un_ncmds_in_driver);
6612 
6613 	/*
6614 	 * If un_ncmds_in_driver is non-zero it indicates commands are
6615 	 * already being processed in the driver.
6616 	 * At the same time somebody is requesting to go to a lower power
6617 	 * that can't perform I/O, which can't happen, therefore we need to
6618 	 * return failure.
6619 	 */
6620 	if ((!SD_PM_IS_IO_CAPABLE(un, level)) &&
6621 	    (un->un_ncmds_in_driver != 0)) {
6622 		mutex_exit(SD_MUTEX(un));
6623 
6624 		SD_TRACE(SD_LOG_IO_PM, un,
6625 		    "sdpower: exit, device has queued cmds.\n");
6626 
6627 		goto sdpower_failed;
6628 	}
6629 
6630 	/*
6631 	 * if it is OFFLINE that means the disk is completely dead
6632 	 * in our case we have to put the disk in on or off by sending commands
6633 	 * Of course that will fail anyway so return back here.
6634 	 *
6635 	 * Power changes to a device that's OFFLINE or SUSPENDED
6636 	 * are not allowed.
6637 	 */
6638 	if ((un->un_state == SD_STATE_OFFLINE) ||
6639 	    (un->un_state == SD_STATE_SUSPENDED)) {
6640 		mutex_exit(SD_MUTEX(un));
6641 
6642 		SD_TRACE(SD_LOG_IO_PM, un,
6643 		    "sdpower: exit, device is off-line.\n");
6644 
6645 		goto sdpower_failed;
6646 	}
6647 
6648 	/*
6649 	 * Change the device's state to indicate it's power level
6650 	 * is being changed. Do this to prevent a power off in the
6651 	 * middle of commands, which is especially bad on devices
6652 	 * that are really powered off instead of just spun down.
6653 	 */
6654 	state_before_pm = un->un_state;
6655 	un->un_state = SD_STATE_PM_CHANGING;
6656 
6657 	mutex_exit(SD_MUTEX(un));
6658 
6659 	/*
6660 	 * If log sense command is not supported, bypass the
6661 	 * following checking, otherwise, check the log sense
6662 	 * information for this device.
6663 	 */
6664 	if (SD_PM_STOP_MOTOR_NEEDED(un, level) &&
6665 	    un->un_f_log_sense_supported) {
6666 		/*
6667 		 * Get the log sense information to understand whether the
6668 		 * the powercycle counts have gone beyond the threshhold.
6669 		 */
6670 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
6671 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
6672 
6673 		mutex_enter(SD_MUTEX(un));
6674 		log_sense_page = un->un_start_stop_cycle_page;
6675 		mutex_exit(SD_MUTEX(un));
6676 
6677 		rval = sd_send_scsi_LOG_SENSE(ssc, log_page_data,
6678 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
6679 
6680 		if (rval != 0) {
6681 			if (rval == EIO)
6682 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6683 			else
6684 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6685 		}
6686 
6687 #ifdef	SDDEBUG
6688 		if (sd_force_pm_supported) {
6689 			/* Force a successful result */
6690 			rval = 0;
6691 		}
6692 #endif
6693 		if (rval != 0) {
6694 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
6695 			    "Log Sense Failed\n");
6696 
6697 			kmem_free(log_page_data, log_page_size);
6698 			/* Cannot support power management on those drives */
6699 
6700 			/*
6701 			 * On exit put the state back to it's original value
6702 			 * and broadcast to anyone waiting for the power
6703 			 * change completion.
6704 			 */
6705 			mutex_enter(SD_MUTEX(un));
6706 			un->un_state = state_before_pm;
6707 			cv_broadcast(&un->un_suspend_cv);
6708 			mutex_exit(SD_MUTEX(un));
6709 			SD_TRACE(SD_LOG_IO_PM, un,
6710 			    "sdpower: exit, Log Sense Failed.\n");
6711 
6712 			goto sdpower_failed;
6713 		}
6714 
6715 		/*
6716 		 * From the page data - Convert the essential information to
6717 		 * pm_trans_data
6718 		 */
6719 		maxcycles =
6720 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
6721 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
6722 
6723 		ncycles =
6724 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
6725 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
6726 
6727 		if (un->un_f_pm_log_sense_smart) {
6728 			sd_pm_tran_data.un.smart_count.allowed = maxcycles;
6729 			sd_pm_tran_data.un.smart_count.consumed = ncycles;
6730 			sd_pm_tran_data.un.smart_count.flag = 0;
6731 			sd_pm_tran_data.format = DC_SMART_FORMAT;
6732 		} else {
6733 			sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
6734 			sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
6735 			for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
6736 				sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
6737 				    log_page_data[8+i];
6738 			}
6739 			sd_pm_tran_data.un.scsi_cycles.flag = 0;
6740 			sd_pm_tran_data.format = DC_SCSI_FORMAT;
6741 		}
6742 
6743 		kmem_free(log_page_data, log_page_size);
6744 
6745 		/*
6746 		 * Call pm_trans_check routine to get the Ok from
6747 		 * the global policy
6748 		 */
6749 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
6750 #ifdef	SDDEBUG
6751 		if (sd_force_pm_supported) {
6752 			/* Force a successful result */
6753 			rval = 1;
6754 		}
6755 #endif
6756 		switch (rval) {
6757 		case 0:
6758 			/*
6759 			 * Not Ok to Power cycle or error in parameters passed
6760 			 * Would have given the advised time to consider power
6761 			 * cycle. Based on the new intvlp parameter we are
6762 			 * supposed to pretend we are busy so that pm framework
6763 			 * will never call our power entry point. Because of
6764 			 * that install a timeout handler and wait for the
6765 			 * recommended time to elapse so that power management
6766 			 * can be effective again.
6767 			 *
6768 			 * To effect this behavior, call pm_busy_component to
6769 			 * indicate to the framework this device is busy.
6770 			 * By not adjusting un_pm_count the rest of PM in
6771 			 * the driver will function normally, and independent
6772 			 * of this but because the framework is told the device
6773 			 * is busy it won't attempt powering down until it gets
6774 			 * a matching idle. The timeout handler sends this.
6775 			 * Note: sd_pm_entry can't be called here to do this
6776 			 * because sdpower may have been called as a result
6777 			 * of a call to pm_raise_power from within sd_pm_entry.
6778 			 *
6779 			 * If a timeout handler is already active then
6780 			 * don't install another.
6781 			 */
6782 			mutex_enter(&un->un_pm_mutex);
6783 			if (un->un_pm_timeid == NULL) {
6784 				un->un_pm_timeid =
6785 				    timeout(sd_pm_timeout_handler,
6786 				    un, intvlp * drv_usectohz(1000000));
6787 				mutex_exit(&un->un_pm_mutex);
6788 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6789 			} else {
6790 				mutex_exit(&un->un_pm_mutex);
6791 			}
6792 			/*
6793 			 * On exit put the state back to its original value
6794 			 * and broadcast to anyone waiting for the power
6795 			 * change completion.
6796 			 */
6797 			mutex_enter(SD_MUTEX(un));
6798 			un->un_state = state_before_pm;
6799 			cv_broadcast(&un->un_suspend_cv);
6800 			mutex_exit(SD_MUTEX(un));
6801 
6802 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6803 			    "trans check Failed, not ok to power cycle.\n");
6804 
6805 			goto sdpower_failed;
6806 		case -1:
6807 			/*
6808 			 * On exit put the state back to its original value
6809 			 * and broadcast to anyone waiting for the power
6810 			 * change completion.
6811 			 */
6812 			mutex_enter(SD_MUTEX(un));
6813 			un->un_state = state_before_pm;
6814 			cv_broadcast(&un->un_suspend_cv);
6815 			mutex_exit(SD_MUTEX(un));
6816 			SD_TRACE(SD_LOG_IO_PM, un,
6817 			    "sdpower: exit, trans check command Failed.\n");
6818 
6819 			goto sdpower_failed;
6820 		}
6821 	}
6822 
6823 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
6824 		/*
6825 		 * Save the last state... if the STOP FAILS we need it
6826 		 * for restoring
6827 		 */
6828 		mutex_enter(SD_MUTEX(un));
6829 		save_state = un->un_last_state;
6830 		last_power_level = un->un_power_level;
6831 		/*
6832 		 * There must not be any cmds. getting processed
6833 		 * in the driver when we get here. Power to the
6834 		 * device is potentially going off.
6835 		 */
6836 		ASSERT(un->un_ncmds_in_driver == 0);
6837 		mutex_exit(SD_MUTEX(un));
6838 
6839 		/*
6840 		 * For now PM suspend the device completely before spindle is
6841 		 * turned off
6842 		 */
6843 		if ((rval = sd_pm_state_change(un, level, SD_PM_STATE_CHANGE))
6844 		    == DDI_FAILURE) {
6845 			/*
6846 			 * On exit put the state back to its original value
6847 			 * and broadcast to anyone waiting for the power
6848 			 * change completion.
6849 			 */
6850 			mutex_enter(SD_MUTEX(un));
6851 			un->un_state = state_before_pm;
6852 			un->un_power_level = last_power_level;
6853 			cv_broadcast(&un->un_suspend_cv);
6854 			mutex_exit(SD_MUTEX(un));
6855 			SD_TRACE(SD_LOG_IO_PM, un,
6856 			    "sdpower: exit, PM suspend Failed.\n");
6857 
6858 			goto sdpower_failed;
6859 		}
6860 	}
6861 
6862 	/*
6863 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6864 	 * close, or strategy. Dump no long uses this routine, it uses it's
6865 	 * own code so it can be done in polled mode.
6866 	 */
6867 
6868 	medium_present = TRUE;
6869 
6870 	/*
6871 	 * When powering up, issue a TUR in case the device is at unit
6872 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6873 	 * a deadlock on un_pm_busy_cv will occur.
6874 	 */
6875 	if (SD_PM_IS_IO_CAPABLE(un, level)) {
6876 		sval = sd_send_scsi_TEST_UNIT_READY(ssc,
6877 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6878 		if (sval != 0)
6879 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6880 	}
6881 
6882 	if (un->un_f_power_condition_supported) {
6883 		char *pm_condition_name[] = {"STOPPED", "STANDBY",
6884 		    "IDLE", "ACTIVE"};
6885 		SD_TRACE(SD_LOG_IO_PM, un,
6886 		    "sdpower: sending \'%s\' power condition",
6887 		    pm_condition_name[level]);
6888 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
6889 		    sd_pl2pc[level], SD_PATH_DIRECT);
6890 	} else {
6891 		SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
6892 		    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
6893 		sval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
6894 		    ((level == SD_SPINDLE_ON) ? SD_TARGET_START :
6895 		    SD_TARGET_STOP), SD_PATH_DIRECT);
6896 	}
6897 	if (sval != 0) {
6898 		if (sval == EIO)
6899 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
6900 		else
6901 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
6902 	}
6903 
6904 	/* Command failed, check for media present. */
6905 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
6906 		medium_present = FALSE;
6907 	}
6908 
6909 	/*
6910 	 * The conditions of interest here are:
6911 	 *   if a spindle off with media present fails,
6912 	 *	then restore the state and return an error.
6913 	 *   else if a spindle on fails,
6914 	 *	then return an error (there's no state to restore).
6915 	 * In all other cases we setup for the new state
6916 	 * and return success.
6917 	 */
6918 	if (!SD_PM_IS_IO_CAPABLE(un, level)) {
6919 		if ((medium_present == TRUE) && (sval != 0)) {
6920 			/* The stop command from above failed */
6921 			rval = DDI_FAILURE;
6922 			/*
6923 			 * The stop command failed, and we have media
6924 			 * present. Put the level back by calling the
6925 			 * sd_pm_resume() and set the state back to
6926 			 * it's previous value.
6927 			 */
6928 			(void) sd_pm_state_change(un, last_power_level,
6929 			    SD_PM_STATE_ROLLBACK);
6930 			mutex_enter(SD_MUTEX(un));
6931 			un->un_last_state = save_state;
6932 			mutex_exit(SD_MUTEX(un));
6933 		} else if (un->un_f_monitor_media_state) {
6934 			/*
6935 			 * The stop command from above succeeded.
6936 			 * Terminate watch thread in case of removable media
6937 			 * devices going into low power state. This is as per
6938 			 * the requirements of pm framework, otherwise commands
6939 			 * will be generated for the device (through watch
6940 			 * thread), even when the device is in low power state.
6941 			 */
6942 			mutex_enter(SD_MUTEX(un));
6943 			un->un_f_watcht_stopped = FALSE;
6944 			if (un->un_swr_token != NULL) {
6945 				opaque_t temp_token = un->un_swr_token;
6946 				un->un_f_watcht_stopped = TRUE;
6947 				un->un_swr_token = NULL;
6948 				mutex_exit(SD_MUTEX(un));
6949 				(void) scsi_watch_request_terminate(temp_token,
6950 				    SCSI_WATCH_TERMINATE_ALL_WAIT);
6951 			} else {
6952 				mutex_exit(SD_MUTEX(un));
6953 			}
6954 		}
6955 	} else {
6956 		/*
6957 		 * The level requested is I/O capable.
6958 		 * Legacy behavior: return success on a failed spinup
6959 		 * if there is no media in the drive.
6960 		 * Do this by looking at medium_present here.
6961 		 */
6962 		if ((sval != 0) && medium_present) {
6963 			/* The start command from above failed */
6964 			rval = DDI_FAILURE;
6965 		} else {
6966 			/*
6967 			 * The start command from above succeeded
6968 			 * PM resume the devices now that we have
6969 			 * started the disks
6970 			 */
6971 			(void) sd_pm_state_change(un, level,
6972 			    SD_PM_STATE_CHANGE);
6973 
6974 			/*
6975 			 * Resume the watch thread since it was suspended
6976 			 * when the device went into low power mode.
6977 			 */
6978 			if (un->un_f_monitor_media_state) {
6979 				mutex_enter(SD_MUTEX(un));
6980 				if (un->un_f_watcht_stopped == TRUE) {
6981 					opaque_t temp_token;
6982 
6983 					un->un_f_watcht_stopped = FALSE;
6984 					mutex_exit(SD_MUTEX(un));
6985 					temp_token =
6986 					    sd_watch_request_submit(un);
6987 					mutex_enter(SD_MUTEX(un));
6988 					un->un_swr_token = temp_token;
6989 				}
6990 				mutex_exit(SD_MUTEX(un));
6991 			}
6992 		}
6993 	}
6994 
6995 	/*
6996 	 * On exit put the state back to its original value
6997 	 * and broadcast to anyone waiting for the power
6998 	 * change completion.
6999 	 */
7000 	mutex_enter(SD_MUTEX(un));
7001 	un->un_state = state_before_pm;
7002 	cv_broadcast(&un->un_suspend_cv);
7003 	mutex_exit(SD_MUTEX(un));
7004 
7005 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
7006 
7007 	sd_ssc_fini(ssc);
7008 	return (rval);
7009 
7010 sdpower_failed:
7011 
7012 	sd_ssc_fini(ssc);
7013 	return (DDI_FAILURE);
7014 }
7015 
7016 
7017 
7018 /*
7019  *    Function: sdattach
7020  *
7021  * Description: Driver's attach(9e) entry point function.
7022  *
7023  *   Arguments: devi - opaque device info handle
7024  *		cmd  - attach  type
7025  *
7026  * Return Code: DDI_SUCCESS
7027  *		DDI_FAILURE
7028  *
7029  *     Context: Kernel thread context
7030  */
7031 
7032 static int
7033 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
7034 {
7035 	switch (cmd) {
7036 	case DDI_ATTACH:
7037 		return (sd_unit_attach(devi));
7038 	case DDI_RESUME:
7039 		return (sd_ddi_resume(devi));
7040 	default:
7041 		break;
7042 	}
7043 	return (DDI_FAILURE);
7044 }
7045 
7046 
7047 /*
7048  *    Function: sddetach
7049  *
7050  * Description: Driver's detach(9E) entry point function.
7051  *
7052  *   Arguments: devi - opaque device info handle
7053  *		cmd  - detach  type
7054  *
7055  * Return Code: DDI_SUCCESS
7056  *		DDI_FAILURE
7057  *
7058  *     Context: Kernel thread context
7059  */
7060 
7061 static int
7062 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
7063 {
7064 	switch (cmd) {
7065 	case DDI_DETACH:
7066 		return (sd_unit_detach(devi));
7067 	case DDI_SUSPEND:
7068 		return (sd_ddi_suspend(devi));
7069 	default:
7070 		break;
7071 	}
7072 	return (DDI_FAILURE);
7073 }
7074 
7075 
7076 /*
7077  *     Function: sd_sync_with_callback
7078  *
7079  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
7080  *		 state while the callback routine is active.
7081  *
7082  *    Arguments: un: softstate structure for the instance
7083  *
7084  *	Context: Kernel thread context
7085  */
7086 
7087 static void
7088 sd_sync_with_callback(struct sd_lun *un)
7089 {
7090 	ASSERT(un != NULL);
7091 
7092 	mutex_enter(SD_MUTEX(un));
7093 
7094 	ASSERT(un->un_in_callback >= 0);
7095 
7096 	while (un->un_in_callback > 0) {
7097 		mutex_exit(SD_MUTEX(un));
7098 		delay(2);
7099 		mutex_enter(SD_MUTEX(un));
7100 	}
7101 
7102 	mutex_exit(SD_MUTEX(un));
7103 }
7104 
7105 /*
7106  *    Function: sd_unit_attach
7107  *
7108  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
7109  *		the soft state structure for the device and performs
7110  *		all necessary structure and device initializations.
7111  *
7112  *   Arguments: devi: the system's dev_info_t for the device.
7113  *
7114  * Return Code: DDI_SUCCESS if attach is successful.
7115  *		DDI_FAILURE if any part of the attach fails.
7116  *
7117  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
7118  *		Kernel thread context only.  Can sleep.
7119  */
7120 
7121 static int
7122 sd_unit_attach(dev_info_t *devi)
7123 {
7124 	struct	scsi_device	*devp;
7125 	struct	sd_lun		*un;
7126 	char			*variantp;
7127 	char			name_str[48];
7128 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
7129 	int	instance;
7130 	int	rval;
7131 	int	wc_enabled;
7132 	int	wc_changeable;
7133 	int	tgt;
7134 	uint64_t	capacity;
7135 	uint_t		lbasize = 0;
7136 	dev_info_t	*pdip = ddi_get_parent(devi);
7137 	int		offbyone = 0;
7138 	int		geom_label_valid = 0;
7139 	sd_ssc_t	*ssc;
7140 	int		status;
7141 	struct sd_fm_internal	*sfip = NULL;
7142 	int		max_xfer_size;
7143 
7144 	/*
7145 	 * Retrieve the target driver's private data area. This was set
7146 	 * up by the HBA.
7147 	 */
7148 	devp = ddi_get_driver_private(devi);
7149 
7150 	/*
7151 	 * Retrieve the target ID of the device.
7152 	 */
7153 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7154 	    SCSI_ADDR_PROP_TARGET, -1);
7155 
7156 	/*
7157 	 * Since we have no idea what state things were left in by the last
7158 	 * user of the device, set up some 'default' settings, ie. turn 'em
7159 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
7160 	 * Do this before the scsi_probe, which sends an inquiry.
7161 	 * This is a fix for bug (4430280).
7162 	 * Of special importance is wide-xfer. The drive could have been left
7163 	 * in wide transfer mode by the last driver to communicate with it,
7164 	 * this includes us. If that's the case, and if the following is not
7165 	 * setup properly or we don't re-negotiate with the drive prior to
7166 	 * transferring data to/from the drive, it causes bus parity errors,
7167 	 * data overruns, and unexpected interrupts. This first occurred when
7168 	 * the fix for bug (4378686) was made.
7169 	 */
7170 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
7171 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
7172 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
7173 
7174 	/*
7175 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
7176 	 * on a target. Setting it per lun instance actually sets the
7177 	 * capability of this target, which affects those luns already
7178 	 * attached on the same target. So during attach, we can only disable
7179 	 * this capability only when no other lun has been attached on this
7180 	 * target. By doing this, we assume a target has the same tagged-qing
7181 	 * capability for every lun. The condition can be removed when HBA
7182 	 * is changed to support per lun based tagged-qing capability.
7183 	 */
7184 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7185 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
7186 	}
7187 
7188 	/*
7189 	 * Use scsi_probe() to issue an INQUIRY command to the device.
7190 	 * This call will allocate and fill in the scsi_inquiry structure
7191 	 * and point the sd_inq member of the scsi_device structure to it.
7192 	 * If the attach succeeds, then this memory will not be de-allocated
7193 	 * (via scsi_unprobe()) until the instance is detached.
7194 	 */
7195 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
7196 		goto probe_failed;
7197 	}
7198 
7199 	/*
7200 	 * Check the device type as specified in the inquiry data and
7201 	 * claim it if it is of a type that we support.
7202 	 */
7203 	switch (devp->sd_inq->inq_dtype) {
7204 	case DTYPE_DIRECT:
7205 		break;
7206 	case DTYPE_RODIRECT:
7207 		break;
7208 	case DTYPE_OPTICAL:
7209 		break;
7210 	case DTYPE_NOTPRESENT:
7211 	default:
7212 		/* Unsupported device type; fail the attach. */
7213 		goto probe_failed;
7214 	}
7215 
7216 	/*
7217 	 * Allocate the soft state structure for this unit.
7218 	 *
7219 	 * We rely upon this memory being set to all zeroes by
7220 	 * ddi_soft_state_zalloc().  We assume that any member of the
7221 	 * soft state structure that is not explicitly initialized by
7222 	 * this routine will have a value of zero.
7223 	 */
7224 	instance = ddi_get_instance(devp->sd_dev);
7225 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
7226 		goto probe_failed;
7227 	}
7228 
7229 	/*
7230 	 * Retrieve a pointer to the newly-allocated soft state.
7231 	 *
7232 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
7233 	 * was successful, unless something has gone horribly wrong and the
7234 	 * ddi's soft state internals are corrupt (in which case it is
7235 	 * probably better to halt here than just fail the attach....)
7236 	 */
7237 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
7238 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
7239 		    instance);
7240 		/*NOTREACHED*/
7241 	}
7242 
7243 	/*
7244 	 * Link the back ptr of the driver soft state to the scsi_device
7245 	 * struct for this lun.
7246 	 * Save a pointer to the softstate in the driver-private area of
7247 	 * the scsi_device struct.
7248 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
7249 	 * we first set un->un_sd below.
7250 	 */
7251 	un->un_sd = devp;
7252 	devp->sd_private = (opaque_t)un;
7253 
7254 	/*
7255 	 * The following must be after devp is stored in the soft state struct.
7256 	 */
7257 #ifdef SDDEBUG
7258 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7259 	    "%s_unit_attach: un:0x%p instance:%d\n",
7260 	    ddi_driver_name(devi), un, instance);
7261 #endif
7262 
7263 	/*
7264 	 * Set up the device type and node type (for the minor nodes).
7265 	 * By default we assume that the device can at least support the
7266 	 * Common Command Set. Call it a CD-ROM if it reports itself
7267 	 * as a RODIRECT device.
7268 	 */
7269 	switch (devp->sd_inq->inq_dtype) {
7270 	case DTYPE_RODIRECT:
7271 		un->un_node_type = DDI_NT_CD_CHAN;
7272 		un->un_ctype	 = CTYPE_CDROM;
7273 		break;
7274 	case DTYPE_OPTICAL:
7275 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7276 		un->un_ctype	 = CTYPE_ROD;
7277 		break;
7278 	default:
7279 		un->un_node_type = DDI_NT_BLOCK_CHAN;
7280 		un->un_ctype	 = CTYPE_CCS;
7281 		break;
7282 	}
7283 
7284 	/*
7285 	 * Try to read the interconnect type from the HBA.
7286 	 *
7287 	 * Note: This driver is currently compiled as two binaries, a parallel
7288 	 * scsi version (sd) and a fibre channel version (ssd). All functional
7289 	 * differences are determined at compile time. In the future a single
7290 	 * binary will be provided and the interconnect type will be used to
7291 	 * differentiate between fibre and parallel scsi behaviors. At that time
7292 	 * it will be necessary for all fibre channel HBAs to support this
7293 	 * property.
7294 	 *
7295 	 * set un_f_is_fiber to TRUE ( default fiber )
7296 	 */
7297 	un->un_f_is_fibre = TRUE;
7298 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
7299 	case INTERCONNECT_SSA:
7300 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
7301 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7302 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
7303 		break;
7304 	case INTERCONNECT_PARALLEL:
7305 		un->un_f_is_fibre = FALSE;
7306 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7307 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7308 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
7309 		break;
7310 	case INTERCONNECT_SAS:
7311 		un->un_f_is_fibre = FALSE;
7312 		un->un_interconnect_type = SD_INTERCONNECT_SAS;
7313 		un->un_node_type = DDI_NT_BLOCK_SAS;
7314 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7315 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SAS\n", un);
7316 		break;
7317 	case INTERCONNECT_SATA:
7318 		un->un_f_is_fibre = FALSE;
7319 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
7320 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7321 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
7322 		break;
7323 	case INTERCONNECT_FIBRE:
7324 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
7325 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7326 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
7327 		break;
7328 	case INTERCONNECT_FABRIC:
7329 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
7330 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
7331 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7332 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
7333 		break;
7334 	default:
7335 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
7336 		/*
7337 		 * The HBA does not support the "interconnect-type" property
7338 		 * (or did not provide a recognized type).
7339 		 *
7340 		 * Note: This will be obsoleted when a single fibre channel
7341 		 * and parallel scsi driver is delivered. In the meantime the
7342 		 * interconnect type will be set to the platform default.If that
7343 		 * type is not parallel SCSI, it means that we should be
7344 		 * assuming "ssd" semantics. However, here this also means that
7345 		 * the FC HBA is not supporting the "interconnect-type" property
7346 		 * like we expect it to, so log this occurrence.
7347 		 */
7348 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
7349 		if (!SD_IS_PARALLEL_SCSI(un)) {
7350 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7351 			    "sd_unit_attach: un:0x%p Assuming "
7352 			    "INTERCONNECT_FIBRE\n", un);
7353 		} else {
7354 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7355 			    "sd_unit_attach: un:0x%p Assuming "
7356 			    "INTERCONNECT_PARALLEL\n", un);
7357 			un->un_f_is_fibre = FALSE;
7358 		}
7359 #else
7360 		/*
7361 		 * Note: This source will be implemented when a single fibre
7362 		 * channel and parallel scsi driver is delivered. The default
7363 		 * will be to assume that if a device does not support the
7364 		 * "interconnect-type" property it is a parallel SCSI HBA and
7365 		 * we will set the interconnect type for parallel scsi.
7366 		 */
7367 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
7368 		un->un_f_is_fibre = FALSE;
7369 #endif
7370 		break;
7371 	}
7372 
7373 	if (un->un_f_is_fibre == TRUE) {
7374 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
7375 		    SCSI_VERSION_3) {
7376 			switch (un->un_interconnect_type) {
7377 			case SD_INTERCONNECT_FIBRE:
7378 			case SD_INTERCONNECT_SSA:
7379 				un->un_node_type = DDI_NT_BLOCK_WWN;
7380 				break;
7381 			default:
7382 				break;
7383 			}
7384 		}
7385 	}
7386 
7387 	/*
7388 	 * Initialize the Request Sense command for the target
7389 	 */
7390 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
7391 		goto alloc_rqs_failed;
7392 	}
7393 
7394 	/*
7395 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
7396 	 * with separate binary for sd and ssd.
7397 	 *
7398 	 * x86 has 1 binary, un_retry_count is set base on connection type.
7399 	 * The hardcoded values will go away when Sparc uses 1 binary
7400 	 * for sd and ssd.  This hardcoded values need to match
7401 	 * SD_RETRY_COUNT in sddef.h
7402 	 * The value used is base on interconnect type.
7403 	 * fibre = 3, parallel = 5
7404 	 */
7405 #if defined(__x86)
7406 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
7407 #else
7408 	un->un_retry_count = SD_RETRY_COUNT;
7409 #endif
7410 
7411 	/*
7412 	 * Set the per disk retry count to the default number of retries
7413 	 * for disks and CDROMs. This value can be overridden by the
7414 	 * disk property list or an entry in sd.conf.
7415 	 */
7416 	un->un_notready_retry_count =
7417 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
7418 	    : DISK_NOT_READY_RETRY_COUNT(un);
7419 
7420 	/*
7421 	 * Set the busy retry count to the default value of un_retry_count.
7422 	 * This can be overridden by entries in sd.conf or the device
7423 	 * config table.
7424 	 */
7425 	un->un_busy_retry_count = un->un_retry_count;
7426 
7427 	/*
7428 	 * Init the reset threshold for retries.  This number determines
7429 	 * how many retries must be performed before a reset can be issued
7430 	 * (for certain error conditions). This can be overridden by entries
7431 	 * in sd.conf or the device config table.
7432 	 */
7433 	un->un_reset_retry_count = (un->un_retry_count / 2);
7434 
7435 	/*
7436 	 * Set the victim_retry_count to the default un_retry_count
7437 	 */
7438 	un->un_victim_retry_count = (2 * un->un_retry_count);
7439 
7440 	/*
7441 	 * Set the reservation release timeout to the default value of
7442 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
7443 	 * device config table.
7444 	 */
7445 	un->un_reserve_release_time = 5;
7446 
7447 	/*
7448 	 * Set up the default maximum transfer size. Note that this may
7449 	 * get updated later in the attach, when setting up default wide
7450 	 * operations for disks.
7451 	 */
7452 #if defined(__x86)
7453 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
7454 	un->un_partial_dma_supported = 1;
7455 #else
7456 	un->un_max_xfer_size = (uint_t)maxphys;
7457 #endif
7458 
7459 	/*
7460 	 * Get "allow bus device reset" property (defaults to "enabled" if
7461 	 * the property was not defined). This is to disable bus resets for
7462 	 * certain kinds of error recovery. Note: In the future when a run-time
7463 	 * fibre check is available the soft state flag should default to
7464 	 * enabled.
7465 	 */
7466 	if (un->un_f_is_fibre == TRUE) {
7467 		un->un_f_allow_bus_device_reset = TRUE;
7468 	} else {
7469 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7470 		    "allow-bus-device-reset", 1) != 0) {
7471 			un->un_f_allow_bus_device_reset = TRUE;
7472 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7473 			    "sd_unit_attach: un:0x%p Bus device reset "
7474 			    "enabled\n", un);
7475 		} else {
7476 			un->un_f_allow_bus_device_reset = FALSE;
7477 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7478 			    "sd_unit_attach: un:0x%p Bus device reset "
7479 			    "disabled\n", un);
7480 		}
7481 	}
7482 
7483 	/*
7484 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
7485 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
7486 	 *
7487 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
7488 	 * property. The new "variant" property with a value of "atapi" has been
7489 	 * introduced so that future 'variants' of standard SCSI behavior (like
7490 	 * atapi) could be specified by the underlying HBA drivers by supplying
7491 	 * a new value for the "variant" property, instead of having to define a
7492 	 * new property.
7493 	 */
7494 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
7495 		un->un_f_cfg_is_atapi = TRUE;
7496 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7497 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
7498 	}
7499 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
7500 	    &variantp) == DDI_PROP_SUCCESS) {
7501 		if (strcmp(variantp, "atapi") == 0) {
7502 			un->un_f_cfg_is_atapi = TRUE;
7503 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7504 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
7505 		}
7506 		ddi_prop_free(variantp);
7507 	}
7508 
7509 	un->un_cmd_timeout	= SD_IO_TIME;
7510 
7511 	un->un_busy_timeout  = SD_BSY_TIMEOUT;
7512 
7513 	/* Info on current states, statuses, etc. (Updated frequently) */
7514 	un->un_state		= SD_STATE_NORMAL;
7515 	un->un_last_state	= SD_STATE_NORMAL;
7516 
7517 	/* Control & status info for command throttling */
7518 	un->un_throttle		= sd_max_throttle;
7519 	un->un_saved_throttle	= sd_max_throttle;
7520 	un->un_min_throttle	= sd_min_throttle;
7521 
7522 	if (un->un_f_is_fibre == TRUE) {
7523 		un->un_f_use_adaptive_throttle = TRUE;
7524 	} else {
7525 		un->un_f_use_adaptive_throttle = FALSE;
7526 	}
7527 
7528 	/* Removable media support. */
7529 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
7530 	un->un_mediastate		= DKIO_NONE;
7531 	un->un_specified_mediastate	= DKIO_NONE;
7532 
7533 	/* CVs for suspend/resume (PM or DR) */
7534 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
7535 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
7536 
7537 	/* Power management support. */
7538 	un->un_power_level = SD_SPINDLE_UNINIT;
7539 
7540 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
7541 	un->un_f_wcc_inprog = 0;
7542 
7543 	/*
7544 	 * The conf file entry and softstate variable is a forceful override,
7545 	 * meaning a non-zero value must be entered to change the default.
7546 	 */
7547 	un->un_f_disksort_disabled = FALSE;
7548 	un->un_f_rmw_type = SD_RMW_TYPE_DEFAULT;
7549 	un->un_f_enable_rmw = FALSE;
7550 
7551 	/*
7552 	 * GET EVENT STATUS NOTIFICATION media polling enabled by default, but
7553 	 * can be overridden via [s]sd-config-list "mmc-gesn-polling" property.
7554 	 */
7555 	un->un_f_mmc_gesn_polling = TRUE;
7556 
7557 	/*
7558 	 * physical sector size defaults to DEV_BSIZE currently. We can
7559 	 * override this value via the driver configuration file so we must
7560 	 * set it before calling sd_read_unit_properties().
7561 	 */
7562 	un->un_phy_blocksize = DEV_BSIZE;
7563 
7564 	/*
7565 	 * Retrieve the properties from the static driver table or the driver
7566 	 * configuration file (.conf) for this unit and update the soft state
7567 	 * for the device as needed for the indicated properties.
7568 	 * Note: the property configuration needs to occur here as some of the
7569 	 * following routines may have dependencies on soft state flags set
7570 	 * as part of the driver property configuration.
7571 	 */
7572 	sd_read_unit_properties(un);
7573 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7574 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
7575 
7576 	/*
7577 	 * Only if a device has "hotpluggable" property, it is
7578 	 * treated as hotpluggable device. Otherwise, it is
7579 	 * regarded as non-hotpluggable one.
7580 	 */
7581 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
7582 	    -1) != -1) {
7583 		un->un_f_is_hotpluggable = TRUE;
7584 	}
7585 
7586 	/*
7587 	 * set unit's attributes(flags) according to "hotpluggable" and
7588 	 * RMB bit in INQUIRY data.
7589 	 */
7590 	sd_set_unit_attributes(un, devi);
7591 
7592 	/*
7593 	 * By default, we mark the capacity, lbasize, and geometry
7594 	 * as invalid. Only if we successfully read a valid capacity
7595 	 * will we update the un_blockcount and un_tgt_blocksize with the
7596 	 * valid values (the geometry will be validated later).
7597 	 */
7598 	un->un_f_blockcount_is_valid	= FALSE;
7599 	un->un_f_tgt_blocksize_is_valid	= FALSE;
7600 
7601 	/*
7602 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
7603 	 * otherwise.
7604 	 */
7605 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
7606 	un->un_blockcount = 0;
7607 
7608 	/*
7609 	 * Set up the per-instance info needed to determine the correct
7610 	 * CDBs and other info for issuing commands to the target.
7611 	 */
7612 	sd_init_cdb_limits(un);
7613 
7614 	/*
7615 	 * Set up the IO chains to use, based upon the target type.
7616 	 */
7617 	if (un->un_f_non_devbsize_supported) {
7618 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
7619 	} else {
7620 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
7621 	}
7622 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
7623 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
7624 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
7625 
7626 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
7627 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
7628 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
7629 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
7630 
7631 
7632 	if (ISCD(un)) {
7633 		un->un_additional_codes = sd_additional_codes;
7634 	} else {
7635 		un->un_additional_codes = NULL;
7636 	}
7637 
7638 	/*
7639 	 * Create the kstats here so they can be available for attach-time
7640 	 * routines that send commands to the unit (either polled or via
7641 	 * sd_send_scsi_cmd).
7642 	 *
7643 	 * Note: This is a critical sequence that needs to be maintained:
7644 	 *	1) Instantiate the kstats here, before any routines using the
7645 	 *	   iopath (i.e. sd_send_scsi_cmd).
7646 	 *	2) Instantiate and initialize the partition stats
7647 	 *	   (sd_set_pstats).
7648 	 *	3) Initialize the error stats (sd_set_errstats), following
7649 	 *	   sd_validate_geometry(),sd_register_devid(),
7650 	 *	   and sd_cache_control().
7651 	 */
7652 
7653 	un->un_stats = kstat_create(sd_label, instance,
7654 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
7655 	if (un->un_stats != NULL) {
7656 		un->un_stats->ks_lock = SD_MUTEX(un);
7657 		kstat_install(un->un_stats);
7658 	}
7659 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7660 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
7661 
7662 	un->un_unmapstats_ks = kstat_create(sd_label, instance, "unmapstats",
7663 	    "misc", KSTAT_TYPE_NAMED, sizeof (*un->un_unmapstats) /
7664 	    sizeof (kstat_named_t), 0);
7665 	if (un->un_unmapstats_ks) {
7666 		un->un_unmapstats = un->un_unmapstats_ks->ks_data;
7667 
7668 		kstat_named_init(&un->un_unmapstats->us_cmds,
7669 		    "commands", KSTAT_DATA_UINT64);
7670 		kstat_named_init(&un->un_unmapstats->us_errs,
7671 		    "errors", KSTAT_DATA_UINT64);
7672 		kstat_named_init(&un->un_unmapstats->us_extents,
7673 		    "extents", KSTAT_DATA_UINT64);
7674 		kstat_named_init(&un->un_unmapstats->us_bytes,
7675 		    "bytes", KSTAT_DATA_UINT64);
7676 
7677 		kstat_install(un->un_unmapstats_ks);
7678 	} else {
7679 		cmn_err(CE_NOTE, "!Cannot create unmap kstats for disk %d",
7680 		    instance);
7681 	}
7682 
7683 	sd_create_errstats(un, instance);
7684 	if (un->un_errstats == NULL) {
7685 		goto create_errstats_failed;
7686 	}
7687 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7688 	    "sd_unit_attach: un:0x%p errstats created\n", un);
7689 
7690 	/*
7691 	 * The following if/else code was relocated here from below as part
7692 	 * of the fix for bug (4430280). However with the default setup added
7693 	 * on entry to this routine, it's no longer absolutely necessary for
7694 	 * this to be before the call to sd_spin_up_unit.
7695 	 */
7696 	if (SD_IS_PARALLEL_SCSI(un) || SD_IS_SERIAL(un)) {
7697 		int tq_trigger_flag = (((devp->sd_inq->inq_ansi == 4) ||
7698 		    (devp->sd_inq->inq_ansi == 5)) &&
7699 		    devp->sd_inq->inq_bque) || devp->sd_inq->inq_cmdque;
7700 
7701 		/*
7702 		 * If tagged queueing is supported by the target
7703 		 * and by the host adapter then we will enable it
7704 		 */
7705 		un->un_tagflags = 0;
7706 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) && tq_trigger_flag &&
7707 		    (un->un_f_arq_enabled == TRUE)) {
7708 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
7709 			    1, 1) == 1) {
7710 				un->un_tagflags = FLAG_STAG;
7711 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7712 				    "sd_unit_attach: un:0x%p tag queueing "
7713 				    "enabled\n", un);
7714 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
7715 			    "untagged-qing", 0) == 1) {
7716 				un->un_f_opt_queueing = TRUE;
7717 				un->un_saved_throttle = un->un_throttle =
7718 				    min(un->un_throttle, 3);
7719 			} else {
7720 				un->un_f_opt_queueing = FALSE;
7721 				un->un_saved_throttle = un->un_throttle = 1;
7722 			}
7723 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
7724 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
7725 			/* The Host Adapter supports internal queueing. */
7726 			un->un_f_opt_queueing = TRUE;
7727 			un->un_saved_throttle = un->un_throttle =
7728 			    min(un->un_throttle, 3);
7729 		} else {
7730 			un->un_f_opt_queueing = FALSE;
7731 			un->un_saved_throttle = un->un_throttle = 1;
7732 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7733 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
7734 		}
7735 
7736 		/*
7737 		 * Enable large transfers for SATA/SAS drives
7738 		 */
7739 		if (SD_IS_SERIAL(un)) {
7740 			un->un_max_xfer_size =
7741 			    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7742 			    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7743 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7744 			    "sd_unit_attach: un:0x%p max transfer "
7745 			    "size=0x%x\n", un, un->un_max_xfer_size);
7746 
7747 		}
7748 
7749 		/* Setup or tear down default wide operations for disks */
7750 
7751 		/*
7752 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
7753 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
7754 		 * system and be set to different values. In the future this
7755 		 * code may need to be updated when the ssd module is
7756 		 * obsoleted and removed from the system. (4299588)
7757 		 */
7758 		if (SD_IS_PARALLEL_SCSI(un) &&
7759 		    (devp->sd_inq->inq_rdf == RDF_SCSI2) &&
7760 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
7761 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7762 			    1, 1) == 1) {
7763 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7764 				    "sd_unit_attach: un:0x%p Wide Transfer "
7765 				    "enabled\n", un);
7766 			}
7767 
7768 			/*
7769 			 * If tagged queuing has also been enabled, then
7770 			 * enable large xfers
7771 			 */
7772 			if (un->un_saved_throttle == sd_max_throttle) {
7773 				un->un_max_xfer_size =
7774 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7775 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
7776 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7777 				    "sd_unit_attach: un:0x%p max transfer "
7778 				    "size=0x%x\n", un, un->un_max_xfer_size);
7779 			}
7780 		} else {
7781 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7782 			    0, 1) == 1) {
7783 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7784 				    "sd_unit_attach: un:0x%p "
7785 				    "Wide Transfer disabled\n", un);
7786 			}
7787 		}
7788 	} else {
7789 		un->un_tagflags = FLAG_STAG;
7790 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
7791 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
7792 	}
7793 
7794 	/*
7795 	 * If this target supports LUN reset, try to enable it.
7796 	 */
7797 	if (un->un_f_lun_reset_enabled) {
7798 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
7799 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7800 			    "un:0x%p lun_reset capability set\n", un);
7801 		} else {
7802 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7803 			    "un:0x%p lun-reset capability not set\n", un);
7804 		}
7805 	}
7806 
7807 	/*
7808 	 * Adjust the maximum transfer size. This is to fix
7809 	 * the problem of partial DMA support on SPARC. Some
7810 	 * HBA driver, like aac, has very small dma_attr_maxxfer
7811 	 * size, which requires partial DMA support on SPARC.
7812 	 * In the future the SPARC pci nexus driver may solve
7813 	 * the problem instead of this fix.
7814 	 */
7815 	max_xfer_size = scsi_ifgetcap(SD_ADDRESS(un), "dma-max", 1);
7816 	if ((max_xfer_size > 0) && (max_xfer_size < un->un_max_xfer_size)) {
7817 		/* We need DMA partial even on sparc to ensure sddump() works */
7818 		un->un_max_xfer_size = max_xfer_size;
7819 		if (un->un_partial_dma_supported == 0)
7820 			un->un_partial_dma_supported = 1;
7821 	}
7822 	if (ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7823 	    DDI_PROP_DONTPASS, "buf_break", 0) == 1) {
7824 		if (ddi_xbuf_attr_setup_brk(un->un_xbuf_attr,
7825 		    un->un_max_xfer_size) == 1) {
7826 			un->un_buf_breakup_supported = 1;
7827 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7828 			    "un:0x%p Buf breakup enabled\n", un);
7829 		}
7830 	}
7831 
7832 	/*
7833 	 * Set PKT_DMA_PARTIAL flag.
7834 	 */
7835 	if (un->un_partial_dma_supported == 1) {
7836 		un->un_pkt_flags = PKT_DMA_PARTIAL;
7837 	} else {
7838 		un->un_pkt_flags = 0;
7839 	}
7840 
7841 	/* Initialize sd_ssc_t for internal uscsi commands */
7842 	ssc = sd_ssc_init(un);
7843 	scsi_fm_init(devp);
7844 
7845 	/*
7846 	 * Allocate memory for SCSI FMA stuffs.
7847 	 */
7848 	un->un_fm_private =
7849 	    kmem_zalloc(sizeof (struct sd_fm_internal), KM_SLEEP);
7850 	sfip = (struct sd_fm_internal *)un->un_fm_private;
7851 	sfip->fm_ssc.ssc_uscsi_cmd = &sfip->fm_ucmd;
7852 	sfip->fm_ssc.ssc_uscsi_info = &sfip->fm_uinfo;
7853 	sfip->fm_ssc.ssc_un = un;
7854 
7855 	if (ISCD(un) ||
7856 	    un->un_f_has_removable_media ||
7857 	    devp->sd_fm_capable == DDI_FM_NOT_CAPABLE) {
7858 		/*
7859 		 * We don't touch CDROM or the DDI_FM_NOT_CAPABLE device.
7860 		 * Their log are unchanged.
7861 		 */
7862 		sfip->fm_log_level = SD_FM_LOG_NSUP;
7863 	} else {
7864 		/*
7865 		 * If enter here, it should be non-CDROM and FM-capable
7866 		 * device, and it will not keep the old scsi_log as before
7867 		 * in /var/adm/messages. However, the property
7868 		 * "fm-scsi-log" will control whether the FM telemetry will
7869 		 * be logged in /var/adm/messages.
7870 		 */
7871 		int fm_scsi_log;
7872 		fm_scsi_log = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
7873 		    DDI_PROP_DONTPASS | DDI_PROP_NOTPROM, "fm-scsi-log", 0);
7874 
7875 		if (fm_scsi_log)
7876 			sfip->fm_log_level = SD_FM_LOG_EREPORT;
7877 		else
7878 			sfip->fm_log_level = SD_FM_LOG_SILENT;
7879 	}
7880 
7881 	/*
7882 	 * At this point in the attach, we have enough info in the
7883 	 * soft state to be able to issue commands to the target.
7884 	 *
7885 	 * All command paths used below MUST issue their commands as
7886 	 * SD_PATH_DIRECT. This is important as intermediate layers
7887 	 * are not all initialized yet (such as PM).
7888 	 */
7889 
7890 	/*
7891 	 * Send a TEST UNIT READY command to the device. This should clear
7892 	 * any outstanding UNIT ATTENTION that may be present.
7893 	 *
7894 	 * Note: Don't check for success, just track if there is a reservation,
7895 	 * this is a throw away command to clear any unit attentions.
7896 	 *
7897 	 * Note: This MUST be the first command issued to the target during
7898 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
7899 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
7900 	 * with attempts at spinning up a device with no media.
7901 	 */
7902 	status = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
7903 	if (status != 0) {
7904 		if (status == EACCES)
7905 			reservation_flag = SD_TARGET_IS_RESERVED;
7906 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
7907 	}
7908 
7909 	/*
7910 	 * If the device is NOT a removable media device, attempt to spin
7911 	 * it up (using the START_STOP_UNIT command) and read its capacity
7912 	 * (using the READ CAPACITY command).  Note, however, that either
7913 	 * of these could fail and in some cases we would continue with
7914 	 * the attach despite the failure (see below).
7915 	 */
7916 	if (un->un_f_descr_format_supported) {
7917 
7918 		switch (sd_spin_up_unit(ssc)) {
7919 		case 0:
7920 			/*
7921 			 * Spin-up was successful; now try to read the
7922 			 * capacity.  If successful then save the results
7923 			 * and mark the capacity & lbasize as valid.
7924 			 */
7925 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7926 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
7927 
7928 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
7929 			    &lbasize, SD_PATH_DIRECT);
7930 
7931 			switch (status) {
7932 			case 0: {
7933 				if (capacity > DK_MAX_BLOCKS) {
7934 #ifdef _LP64
7935 					if ((capacity + 1) >
7936 					    SD_GROUP1_MAX_ADDRESS) {
7937 						/*
7938 						 * Enable descriptor format
7939 						 * sense data so that we can
7940 						 * get 64 bit sense data
7941 						 * fields.
7942 						 */
7943 						sd_enable_descr_sense(ssc);
7944 					}
7945 #else
7946 					/* 32-bit kernels can't handle this */
7947 					scsi_log(SD_DEVINFO(un),
7948 					    sd_label, CE_WARN,
7949 					    "disk has %llu blocks, which "
7950 					    "is too large for a 32-bit "
7951 					    "kernel", capacity);
7952 
7953 #if defined(__x86)
7954 					/*
7955 					 * 1TB disk was treated as (1T - 512)B
7956 					 * in the past, so that it might have
7957 					 * valid VTOC and solaris partitions,
7958 					 * we have to allow it to continue to
7959 					 * work.
7960 					 */
7961 					if (capacity - 1 > DK_MAX_BLOCKS)
7962 #endif
7963 					goto spinup_failed;
7964 #endif
7965 				}
7966 
7967 				/*
7968 				 * Here it's not necessary to check the case:
7969 				 * the capacity of the device is bigger than
7970 				 * what the max hba cdb can support. Because
7971 				 * sd_send_scsi_READ_CAPACITY will retrieve
7972 				 * the capacity by sending USCSI command, which
7973 				 * is constrained by the max hba cdb. Actually,
7974 				 * sd_send_scsi_READ_CAPACITY will return
7975 				 * EINVAL when using bigger cdb than required
7976 				 * cdb length. Will handle this case in
7977 				 * "case EINVAL".
7978 				 */
7979 
7980 				/*
7981 				 * The following relies on
7982 				 * sd_send_scsi_READ_CAPACITY never
7983 				 * returning 0 for capacity and/or lbasize.
7984 				 */
7985 				sd_update_block_info(un, lbasize, capacity);
7986 
7987 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7988 				    "sd_unit_attach: un:0x%p capacity = %ld "
7989 				    "blocks; lbasize= %ld.\n", un,
7990 				    un->un_blockcount, un->un_tgt_blocksize);
7991 
7992 				break;
7993 			}
7994 			case EINVAL:
7995 				/*
7996 				 * In the case where the max-cdb-length property
7997 				 * is smaller than the required CDB length for
7998 				 * a SCSI device, a target driver can fail to
7999 				 * attach to that device.
8000 				 */
8001 				scsi_log(SD_DEVINFO(un),
8002 				    sd_label, CE_WARN,
8003 				    "disk capacity is too large "
8004 				    "for current cdb length");
8005 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8006 
8007 				goto spinup_failed;
8008 			case EACCES:
8009 				/*
8010 				 * Should never get here if the spin-up
8011 				 * succeeded, but code it in anyway.
8012 				 * From here, just continue with the attach...
8013 				 */
8014 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
8015 				    "sd_unit_attach: un:0x%p "
8016 				    "sd_send_scsi_READ_CAPACITY "
8017 				    "returned reservation conflict\n", un);
8018 				reservation_flag = SD_TARGET_IS_RESERVED;
8019 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8020 				break;
8021 			default:
8022 				/*
8023 				 * Likewise, should never get here if the
8024 				 * spin-up succeeded. Just continue with
8025 				 * the attach...
8026 				 */
8027 				if (status == EIO)
8028 					sd_ssc_assessment(ssc,
8029 					    SD_FMT_STATUS_CHECK);
8030 				else
8031 					sd_ssc_assessment(ssc,
8032 					    SD_FMT_IGNORE);
8033 				break;
8034 			}
8035 			break;
8036 		case EACCES:
8037 			/*
8038 			 * Device is reserved by another host.  In this case
8039 			 * we could not spin it up or read the capacity, but
8040 			 * we continue with the attach anyway.
8041 			 */
8042 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8043 			    "sd_unit_attach: un:0x%p spin-up reservation "
8044 			    "conflict.\n", un);
8045 			reservation_flag = SD_TARGET_IS_RESERVED;
8046 			break;
8047 		default:
8048 			/* Fail the attach if the spin-up failed. */
8049 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
8050 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
8051 			goto spinup_failed;
8052 		}
8053 
8054 	}
8055 
8056 	/*
8057 	 * Check to see if this is a MMC drive
8058 	 */
8059 	if (ISCD(un)) {
8060 		sd_set_mmc_caps(ssc);
8061 	}
8062 
8063 	/*
8064 	 * Add a zero-length attribute to tell the world we support
8065 	 * kernel ioctls (for layered drivers)
8066 	 */
8067 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8068 	    DDI_KERNEL_IOCTL, NULL, 0);
8069 
8070 	/*
8071 	 * Add a boolean property to tell the world we support
8072 	 * the B_FAILFAST flag (for layered drivers)
8073 	 */
8074 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
8075 	    "ddi-failfast-supported", NULL, 0);
8076 
8077 	/*
8078 	 * Initialize power management
8079 	 */
8080 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
8081 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
8082 	sd_setup_pm(ssc, devi);
8083 	if (un->un_f_pm_is_enabled == FALSE) {
8084 		/*
8085 		 * For performance, point to a jump table that does
8086 		 * not include pm.
8087 		 * The direct and priority chains don't change with PM.
8088 		 *
8089 		 * Note: this is currently done based on individual device
8090 		 * capabilities. When an interface for determining system
8091 		 * power enabled state becomes available, or when additional
8092 		 * layers are added to the command chain, these values will
8093 		 * have to be re-evaluated for correctness.
8094 		 */
8095 		if (un->un_f_non_devbsize_supported) {
8096 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
8097 		} else {
8098 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
8099 		}
8100 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8101 	}
8102 
8103 	/*
8104 	 * This property is set to 0 by HA software to avoid retries
8105 	 * on a reserved disk. (The preferred property name is
8106 	 * "retry-on-reservation-conflict") (1189689)
8107 	 *
8108 	 * Note: The use of a global here can have unintended consequences. A
8109 	 * per instance variable is preferable to match the capabilities of
8110 	 * different underlying hba's (4402600)
8111 	 */
8112 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
8113 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
8114 	    sd_retry_on_reservation_conflict);
8115 	if (sd_retry_on_reservation_conflict != 0) {
8116 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
8117 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
8118 		    sd_retry_on_reservation_conflict);
8119 	}
8120 
8121 	/* Set up options for QFULL handling. */
8122 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8123 	    "qfull-retries", -1)) != -1) {
8124 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
8125 		    rval, 1);
8126 	}
8127 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
8128 	    "qfull-retry-interval", -1)) != -1) {
8129 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
8130 		    rval, 1);
8131 	}
8132 
8133 	/*
8134 	 * This just prints a message that announces the existence of the
8135 	 * device. The message is always printed in the system logfile, but
8136 	 * only appears on the console if the system is booted with the
8137 	 * -v (verbose) argument.
8138 	 */
8139 	ddi_report_dev(devi);
8140 
8141 	un->un_mediastate = DKIO_NONE;
8142 
8143 	/*
8144 	 * Check Block Device Characteristics VPD.
8145 	 */
8146 	sd_check_bdc_vpd(ssc);
8147 
8148 	/*
8149 	 * Check whether the drive is in emulation mode.
8150 	 */
8151 	sd_check_emulation_mode(ssc);
8152 
8153 	cmlb_alloc_handle(&un->un_cmlbhandle);
8154 
8155 #if defined(__x86)
8156 	/*
8157 	 * On x86, compensate for off-by-1 legacy error
8158 	 */
8159 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
8160 	    (lbasize == un->un_sys_blocksize))
8161 		offbyone = CMLB_OFF_BY_ONE;
8162 #endif
8163 
8164 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
8165 	    VOID2BOOLEAN(un->un_f_has_removable_media != 0),
8166 	    VOID2BOOLEAN(un->un_f_is_hotpluggable != 0),
8167 	    un->un_node_type, offbyone, un->un_cmlbhandle,
8168 	    (void *)SD_PATH_DIRECT) != 0) {
8169 		goto cmlb_attach_failed;
8170 	}
8171 
8172 
8173 	/*
8174 	 * Read and validate the device's geometry (ie, disk label)
8175 	 * A new unformatted drive will not have a valid geometry, but
8176 	 * the driver needs to successfully attach to this device so
8177 	 * the drive can be formatted via ioctls.
8178 	 */
8179 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
8180 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
8181 
8182 	mutex_enter(SD_MUTEX(un));
8183 
8184 	/*
8185 	 * Read and initialize the devid for the unit.
8186 	 */
8187 	if (un->un_f_devid_supported) {
8188 		sd_register_devid(ssc, devi, reservation_flag);
8189 	}
8190 	mutex_exit(SD_MUTEX(un));
8191 
8192 #if (defined(__fibre))
8193 	/*
8194 	 * Register callbacks for fibre only.  You can't do this solely
8195 	 * on the basis of the devid_type because this is hba specific.
8196 	 * We need to query our hba capabilities to find out whether to
8197 	 * register or not.
8198 	 */
8199 	if (un->un_f_is_fibre) {
8200 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
8201 			sd_init_event_callbacks(un);
8202 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8203 			    "sd_unit_attach: un:0x%p event callbacks inserted",
8204 			    un);
8205 		}
8206 	}
8207 #endif
8208 
8209 	if (un->un_f_opt_disable_cache == TRUE) {
8210 		/*
8211 		 * Disable both read cache and write cache.  This is
8212 		 * the historic behavior of the keywords in the config file.
8213 		 */
8214 		if (sd_cache_control(ssc, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
8215 		    0) {
8216 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8217 			    "sd_unit_attach: un:0x%p Could not disable "
8218 			    "caching", un);
8219 			goto devid_failed;
8220 		}
8221 	}
8222 
8223 	/*
8224 	 * Check the value of the WCE bit and if it's allowed to be changed,
8225 	 * set un_f_write_cache_enabled and un_f_cache_mode_changeable
8226 	 * accordingly.
8227 	 */
8228 	(void) sd_get_write_cache_enabled(ssc, &wc_enabled);
8229 	sd_get_write_cache_changeable(ssc, &wc_changeable);
8230 	mutex_enter(SD_MUTEX(un));
8231 	un->un_f_write_cache_enabled = (wc_enabled != 0);
8232 	un->un_f_cache_mode_changeable = (wc_changeable != 0);
8233 	mutex_exit(SD_MUTEX(un));
8234 
8235 	if ((un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR &&
8236 	    un->un_tgt_blocksize != DEV_BSIZE) ||
8237 	    un->un_f_enable_rmw) {
8238 		if (!(un->un_wm_cache)) {
8239 			(void) snprintf(name_str, sizeof (name_str),
8240 			    "%s%d_cache",
8241 			    ddi_driver_name(SD_DEVINFO(un)),
8242 			    ddi_get_instance(SD_DEVINFO(un)));
8243 			un->un_wm_cache = kmem_cache_create(
8244 			    name_str, sizeof (struct sd_w_map),
8245 			    8, sd_wm_cache_constructor,
8246 			    sd_wm_cache_destructor, NULL,
8247 			    (void *)un, NULL, 0);
8248 			if (!(un->un_wm_cache)) {
8249 				goto wm_cache_failed;
8250 			}
8251 		}
8252 	}
8253 
8254 	/*
8255 	 * Check the value of the NV_SUP bit and set
8256 	 * un_f_suppress_cache_flush accordingly.
8257 	 */
8258 	sd_get_nv_sup(ssc);
8259 
8260 	/*
8261 	 * Find out what type of reservation this disk supports.
8262 	 */
8263 	status = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS, 0, NULL);
8264 
8265 	switch (status) {
8266 	case 0:
8267 		/*
8268 		 * SCSI-3 reservations are supported.
8269 		 */
8270 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8271 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8272 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
8273 		break;
8274 	case ENOTSUP:
8275 		/*
8276 		 * The PERSISTENT RESERVE IN command would not be recognized by
8277 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
8278 		 */
8279 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8280 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
8281 		un->un_reservation_type = SD_SCSI2_RESERVATION;
8282 
8283 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8284 		break;
8285 	default:
8286 		/*
8287 		 * default to SCSI-3 reservations
8288 		 */
8289 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
8290 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
8291 		un->un_reservation_type = SD_SCSI3_RESERVATION;
8292 
8293 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
8294 		break;
8295 	}
8296 
8297 	/*
8298 	 * Set the pstat and error stat values here, so data obtained during the
8299 	 * previous attach-time routines is available.
8300 	 *
8301 	 * Note: This is a critical sequence that needs to be maintained:
8302 	 *	1) Instantiate the kstats before any routines using the iopath
8303 	 *	   (i.e. sd_send_scsi_cmd).
8304 	 *	2) Initialize the error stats (sd_set_errstats) and partition
8305 	 *	   stats (sd_set_pstats)here, following
8306 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
8307 	 *	   sd_cache_control().
8308 	 */
8309 
8310 	if (un->un_f_pkstats_enabled && geom_label_valid) {
8311 		sd_set_pstats(un);
8312 		SD_TRACE(SD_LOG_IO_PARTITION, un,
8313 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
8314 	}
8315 
8316 	sd_set_errstats(un);
8317 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8318 	    "sd_unit_attach: un:0x%p errstats set\n", un);
8319 
8320 	sd_setup_blk_limits(ssc);
8321 
8322 	/*
8323 	 * After successfully attaching an instance, we record the information
8324 	 * of how many luns have been attached on the relative target and
8325 	 * controller for parallel SCSI. This information is used when sd tries
8326 	 * to set the tagged queuing capability in HBA.
8327 	 */
8328 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8329 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
8330 	}
8331 
8332 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
8333 	    "sd_unit_attach: un:0x%p exit success\n", un);
8334 
8335 	/* Uninitialize sd_ssc_t pointer */
8336 	sd_ssc_fini(ssc);
8337 
8338 	return (DDI_SUCCESS);
8339 
8340 	/*
8341 	 * An error occurred during the attach; clean up & return failure.
8342 	 */
8343 wm_cache_failed:
8344 devid_failed:
8345 	ddi_remove_minor_node(devi, NULL);
8346 
8347 cmlb_attach_failed:
8348 	/*
8349 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8350 	 */
8351 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8352 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8353 
8354 	/*
8355 	 * Refer to the comments of setting tagged-qing in the beginning of
8356 	 * sd_unit_attach. We can only disable tagged queuing when there is
8357 	 * no lun attached on the target.
8358 	 */
8359 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
8360 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8361 	}
8362 
8363 	if (un->un_f_is_fibre == FALSE) {
8364 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8365 	}
8366 
8367 spinup_failed:
8368 
8369 	/* Uninitialize sd_ssc_t pointer */
8370 	sd_ssc_fini(ssc);
8371 
8372 	mutex_enter(SD_MUTEX(un));
8373 
8374 	/* Deallocate SCSI FMA memory spaces */
8375 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8376 
8377 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
8378 	if (un->un_direct_priority_timeid != NULL) {
8379 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8380 		un->un_direct_priority_timeid = NULL;
8381 		mutex_exit(SD_MUTEX(un));
8382 		(void) untimeout(temp_id);
8383 		mutex_enter(SD_MUTEX(un));
8384 	}
8385 
8386 	/* Cancel any pending start/stop timeouts */
8387 	if (un->un_startstop_timeid != NULL) {
8388 		timeout_id_t temp_id = un->un_startstop_timeid;
8389 		un->un_startstop_timeid = NULL;
8390 		mutex_exit(SD_MUTEX(un));
8391 		(void) untimeout(temp_id);
8392 		mutex_enter(SD_MUTEX(un));
8393 	}
8394 
8395 	/* Cancel any pending reset-throttle timeouts */
8396 	if (un->un_reset_throttle_timeid != NULL) {
8397 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8398 		un->un_reset_throttle_timeid = NULL;
8399 		mutex_exit(SD_MUTEX(un));
8400 		(void) untimeout(temp_id);
8401 		mutex_enter(SD_MUTEX(un));
8402 	}
8403 
8404 	/* Cancel rmw warning message timeouts */
8405 	if (un->un_rmw_msg_timeid != NULL) {
8406 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8407 		un->un_rmw_msg_timeid = NULL;
8408 		mutex_exit(SD_MUTEX(un));
8409 		(void) untimeout(temp_id);
8410 		mutex_enter(SD_MUTEX(un));
8411 	}
8412 
8413 	/* Cancel any pending retry timeouts */
8414 	if (un->un_retry_timeid != NULL) {
8415 		timeout_id_t temp_id = un->un_retry_timeid;
8416 		un->un_retry_timeid = NULL;
8417 		mutex_exit(SD_MUTEX(un));
8418 		(void) untimeout(temp_id);
8419 		mutex_enter(SD_MUTEX(un));
8420 	}
8421 
8422 	/* Cancel any pending delayed cv broadcast timeouts */
8423 	if (un->un_dcvb_timeid != NULL) {
8424 		timeout_id_t temp_id = un->un_dcvb_timeid;
8425 		un->un_dcvb_timeid = NULL;
8426 		mutex_exit(SD_MUTEX(un));
8427 		(void) untimeout(temp_id);
8428 		mutex_enter(SD_MUTEX(un));
8429 	}
8430 
8431 	mutex_exit(SD_MUTEX(un));
8432 
8433 	/* There should not be any in-progress I/O so ASSERT this check */
8434 	ASSERT(un->un_ncmds_in_transport == 0);
8435 	ASSERT(un->un_ncmds_in_driver == 0);
8436 
8437 	/* Do not free the softstate if the callback routine is active */
8438 	sd_sync_with_callback(un);
8439 
8440 	/*
8441 	 * Partition stats apparently are not used with removables. These would
8442 	 * not have been created during attach, so no need to clean them up...
8443 	 */
8444 	if (un->un_errstats != NULL) {
8445 		kstat_delete(un->un_errstats);
8446 		un->un_errstats = NULL;
8447 	}
8448 
8449 create_errstats_failed:
8450 
8451 	if (un->un_stats != NULL) {
8452 		kstat_delete(un->un_stats);
8453 		un->un_stats = NULL;
8454 	}
8455 
8456 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8457 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8458 
8459 	ddi_prop_remove_all(devi);
8460 	cv_destroy(&un->un_state_cv);
8461 
8462 	sd_free_rqs(un);
8463 
8464 alloc_rqs_failed:
8465 
8466 	devp->sd_private = NULL;
8467 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
8468 
8469 	/*
8470 	 * Note: the man pages are unclear as to whether or not doing a
8471 	 * ddi_soft_state_free(sd_state, instance) is the right way to
8472 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
8473 	 * ddi_get_soft_state() fails.  The implication seems to be
8474 	 * that the get_soft_state cannot fail if the zalloc succeeds.
8475 	 */
8476 #ifndef XPV_HVM_DRIVER
8477 	ddi_soft_state_free(sd_state, instance);
8478 #endif /* !XPV_HVM_DRIVER */
8479 
8480 probe_failed:
8481 	scsi_unprobe(devp);
8482 
8483 	return (DDI_FAILURE);
8484 }
8485 
8486 
8487 /*
8488  *    Function: sd_unit_detach
8489  *
8490  * Description: Performs DDI_DETACH processing for sddetach().
8491  *
8492  * Return Code: DDI_SUCCESS
8493  *		DDI_FAILURE
8494  *
8495  *     Context: Kernel thread context
8496  */
8497 
8498 static int
8499 sd_unit_detach(dev_info_t *devi)
8500 {
8501 	struct scsi_device	*devp;
8502 	struct sd_lun		*un;
8503 	int			i;
8504 	int			tgt;
8505 	dev_t			dev;
8506 	dev_info_t		*pdip = ddi_get_parent(devi);
8507 	int			instance = ddi_get_instance(devi);
8508 
8509 	/*
8510 	 * Fail the detach for any of the following:
8511 	 *  - Unable to get the sd_lun struct for the instance
8512 	 *  - There is pending I/O
8513 	 */
8514 	devp = ddi_get_driver_private(devi);
8515 	if ((devp == NULL) ||
8516 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
8517 	    (un->un_ncmds_in_driver != 0)) {
8518 		return (DDI_FAILURE);
8519 	}
8520 
8521 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
8522 
8523 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
8524 	    SCSI_ADDR_PROP_TARGET, -1);
8525 
8526 	dev = sd_make_device(SD_DEVINFO(un));
8527 
8528 #ifndef lint
8529 	_NOTE(COMPETING_THREADS_NOW);
8530 #endif
8531 
8532 	mutex_enter(SD_MUTEX(un));
8533 
8534 	/*
8535 	 * Fail the detach if there are any outstanding layered
8536 	 * opens on this device.
8537 	 */
8538 	for (i = 0; i < NDKMAP; i++) {
8539 		if (un->un_ocmap.lyropen[i] != 0) {
8540 			goto err_notclosed;
8541 		}
8542 	}
8543 
8544 	/*
8545 	 * Verify there are NO outstanding commands issued to this device.
8546 	 * ie, un_ncmds_in_transport == 0.
8547 	 * It's possible to have outstanding commands through the physio
8548 	 * code path, even though everything's closed.
8549 	 */
8550 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
8551 	    (un->un_direct_priority_timeid != NULL) ||
8552 	    (un->un_state == SD_STATE_RWAIT)) {
8553 		mutex_exit(SD_MUTEX(un));
8554 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8555 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
8556 		goto err_stillbusy;
8557 	}
8558 
8559 	/*
8560 	 * If we have the device reserved, release the reservation.
8561 	 */
8562 	if ((un->un_resvd_status & SD_RESERVE) &&
8563 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
8564 		mutex_exit(SD_MUTEX(un));
8565 		/*
8566 		 * Note: sd_reserve_release sends a command to the device
8567 		 * via the sd_ioctlcmd() path, and can sleep.
8568 		 */
8569 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
8570 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8571 			    "sd_dr_detach: Cannot release reservation \n");
8572 		}
8573 	} else {
8574 		mutex_exit(SD_MUTEX(un));
8575 	}
8576 
8577 	/*
8578 	 * Untimeout any reserve recover, throttle reset, restart unit
8579 	 * and delayed broadcast timeout threads. Protect the timeout pointer
8580 	 * from getting nulled by their callback functions.
8581 	 */
8582 	mutex_enter(SD_MUTEX(un));
8583 	if (un->un_resvd_timeid != NULL) {
8584 		timeout_id_t temp_id = un->un_resvd_timeid;
8585 		un->un_resvd_timeid = NULL;
8586 		mutex_exit(SD_MUTEX(un));
8587 		(void) untimeout(temp_id);
8588 		mutex_enter(SD_MUTEX(un));
8589 	}
8590 
8591 	if (un->un_reset_throttle_timeid != NULL) {
8592 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
8593 		un->un_reset_throttle_timeid = NULL;
8594 		mutex_exit(SD_MUTEX(un));
8595 		(void) untimeout(temp_id);
8596 		mutex_enter(SD_MUTEX(un));
8597 	}
8598 
8599 	if (un->un_startstop_timeid != NULL) {
8600 		timeout_id_t temp_id = un->un_startstop_timeid;
8601 		un->un_startstop_timeid = NULL;
8602 		mutex_exit(SD_MUTEX(un));
8603 		(void) untimeout(temp_id);
8604 		mutex_enter(SD_MUTEX(un));
8605 	}
8606 
8607 	if (un->un_rmw_msg_timeid != NULL) {
8608 		timeout_id_t temp_id = un->un_rmw_msg_timeid;
8609 		un->un_rmw_msg_timeid = NULL;
8610 		mutex_exit(SD_MUTEX(un));
8611 		(void) untimeout(temp_id);
8612 		mutex_enter(SD_MUTEX(un));
8613 	}
8614 
8615 	if (un->un_dcvb_timeid != NULL) {
8616 		timeout_id_t temp_id = un->un_dcvb_timeid;
8617 		un->un_dcvb_timeid = NULL;
8618 		mutex_exit(SD_MUTEX(un));
8619 		(void) untimeout(temp_id);
8620 	} else {
8621 		mutex_exit(SD_MUTEX(un));
8622 	}
8623 
8624 	/* Remove any pending reservation reclaim requests for this device */
8625 	sd_rmv_resv_reclaim_req(dev);
8626 
8627 	mutex_enter(SD_MUTEX(un));
8628 
8629 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
8630 	if (un->un_direct_priority_timeid != NULL) {
8631 		timeout_id_t temp_id = un->un_direct_priority_timeid;
8632 		un->un_direct_priority_timeid = NULL;
8633 		mutex_exit(SD_MUTEX(un));
8634 		(void) untimeout(temp_id);
8635 		mutex_enter(SD_MUTEX(un));
8636 	}
8637 
8638 	/* Cancel any active multi-host disk watch thread requests */
8639 	if (un->un_mhd_token != NULL) {
8640 		mutex_exit(SD_MUTEX(un));
8641 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
8642 		if (scsi_watch_request_terminate(un->un_mhd_token,
8643 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8644 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8645 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
8646 			/*
8647 			 * Note: We are returning here after having removed
8648 			 * some driver timeouts above. This is consistent with
8649 			 * the legacy implementation but perhaps the watch
8650 			 * terminate call should be made with the wait flag set.
8651 			 */
8652 			goto err_stillbusy;
8653 		}
8654 		mutex_enter(SD_MUTEX(un));
8655 		un->un_mhd_token = NULL;
8656 	}
8657 
8658 	if (un->un_swr_token != NULL) {
8659 		mutex_exit(SD_MUTEX(un));
8660 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
8661 		if (scsi_watch_request_terminate(un->un_swr_token,
8662 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
8663 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8664 			    "sd_dr_detach: Cannot cancel swr watch request\n");
8665 			/*
8666 			 * Note: We are returning here after having removed
8667 			 * some driver timeouts above. This is consistent with
8668 			 * the legacy implementation but perhaps the watch
8669 			 * terminate call should be made with the wait flag set.
8670 			 */
8671 			goto err_stillbusy;
8672 		}
8673 		mutex_enter(SD_MUTEX(un));
8674 		un->un_swr_token = NULL;
8675 	}
8676 
8677 	mutex_exit(SD_MUTEX(un));
8678 
8679 	/*
8680 	 * Clear any scsi_reset_notifies. We clear the reset notifies
8681 	 * if we have not registered one.
8682 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
8683 	 */
8684 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
8685 	    sd_mhd_reset_notify_cb, (caddr_t)un);
8686 
8687 	/*
8688 	 * protect the timeout pointers from getting nulled by
8689 	 * their callback functions during the cancellation process.
8690 	 * In such a scenario untimeout can be invoked with a null value.
8691 	 */
8692 	_NOTE(NO_COMPETING_THREADS_NOW);
8693 
8694 	mutex_enter(&un->un_pm_mutex);
8695 	if (un->un_pm_idle_timeid != NULL) {
8696 		timeout_id_t temp_id = un->un_pm_idle_timeid;
8697 		un->un_pm_idle_timeid = NULL;
8698 		mutex_exit(&un->un_pm_mutex);
8699 
8700 		/*
8701 		 * Timeout is active; cancel it.
8702 		 * Note that it'll never be active on a device
8703 		 * that does not support PM therefore we don't
8704 		 * have to check before calling pm_idle_component.
8705 		 */
8706 		(void) untimeout(temp_id);
8707 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8708 		mutex_enter(&un->un_pm_mutex);
8709 	}
8710 
8711 	/*
8712 	 * Check whether there is already a timeout scheduled for power
8713 	 * management. If yes then don't lower the power here, that's.
8714 	 * the timeout handler's job.
8715 	 */
8716 	if (un->un_pm_timeid != NULL) {
8717 		timeout_id_t temp_id = un->un_pm_timeid;
8718 		un->un_pm_timeid = NULL;
8719 		mutex_exit(&un->un_pm_mutex);
8720 		/*
8721 		 * Timeout is active; cancel it.
8722 		 * Note that it'll never be active on a device
8723 		 * that does not support PM therefore we don't
8724 		 * have to check before calling pm_idle_component.
8725 		 */
8726 		(void) untimeout(temp_id);
8727 		(void) pm_idle_component(SD_DEVINFO(un), 0);
8728 
8729 	} else {
8730 		mutex_exit(&un->un_pm_mutex);
8731 		if ((un->un_f_pm_is_enabled == TRUE) &&
8732 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_PM_STATE_STOPPED(un))
8733 		    != DDI_SUCCESS)) {
8734 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8735 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
8736 			/*
8737 			 * Fix for bug: 4297749, item # 13
8738 			 * The above test now includes a check to see if PM is
8739 			 * supported by this device before call
8740 			 * pm_lower_power().
8741 			 * Note, the following is not dead code. The call to
8742 			 * pm_lower_power above will generate a call back into
8743 			 * our sdpower routine which might result in a timeout
8744 			 * handler getting activated. Therefore the following
8745 			 * code is valid and necessary.
8746 			 */
8747 			mutex_enter(&un->un_pm_mutex);
8748 			if (un->un_pm_timeid != NULL) {
8749 				timeout_id_t temp_id = un->un_pm_timeid;
8750 				un->un_pm_timeid = NULL;
8751 				mutex_exit(&un->un_pm_mutex);
8752 				(void) untimeout(temp_id);
8753 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8754 			} else {
8755 				mutex_exit(&un->un_pm_mutex);
8756 			}
8757 		}
8758 	}
8759 
8760 	/*
8761 	 * Cleanup from the scsi_ifsetcap() calls (437868)
8762 	 * Relocated here from above to be after the call to
8763 	 * pm_lower_power, which was getting errors.
8764 	 */
8765 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
8766 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
8767 
8768 	/*
8769 	 * Currently, tagged queuing is supported per target based by HBA.
8770 	 * Setting this per lun instance actually sets the capability of this
8771 	 * target in HBA, which affects those luns already attached on the
8772 	 * same target. So during detach, we can only disable this capability
8773 	 * only when this is the only lun left on this target. By doing
8774 	 * this, we assume a target has the same tagged queuing capability
8775 	 * for every lun. The condition can be removed when HBA is changed to
8776 	 * support per lun based tagged queuing capability.
8777 	 */
8778 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
8779 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
8780 	}
8781 
8782 	if (un->un_f_is_fibre == FALSE) {
8783 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
8784 	}
8785 
8786 	/*
8787 	 * Remove any event callbacks, fibre only
8788 	 */
8789 	if (un->un_f_is_fibre == TRUE) {
8790 		if ((un->un_insert_event != NULL) &&
8791 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
8792 		    DDI_SUCCESS)) {
8793 			/*
8794 			 * Note: We are returning here after having done
8795 			 * substantial cleanup above. This is consistent
8796 			 * with the legacy implementation but this may not
8797 			 * be the right thing to do.
8798 			 */
8799 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8800 			    "sd_dr_detach: Cannot cancel insert event\n");
8801 			goto err_remove_event;
8802 		}
8803 		un->un_insert_event = NULL;
8804 
8805 		if ((un->un_remove_event != NULL) &&
8806 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
8807 		    DDI_SUCCESS)) {
8808 			/*
8809 			 * Note: We are returning here after having done
8810 			 * substantial cleanup above. This is consistent
8811 			 * with the legacy implementation but this may not
8812 			 * be the right thing to do.
8813 			 */
8814 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8815 			    "sd_dr_detach: Cannot cancel remove event\n");
8816 			goto err_remove_event;
8817 		}
8818 		un->un_remove_event = NULL;
8819 	}
8820 
8821 	/* Do not free the softstate if the callback routine is active */
8822 	sd_sync_with_callback(un);
8823 
8824 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
8825 	cmlb_free_handle(&un->un_cmlbhandle);
8826 
8827 	/*
8828 	 * Clean up the soft state struct.
8829 	 * Cleanup is done in reverse order of allocs/inits.
8830 	 * At this point there should be no competing threads anymore.
8831 	 */
8832 
8833 	scsi_fm_fini(devp);
8834 
8835 	/*
8836 	 * Deallocate memory for SCSI FMA.
8837 	 */
8838 	kmem_free(un->un_fm_private, sizeof (struct sd_fm_internal));
8839 
8840 	/*
8841 	 * Unregister and free device id if it was not registered
8842 	 * by the transport.
8843 	 */
8844 	if (un->un_f_devid_transport_defined == FALSE)
8845 		ddi_devid_unregister(devi);
8846 
8847 	/*
8848 	 * free the devid structure if allocated before (by ddi_devid_init()
8849 	 * or ddi_devid_get()).
8850 	 */
8851 	if (un->un_devid) {
8852 		ddi_devid_free(un->un_devid);
8853 		un->un_devid = NULL;
8854 	}
8855 
8856 	/*
8857 	 * Destroy wmap cache if it exists.
8858 	 */
8859 	if (un->un_wm_cache != NULL) {
8860 		kmem_cache_destroy(un->un_wm_cache);
8861 		un->un_wm_cache = NULL;
8862 	}
8863 
8864 	/*
8865 	 * kstat cleanup is done in detach for all device types (4363169).
8866 	 * We do not want to fail detach if the device kstats are not deleted
8867 	 * since there is a confusion about the devo_refcnt for the device.
8868 	 * We just delete the kstats and let detach complete successfully.
8869 	 */
8870 	if (un->un_stats != NULL) {
8871 		kstat_delete(un->un_stats);
8872 		un->un_stats = NULL;
8873 	}
8874 	if (un->un_unmapstats != NULL) {
8875 		kstat_delete(un->un_unmapstats_ks);
8876 		un->un_unmapstats_ks = NULL;
8877 		un->un_unmapstats = NULL;
8878 	}
8879 	if (un->un_errstats != NULL) {
8880 		kstat_delete(un->un_errstats);
8881 		un->un_errstats = NULL;
8882 	}
8883 
8884 	/* Remove partition stats */
8885 	if (un->un_f_pkstats_enabled) {
8886 		for (i = 0; i < NSDMAP; i++) {
8887 			if (un->un_pstats[i] != NULL) {
8888 				kstat_delete(un->un_pstats[i]);
8889 				un->un_pstats[i] = NULL;
8890 			}
8891 		}
8892 	}
8893 
8894 	/* Remove xbuf registration */
8895 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
8896 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
8897 
8898 	/* Remove driver properties */
8899 	ddi_prop_remove_all(devi);
8900 
8901 	mutex_destroy(&un->un_pm_mutex);
8902 	cv_destroy(&un->un_pm_busy_cv);
8903 
8904 	cv_destroy(&un->un_wcc_cv);
8905 
8906 	/* Removable media condvar. */
8907 	cv_destroy(&un->un_state_cv);
8908 
8909 	/* Suspend/resume condvar. */
8910 	cv_destroy(&un->un_suspend_cv);
8911 	cv_destroy(&un->un_disk_busy_cv);
8912 
8913 	sd_free_rqs(un);
8914 
8915 	/* Free up soft state */
8916 	devp->sd_private = NULL;
8917 
8918 	bzero(un, sizeof (struct sd_lun));
8919 
8920 	ddi_soft_state_free(sd_state, instance);
8921 
8922 	/* This frees up the INQUIRY data associated with the device. */
8923 	scsi_unprobe(devp);
8924 
8925 	/*
8926 	 * After successfully detaching an instance, we update the information
8927 	 * of how many luns have been attached in the relative target and
8928 	 * controller for parallel SCSI. This information is used when sd tries
8929 	 * to set the tagged queuing capability in HBA.
8930 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
8931 	 * check if the device is parallel SCSI. However, we don't need to
8932 	 * check here because we've already checked during attach. No device
8933 	 * that is not parallel SCSI is in the chain.
8934 	 */
8935 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8936 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
8937 	}
8938 
8939 	return (DDI_SUCCESS);
8940 
8941 err_notclosed:
8942 	mutex_exit(SD_MUTEX(un));
8943 
8944 err_stillbusy:
8945 	_NOTE(NO_COMPETING_THREADS_NOW);
8946 
8947 err_remove_event:
8948 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
8949 	return (DDI_FAILURE);
8950 }
8951 
8952 
8953 /*
8954  *    Function: sd_create_errstats
8955  *
8956  * Description: This routine instantiates the device error stats.
8957  *
8958  *		Note: During attach the stats are instantiated first so they are
8959  *		available for attach-time routines that utilize the driver
8960  *		iopath to send commands to the device. The stats are initialized
8961  *		separately so data obtained during some attach-time routines is
8962  *		available. (4362483)
8963  *
8964  *   Arguments: un - driver soft state (unit) structure
8965  *		instance - driver instance
8966  *
8967  *     Context: Kernel thread context
8968  */
8969 
8970 static void
8971 sd_create_errstats(struct sd_lun *un, int instance)
8972 {
8973 	struct	sd_errstats	*stp;
8974 	char	kstatmodule_err[KSTAT_STRLEN];
8975 	char	kstatname[KSTAT_STRLEN];
8976 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
8977 
8978 	ASSERT(un != NULL);
8979 
8980 	if (un->un_errstats != NULL) {
8981 		return;
8982 	}
8983 
8984 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
8985 	    "%serr", sd_label);
8986 	(void) snprintf(kstatname, sizeof (kstatname),
8987 	    "%s%d,err", sd_label, instance);
8988 
8989 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
8990 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
8991 
8992 	if (un->un_errstats == NULL) {
8993 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8994 		    "sd_create_errstats: Failed kstat_create\n");
8995 		return;
8996 	}
8997 
8998 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8999 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
9000 	    KSTAT_DATA_UINT32);
9001 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
9002 	    KSTAT_DATA_UINT32);
9003 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
9004 	    KSTAT_DATA_UINT32);
9005 	kstat_named_init(&stp->sd_vid,		"Vendor",
9006 	    KSTAT_DATA_CHAR);
9007 	kstat_named_init(&stp->sd_pid,		"Product",
9008 	    KSTAT_DATA_CHAR);
9009 	kstat_named_init(&stp->sd_revision,	"Revision",
9010 	    KSTAT_DATA_CHAR);
9011 	kstat_named_init(&stp->sd_serial,	"Serial No",
9012 	    KSTAT_DATA_CHAR);
9013 	kstat_named_init(&stp->sd_capacity,	"Size",
9014 	    KSTAT_DATA_ULONGLONG);
9015 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
9016 	    KSTAT_DATA_UINT32);
9017 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
9018 	    KSTAT_DATA_UINT32);
9019 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
9020 	    KSTAT_DATA_UINT32);
9021 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
9022 	    KSTAT_DATA_UINT32);
9023 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
9024 	    KSTAT_DATA_UINT32);
9025 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
9026 	    KSTAT_DATA_UINT32);
9027 
9028 	un->un_errstats->ks_private = un;
9029 	un->un_errstats->ks_update  = nulldev;
9030 
9031 	kstat_install(un->un_errstats);
9032 }
9033 
9034 
9035 /*
9036  *    Function: sd_set_errstats
9037  *
9038  * Description: This routine sets the value of the vendor id, product id,
9039  *		revision, serial number, and capacity device error stats.
9040  *
9041  *		Note: During attach the stats are instantiated first so they are
9042  *		available for attach-time routines that utilize the driver
9043  *		iopath to send commands to the device. The stats are initialized
9044  *		separately so data obtained during some attach-time routines is
9045  *		available. (4362483)
9046  *
9047  *   Arguments: un - driver soft state (unit) structure
9048  *
9049  *     Context: Kernel thread context
9050  */
9051 
9052 static void
9053 sd_set_errstats(struct sd_lun *un)
9054 {
9055 	struct	sd_errstats	*stp;
9056 	char			*sn;
9057 
9058 	ASSERT(un != NULL);
9059 	ASSERT(un->un_errstats != NULL);
9060 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
9061 	ASSERT(stp != NULL);
9062 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
9063 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
9064 	(void) strncpy(stp->sd_revision.value.c,
9065 	    un->un_sd->sd_inq->inq_revision, 4);
9066 
9067 	/*
9068 	 * All the errstats are persistent across detach/attach,
9069 	 * so reset all the errstats here in case of the hot
9070 	 * replacement of disk drives, except for not changed
9071 	 * Sun qualified drives.
9072 	 */
9073 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
9074 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9075 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
9076 		stp->sd_softerrs.value.ui32 = 0;
9077 		stp->sd_harderrs.value.ui32 = 0;
9078 		stp->sd_transerrs.value.ui32 = 0;
9079 		stp->sd_rq_media_err.value.ui32 = 0;
9080 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
9081 		stp->sd_rq_nodev_err.value.ui32 = 0;
9082 		stp->sd_rq_recov_err.value.ui32 = 0;
9083 		stp->sd_rq_illrq_err.value.ui32 = 0;
9084 		stp->sd_rq_pfa_err.value.ui32 = 0;
9085 	}
9086 
9087 	/*
9088 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
9089 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
9090 	 * (4376302))
9091 	 */
9092 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
9093 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
9094 		    sizeof (SD_INQUIRY(un)->inq_serial));
9095 	} else {
9096 		/*
9097 		 * Set the "Serial No" kstat for non-Sun qualified drives
9098 		 */
9099 		if (ddi_prop_lookup_string(DDI_DEV_T_ANY, SD_DEVINFO(un),
9100 		    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
9101 		    INQUIRY_SERIAL_NO, &sn) == DDI_SUCCESS) {
9102 			(void) strlcpy(stp->sd_serial.value.c, sn,
9103 			    sizeof (stp->sd_serial.value.c));
9104 			ddi_prop_free(sn);
9105 		}
9106 	}
9107 
9108 	if (un->un_f_blockcount_is_valid != TRUE) {
9109 		/*
9110 		 * Set capacity error stat to 0 for no media. This ensures
9111 		 * a valid capacity is displayed in response to 'iostat -E'
9112 		 * when no media is present in the device.
9113 		 */
9114 		stp->sd_capacity.value.ui64 = 0;
9115 	} else {
9116 		/*
9117 		 * Multiply un_blockcount by un->un_sys_blocksize to get
9118 		 * capacity.
9119 		 *
9120 		 * Note: for non-512 blocksize devices "un_blockcount" has been
9121 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
9122 		 * (un_tgt_blocksize / un->un_sys_blocksize).
9123 		 */
9124 		stp->sd_capacity.value.ui64 = (uint64_t)
9125 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
9126 	}
9127 }
9128 
9129 
9130 /*
9131  *    Function: sd_set_pstats
9132  *
9133  * Description: This routine instantiates and initializes the partition
9134  *              stats for each partition with more than zero blocks.
9135  *		(4363169)
9136  *
9137  *   Arguments: un - driver soft state (unit) structure
9138  *
9139  *     Context: Kernel thread context
9140  */
9141 
9142 static void
9143 sd_set_pstats(struct sd_lun *un)
9144 {
9145 	char	kstatname[KSTAT_STRLEN];
9146 	int	instance;
9147 	int	i;
9148 	diskaddr_t	nblks = 0;
9149 	char	*partname = NULL;
9150 
9151 	ASSERT(un != NULL);
9152 
9153 	instance = ddi_get_instance(SD_DEVINFO(un));
9154 
9155 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
9156 	for (i = 0; i < NSDMAP; i++) {
9157 
9158 		if (cmlb_partinfo(un->un_cmlbhandle, i,
9159 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
9160 			continue;
9161 		mutex_enter(SD_MUTEX(un));
9162 
9163 		if ((un->un_pstats[i] == NULL) &&
9164 		    (nblks != 0)) {
9165 
9166 			(void) snprintf(kstatname, sizeof (kstatname),
9167 			    "%s%d,%s", sd_label, instance,
9168 			    partname);
9169 
9170 			un->un_pstats[i] = kstat_create(sd_label,
9171 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
9172 			    1, KSTAT_FLAG_PERSISTENT);
9173 			if (un->un_pstats[i] != NULL) {
9174 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
9175 				kstat_install(un->un_pstats[i]);
9176 			}
9177 		}
9178 		mutex_exit(SD_MUTEX(un));
9179 	}
9180 }
9181 
9182 
9183 #if (defined(__fibre))
9184 /*
9185  *    Function: sd_init_event_callbacks
9186  *
9187  * Description: This routine initializes the insertion and removal event
9188  *		callbacks. (fibre only)
9189  *
9190  *   Arguments: un - driver soft state (unit) structure
9191  *
9192  *     Context: Kernel thread context
9193  */
9194 
9195 static void
9196 sd_init_event_callbacks(struct sd_lun *un)
9197 {
9198 	ASSERT(un != NULL);
9199 
9200 	if ((un->un_insert_event == NULL) &&
9201 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
9202 	    &un->un_insert_event) == DDI_SUCCESS)) {
9203 		/*
9204 		 * Add the callback for an insertion event
9205 		 */
9206 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9207 		    un->un_insert_event, sd_event_callback, (void *)un,
9208 		    &(un->un_insert_cb_id));
9209 	}
9210 
9211 	if ((un->un_remove_event == NULL) &&
9212 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
9213 	    &un->un_remove_event) == DDI_SUCCESS)) {
9214 		/*
9215 		 * Add the callback for a removal event
9216 		 */
9217 		(void) ddi_add_event_handler(SD_DEVINFO(un),
9218 		    un->un_remove_event, sd_event_callback, (void *)un,
9219 		    &(un->un_remove_cb_id));
9220 	}
9221 }
9222 
9223 
9224 /*
9225  *    Function: sd_event_callback
9226  *
9227  * Description: This routine handles insert/remove events (photon). The
9228  *		state is changed to OFFLINE which can be used to supress
9229  *		error msgs. (fibre only)
9230  *
9231  *   Arguments: un - driver soft state (unit) structure
9232  *
9233  *     Context: Callout thread context
9234  */
9235 /* ARGSUSED */
9236 static void
9237 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
9238     void *bus_impldata)
9239 {
9240 	struct sd_lun *un = (struct sd_lun *)arg;
9241 
9242 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
9243 	if (event == un->un_insert_event) {
9244 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
9245 		mutex_enter(SD_MUTEX(un));
9246 		if (un->un_state == SD_STATE_OFFLINE) {
9247 			if (un->un_last_state != SD_STATE_SUSPENDED) {
9248 				un->un_state = un->un_last_state;
9249 			} else {
9250 				/*
9251 				 * We have gone through SUSPEND/RESUME while
9252 				 * we were offline. Restore the last state
9253 				 */
9254 				un->un_state = un->un_save_state;
9255 			}
9256 		}
9257 		mutex_exit(SD_MUTEX(un));
9258 
9259 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
9260 	} else if (event == un->un_remove_event) {
9261 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
9262 		mutex_enter(SD_MUTEX(un));
9263 		/*
9264 		 * We need to handle an event callback that occurs during
9265 		 * the suspend operation, since we don't prevent it.
9266 		 */
9267 		if (un->un_state != SD_STATE_OFFLINE) {
9268 			if (un->un_state != SD_STATE_SUSPENDED) {
9269 				New_state(un, SD_STATE_OFFLINE);
9270 			} else {
9271 				un->un_last_state = SD_STATE_OFFLINE;
9272 			}
9273 		}
9274 		mutex_exit(SD_MUTEX(un));
9275 	} else {
9276 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
9277 		    "!Unknown event\n");
9278 	}
9279 
9280 }
9281 #endif
9282 
9283 /*
9284  * Values related to caching mode page depending on whether the unit is ATAPI.
9285  */
9286 #define	SDC_CDB_GROUP(un) ((un->un_f_cfg_is_atapi == TRUE) ? \
9287 	CDB_GROUP1 : CDB_GROUP0)
9288 #define	SDC_HDRLEN(un) ((un->un_f_cfg_is_atapi == TRUE) ? \
9289 	MODE_HEADER_LENGTH_GRP2 : MODE_HEADER_LENGTH)
9290 /*
9291  * Use mode_cache_scsi3 to ensure we get all of the mode sense data, otherwise
9292  * the mode select will fail (mode_cache_scsi3 is a superset of mode_caching).
9293  */
9294 #define	SDC_BUFLEN(un) (SDC_HDRLEN(un) + MODE_BLK_DESC_LENGTH + \
9295 	sizeof (struct mode_cache_scsi3))
9296 
9297 static int
9298 sd_get_caching_mode_page(sd_ssc_t *ssc, uchar_t page_control, uchar_t **header,
9299     int *bdlen)
9300 {
9301 	struct sd_lun	*un = ssc->ssc_un;
9302 	struct mode_caching *mode_caching_page;
9303 	size_t		buflen = SDC_BUFLEN(un);
9304 	int		hdrlen = SDC_HDRLEN(un);
9305 	int		rval;
9306 
9307 	/*
9308 	 * Do a test unit ready, otherwise a mode sense may not work if this
9309 	 * is the first command sent to the device after boot.
9310 	 */
9311 	if (sd_send_scsi_TEST_UNIT_READY(ssc, 0) != 0)
9312 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9313 
9314 	/*
9315 	 * Allocate memory for the retrieved mode page and its headers.  Set
9316 	 * a pointer to the page itself.
9317 	 */
9318 	*header = kmem_zalloc(buflen, KM_SLEEP);
9319 
9320 	/* Get the information from the device */
9321 	rval = sd_send_scsi_MODE_SENSE(ssc, SDC_CDB_GROUP(un), *header, buflen,
9322 	    page_control | MODEPAGE_CACHING, SD_PATH_DIRECT);
9323 	if (rval != 0) {
9324 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un, "%s: Mode Sense Failed\n",
9325 		    __func__);
9326 		goto mode_sense_failed;
9327 	}
9328 
9329 	/*
9330 	 * Determine size of Block Descriptors in order to locate
9331 	 * the mode page data. ATAPI devices return 0, SCSI devices
9332 	 * should return MODE_BLK_DESC_LENGTH.
9333 	 */
9334 	if (un->un_f_cfg_is_atapi == TRUE) {
9335 		struct mode_header_grp2 *mhp =
9336 		    (struct mode_header_grp2 *)(*header);
9337 		*bdlen = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
9338 	} else {
9339 		*bdlen = ((struct mode_header *)(*header))->bdesc_length;
9340 	}
9341 
9342 	if (*bdlen > MODE_BLK_DESC_LENGTH) {
9343 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, 0,
9344 		    "%s: Mode Sense returned invalid block descriptor length\n",
9345 		    __func__);
9346 		rval = EIO;
9347 		goto mode_sense_failed;
9348 	}
9349 
9350 	mode_caching_page = (struct mode_caching *)(*header + hdrlen + *bdlen);
9351 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
9352 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, SD_LOG_COMMON,
9353 		    "%s: Mode Sense caching page code mismatch %d\n",
9354 		    __func__, mode_caching_page->mode_page.code);
9355 		rval = EIO;
9356 	}
9357 
9358 mode_sense_failed:
9359 	if (rval != 0) {
9360 		kmem_free(*header, buflen);
9361 		*header = NULL;
9362 		*bdlen = 0;
9363 	}
9364 	return (rval);
9365 }
9366 
9367 /*
9368  *    Function: sd_cache_control()
9369  *
9370  * Description: This routine is the driver entry point for setting
9371  *		read and write caching by modifying the WCE (write cache
9372  *		enable) and RCD (read cache disable) bits of mode
9373  *		page 8 (MODEPAGE_CACHING).
9374  *
9375  *   Arguments: ssc		- ssc contains pointer to driver soft state
9376  *				  (unit) structure for this target.
9377  *		rcd_flag	- flag for controlling the read cache
9378  *		wce_flag	- flag for controlling the write cache
9379  *
9380  * Return Code: EIO
9381  *		code returned by sd_send_scsi_MODE_SENSE and
9382  *		sd_send_scsi_MODE_SELECT
9383  *
9384  *     Context: Kernel Thread
9385  */
9386 
9387 static int
9388 sd_cache_control(sd_ssc_t *ssc, int rcd_flag, int wce_flag)
9389 {
9390 	struct sd_lun	*un = ssc->ssc_un;
9391 	struct mode_caching *mode_caching_page;
9392 	uchar_t		*header;
9393 	size_t		buflen = SDC_BUFLEN(un);
9394 	int		hdrlen = SDC_HDRLEN(un);
9395 	int		bdlen;
9396 	int		rval;
9397 
9398 	rval = sd_get_caching_mode_page(ssc, MODEPAGE_CURRENT, &header, &bdlen);
9399 	switch (rval) {
9400 	case 0:
9401 		/* Check the relevant bits on successful mode sense */
9402 		mode_caching_page = (struct mode_caching *)(header + hdrlen +
9403 		    bdlen);
9404 		if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
9405 		    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
9406 		    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
9407 		    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
9408 			size_t sbuflen;
9409 			uchar_t save_pg;
9410 
9411 			/*
9412 			 * Construct select buffer length based on the
9413 			 * length of the sense data returned.
9414 			 */
9415 			sbuflen = hdrlen + bdlen + sizeof (struct mode_page) +
9416 			    (int)mode_caching_page->mode_page.length;
9417 
9418 			/* Set the caching bits as requested */
9419 			if (rcd_flag == SD_CACHE_ENABLE)
9420 				mode_caching_page->rcd = 0;
9421 			else if (rcd_flag == SD_CACHE_DISABLE)
9422 				mode_caching_page->rcd = 1;
9423 
9424 			if (wce_flag == SD_CACHE_ENABLE)
9425 				mode_caching_page->wce = 1;
9426 			else if (wce_flag == SD_CACHE_DISABLE)
9427 				mode_caching_page->wce = 0;
9428 
9429 			/*
9430 			 * Save the page if the mode sense says the
9431 			 * drive supports it.
9432 			 */
9433 			save_pg = mode_caching_page->mode_page.ps ?
9434 			    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
9435 
9436 			/* Clear reserved bits before mode select */
9437 			mode_caching_page->mode_page.ps = 0;
9438 
9439 			/*
9440 			 * Clear out mode header for mode select.
9441 			 * The rest of the retrieved page will be reused.
9442 			 */
9443 			bzero(header, hdrlen);
9444 
9445 			if (un->un_f_cfg_is_atapi == TRUE) {
9446 				struct mode_header_grp2 *mhp =
9447 				    (struct mode_header_grp2 *)header;
9448 				mhp->bdesc_length_hi = bdlen >> 8;
9449 				mhp->bdesc_length_lo = (uchar_t)bdlen & 0xff;
9450 			} else {
9451 				((struct mode_header *)header)->bdesc_length =
9452 				    bdlen;
9453 			}
9454 
9455 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9456 
9457 			/* Issue mode select to change the cache settings */
9458 			rval = sd_send_scsi_MODE_SELECT(ssc, SDC_CDB_GROUP(un),
9459 			    header, sbuflen, save_pg, SD_PATH_DIRECT);
9460 		}
9461 		kmem_free(header, buflen);
9462 		break;
9463 	case EIO:
9464 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9465 		break;
9466 	default:
9467 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9468 		break;
9469 	}
9470 
9471 	return (rval);
9472 }
9473 
9474 
9475 /*
9476  *    Function: sd_get_write_cache_enabled()
9477  *
9478  * Description: This routine is the driver entry point for determining if write
9479  *		caching is enabled.  It examines the WCE (write cache enable)
9480  *		bits of mode page 8 (MODEPAGE_CACHING) with Page Control field
9481  *		bits set to MODEPAGE_CURRENT.
9482  *
9483  *   Arguments: ssc		- ssc contains pointer to driver soft state
9484  *				  (unit) structure for this target.
9485  *		is_enabled	- pointer to int where write cache enabled state
9486  *				  is returned (non-zero -> write cache enabled)
9487  *
9488  * Return Code: EIO
9489  *		code returned by sd_send_scsi_MODE_SENSE
9490  *
9491  *     Context: Kernel Thread
9492  *
9493  * NOTE: If ioctl is added to disable write cache, this sequence should
9494  * be followed so that no locking is required for accesses to
9495  * un->un_f_write_cache_enabled:
9496  *	do mode select to clear wce
9497  *	do synchronize cache to flush cache
9498  *	set un->un_f_write_cache_enabled = FALSE
9499  *
9500  * Conversely, an ioctl to enable the write cache should be done
9501  * in this order:
9502  *	set un->un_f_write_cache_enabled = TRUE
9503  *	do mode select to set wce
9504  */
9505 
9506 static int
9507 sd_get_write_cache_enabled(sd_ssc_t *ssc, int *is_enabled)
9508 {
9509 	struct sd_lun	*un = ssc->ssc_un;
9510 	struct mode_caching *mode_caching_page;
9511 	uchar_t		*header;
9512 	size_t		buflen = SDC_BUFLEN(un);
9513 	int		hdrlen = SDC_HDRLEN(un);
9514 	int		bdlen;
9515 	int		rval;
9516 
9517 	/* In case of error, flag as enabled */
9518 	*is_enabled = TRUE;
9519 
9520 	rval = sd_get_caching_mode_page(ssc, MODEPAGE_CURRENT, &header, &bdlen);
9521 	switch (rval) {
9522 	case 0:
9523 		mode_caching_page = (struct mode_caching *)(header + hdrlen +
9524 		    bdlen);
9525 		*is_enabled = mode_caching_page->wce;
9526 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
9527 		kmem_free(header, buflen);
9528 		break;
9529 	case EIO: {
9530 		/*
9531 		 * Some disks do not support Mode Sense(6), we
9532 		 * should ignore this kind of error (sense key is
9533 		 * 0x5 - illegal request).
9534 		 */
9535 		uint8_t *sensep;
9536 		int senlen;
9537 
9538 		sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
9539 		senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
9540 		    ssc->ssc_uscsi_cmd->uscsi_rqresid);
9541 
9542 		if (senlen > 0 &&
9543 		    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
9544 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
9545 		} else {
9546 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9547 		}
9548 		break;
9549 	}
9550 	default:
9551 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9552 		break;
9553 	}
9554 
9555 	return (rval);
9556 }
9557 
9558 /*
9559  *    Function: sd_get_write_cache_changeable()
9560  *
9561  * Description: This routine is the driver entry point for determining if write
9562  *		caching is changeable.  It examines the WCE (write cache enable)
9563  *		bits of mode page 8 (MODEPAGE_CACHING) with Page Control field
9564  *		bits set to MODEPAGE_CHANGEABLE.
9565  *
9566  *   Arguments: ssc		- ssc contains pointer to driver soft state
9567  *				  (unit) structure for this target.
9568  *		is_changeable	- pointer to int where write cache changeable
9569  *				  state is returned (non-zero -> write cache
9570  *				  changeable)
9571  *
9572  *     Context: Kernel Thread
9573  */
9574 
9575 static void
9576 sd_get_write_cache_changeable(sd_ssc_t *ssc, int *is_changeable)
9577 {
9578 	struct sd_lun	*un = ssc->ssc_un;
9579 	struct mode_caching *mode_caching_page;
9580 	uchar_t		*header;
9581 	size_t		buflen = SDC_BUFLEN(un);
9582 	int		hdrlen = SDC_HDRLEN(un);
9583 	int		bdlen;
9584 	int		rval;
9585 
9586 	/* In case of error, flag as enabled */
9587 	*is_changeable = TRUE;
9588 
9589 	rval = sd_get_caching_mode_page(ssc, MODEPAGE_CHANGEABLE, &header,
9590 	    &bdlen);
9591 	switch (rval) {
9592 	case 0:
9593 		mode_caching_page = (struct mode_caching *)(header + hdrlen +
9594 		    bdlen);
9595 		*is_changeable = mode_caching_page->wce;
9596 		kmem_free(header, buflen);
9597 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
9598 		break;
9599 	case EIO:
9600 		sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
9601 		break;
9602 	default:
9603 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9604 		break;
9605 	}
9606 }
9607 
9608 /*
9609  *    Function: sd_get_nv_sup()
9610  *
9611  * Description: This routine is the driver entry point for
9612  * determining whether non-volatile cache is supported. This
9613  * determination process works as follows:
9614  *
9615  * 1. sd first queries sd.conf on whether
9616  * suppress_cache_flush bit is set for this device.
9617  *
9618  * 2. if not there, then queries the internal disk table.
9619  *
9620  * 3. if either sd.conf or internal disk table specifies
9621  * cache flush be suppressed, we don't bother checking
9622  * NV_SUP bit.
9623  *
9624  * If SUPPRESS_CACHE_FLUSH bit is not set to 1, sd queries
9625  * the optional INQUIRY VPD page 0x86. If the device
9626  * supports VPD page 0x86, sd examines the NV_SUP
9627  * (non-volatile cache support) bit in the INQUIRY VPD page
9628  * 0x86:
9629  *   o If NV_SUP bit is set, sd assumes the device has a
9630  *   non-volatile cache and set the
9631  *   un_f_sync_nv_supported to TRUE.
9632  *   o Otherwise cache is not non-volatile,
9633  *   un_f_sync_nv_supported is set to FALSE.
9634  *
9635  * Arguments: un - driver soft state (unit) structure
9636  *
9637  * Return Code:
9638  *
9639  *     Context: Kernel Thread
9640  */
9641 
9642 static void
9643 sd_get_nv_sup(sd_ssc_t *ssc)
9644 {
9645 	int		rval		= 0;
9646 	uchar_t		*inq86		= NULL;
9647 	size_t		inq86_len	= MAX_INQUIRY_SIZE;
9648 	size_t		inq86_resid	= 0;
9649 	struct		dk_callback *dkc;
9650 	struct sd_lun	*un;
9651 
9652 	ASSERT(ssc != NULL);
9653 	un = ssc->ssc_un;
9654 	ASSERT(un != NULL);
9655 
9656 	mutex_enter(SD_MUTEX(un));
9657 
9658 	/*
9659 	 * Be conservative on the device's support of
9660 	 * SYNC_NV bit: un_f_sync_nv_supported is
9661 	 * initialized to be false.
9662 	 */
9663 	un->un_f_sync_nv_supported = FALSE;
9664 
9665 	/*
9666 	 * If either sd.conf or internal disk table
9667 	 * specifies cache flush be suppressed, then
9668 	 * we don't bother checking NV_SUP bit.
9669 	 */
9670 	if (un->un_f_suppress_cache_flush == TRUE) {
9671 		mutex_exit(SD_MUTEX(un));
9672 		return;
9673 	}
9674 
9675 	if (sd_check_vpd_page_support(ssc) == 0 &&
9676 	    un->un_vpd_page_mask & SD_VPD_EXTENDED_DATA_PG) {
9677 		mutex_exit(SD_MUTEX(un));
9678 		/* collect page 86 data if available */
9679 		inq86 = kmem_zalloc(inq86_len, KM_SLEEP);
9680 
9681 		rval = sd_send_scsi_INQUIRY(ssc, inq86, inq86_len,
9682 		    0x01, 0x86, &inq86_resid);
9683 
9684 		if (rval == 0 && (inq86_len - inq86_resid > 6)) {
9685 			SD_TRACE(SD_LOG_COMMON, un,
9686 			    "sd_get_nv_sup: \
9687 			    successfully get VPD page: %x \
9688 			    PAGE LENGTH: %x BYTE 6: %x\n",
9689 			    inq86[1], inq86[3], inq86[6]);
9690 
9691 			mutex_enter(SD_MUTEX(un));
9692 			/*
9693 			 * check the value of NV_SUP bit: only if the device
9694 			 * reports NV_SUP bit to be 1, the
9695 			 * un_f_sync_nv_supported bit will be set to true.
9696 			 */
9697 			if (inq86[6] & SD_VPD_NV_SUP) {
9698 				un->un_f_sync_nv_supported = TRUE;
9699 			}
9700 			mutex_exit(SD_MUTEX(un));
9701 		} else if (rval != 0) {
9702 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9703 		}
9704 
9705 		kmem_free(inq86, inq86_len);
9706 	} else {
9707 		mutex_exit(SD_MUTEX(un));
9708 	}
9709 
9710 	/*
9711 	 * Send a SYNC CACHE command to check whether
9712 	 * SYNC_NV bit is supported. This command should have
9713 	 * un_f_sync_nv_supported set to correct value.
9714 	 */
9715 	mutex_enter(SD_MUTEX(un));
9716 	if (un->un_f_sync_nv_supported) {
9717 		mutex_exit(SD_MUTEX(un));
9718 		dkc = kmem_zalloc(sizeof (struct dk_callback), KM_SLEEP);
9719 		dkc->dkc_flag = FLUSH_VOLATILE;
9720 		(void) sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
9721 
9722 		/*
9723 		 * Send a TEST UNIT READY command to the device. This should
9724 		 * clear any outstanding UNIT ATTENTION that may be present.
9725 		 */
9726 		rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_DONT_RETRY_TUR);
9727 		if (rval != 0)
9728 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
9729 
9730 		kmem_free(dkc, sizeof (struct dk_callback));
9731 	} else {
9732 		mutex_exit(SD_MUTEX(un));
9733 	}
9734 
9735 	SD_TRACE(SD_LOG_COMMON, un, "sd_get_nv_sup: \
9736 	    un_f_suppress_cache_flush is set to %d\n",
9737 	    un->un_f_suppress_cache_flush);
9738 }
9739 
9740 /*
9741  *    Function: sd_make_device
9742  *
9743  * Description: Utility routine to return the Solaris device number from
9744  *		the data in the device's dev_info structure.
9745  *
9746  * Return Code: The Solaris device number
9747  *
9748  *     Context: Any
9749  */
9750 
9751 static dev_t
9752 sd_make_device(dev_info_t *devi)
9753 {
9754 	return (makedevice(ddi_driver_major(devi),
9755 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
9756 }
9757 
9758 
9759 /*
9760  *    Function: sd_pm_entry
9761  *
9762  * Description: Called at the start of a new command to manage power
9763  *		and busy status of a device. This includes determining whether
9764  *		the current power state of the device is sufficient for
9765  *		performing the command or whether it must be changed.
9766  *		The PM framework is notified appropriately.
9767  *		Only with a return status of DDI_SUCCESS will the
9768  *		component be busy to the framework.
9769  *
9770  *		All callers of sd_pm_entry must check the return status
9771  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
9772  *		of DDI_FAILURE indicates the device failed to power up.
9773  *		In this case un_pm_count has been adjusted so the result
9774  *		on exit is still powered down, ie. count is less than 0.
9775  *		Calling sd_pm_exit with this count value hits an ASSERT.
9776  *
9777  * Return Code: DDI_SUCCESS or DDI_FAILURE
9778  *
9779  *     Context: Kernel thread context.
9780  */
9781 
9782 static int
9783 sd_pm_entry(struct sd_lun *un)
9784 {
9785 	int return_status = DDI_SUCCESS;
9786 
9787 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9788 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9789 
9790 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
9791 
9792 	if (un->un_f_pm_is_enabled == FALSE) {
9793 		SD_TRACE(SD_LOG_IO_PM, un,
9794 		    "sd_pm_entry: exiting, PM not enabled\n");
9795 		return (return_status);
9796 	}
9797 
9798 	/*
9799 	 * Just increment a counter if PM is enabled. On the transition from
9800 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
9801 	 * the count with each IO and mark the device as idle when the count
9802 	 * hits 0.
9803 	 *
9804 	 * If the count is less than 0 the device is powered down. If a powered
9805 	 * down device is successfully powered up then the count must be
9806 	 * incremented to reflect the power up. Note that it'll get incremented
9807 	 * a second time to become busy.
9808 	 *
9809 	 * Because the following has the potential to change the device state
9810 	 * and must release the un_pm_mutex to do so, only one thread can be
9811 	 * allowed through at a time.
9812 	 */
9813 
9814 	mutex_enter(&un->un_pm_mutex);
9815 	while (un->un_pm_busy == TRUE) {
9816 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
9817 	}
9818 	un->un_pm_busy = TRUE;
9819 
9820 	if (un->un_pm_count < 1) {
9821 
9822 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
9823 
9824 		/*
9825 		 * Indicate we are now busy so the framework won't attempt to
9826 		 * power down the device. This call will only fail if either
9827 		 * we passed a bad component number or the device has no
9828 		 * components. Neither of these should ever happen.
9829 		 */
9830 		mutex_exit(&un->un_pm_mutex);
9831 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
9832 		ASSERT(return_status == DDI_SUCCESS);
9833 
9834 		mutex_enter(&un->un_pm_mutex);
9835 
9836 		if (un->un_pm_count < 0) {
9837 			mutex_exit(&un->un_pm_mutex);
9838 
9839 			SD_TRACE(SD_LOG_IO_PM, un,
9840 			    "sd_pm_entry: power up component\n");
9841 
9842 			/*
9843 			 * pm_raise_power will cause sdpower to be called
9844 			 * which brings the device power level to the
9845 			 * desired state, If successful, un_pm_count and
9846 			 * un_power_level will be updated appropriately.
9847 			 */
9848 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
9849 			    SD_PM_STATE_ACTIVE(un));
9850 
9851 			mutex_enter(&un->un_pm_mutex);
9852 
9853 			if (return_status != DDI_SUCCESS) {
9854 				/*
9855 				 * Power up failed.
9856 				 * Idle the device and adjust the count
9857 				 * so the result on exit is that we're
9858 				 * still powered down, ie. count is less than 0.
9859 				 */
9860 				SD_TRACE(SD_LOG_IO_PM, un,
9861 				    "sd_pm_entry: power up failed,"
9862 				    " idle the component\n");
9863 
9864 				(void) pm_idle_component(SD_DEVINFO(un), 0);
9865 				un->un_pm_count--;
9866 			} else {
9867 				/*
9868 				 * Device is powered up, verify the
9869 				 * count is non-negative.
9870 				 * This is debug only.
9871 				 */
9872 				ASSERT(un->un_pm_count == 0);
9873 			}
9874 		}
9875 
9876 		if (return_status == DDI_SUCCESS) {
9877 			/*
9878 			 * For performance, now that the device has been tagged
9879 			 * as busy, and it's known to be powered up, update the
9880 			 * chain types to use jump tables that do not include
9881 			 * pm. This significantly lowers the overhead and
9882 			 * therefore improves performance.
9883 			 */
9884 
9885 			mutex_exit(&un->un_pm_mutex);
9886 			mutex_enter(SD_MUTEX(un));
9887 			SD_TRACE(SD_LOG_IO_PM, un,
9888 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
9889 			    un->un_uscsi_chain_type);
9890 
9891 			if (un->un_f_non_devbsize_supported) {
9892 				un->un_buf_chain_type =
9893 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
9894 			} else {
9895 				un->un_buf_chain_type =
9896 				    SD_CHAIN_INFO_DISK_NO_PM;
9897 			}
9898 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
9899 
9900 			SD_TRACE(SD_LOG_IO_PM, un,
9901 			    "             changed  uscsi_chain_type to   %d\n",
9902 			    un->un_uscsi_chain_type);
9903 			mutex_exit(SD_MUTEX(un));
9904 			mutex_enter(&un->un_pm_mutex);
9905 
9906 			if (un->un_pm_idle_timeid == NULL) {
9907 				/* 300 ms. */
9908 				un->un_pm_idle_timeid =
9909 				    timeout(sd_pm_idletimeout_handler, un,
9910 				    (drv_usectohz((clock_t)300000)));
9911 				/*
9912 				 * Include an extra call to busy which keeps the
9913 				 * device busy with-respect-to the PM layer
9914 				 * until the timer fires, at which time it'll
9915 				 * get the extra idle call.
9916 				 */
9917 				(void) pm_busy_component(SD_DEVINFO(un), 0);
9918 			}
9919 		}
9920 	}
9921 	un->un_pm_busy = FALSE;
9922 	/* Next... */
9923 	cv_signal(&un->un_pm_busy_cv);
9924 
9925 	un->un_pm_count++;
9926 
9927 	SD_TRACE(SD_LOG_IO_PM, un,
9928 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
9929 
9930 	mutex_exit(&un->un_pm_mutex);
9931 
9932 	return (return_status);
9933 }
9934 
9935 
9936 /*
9937  *    Function: sd_pm_exit
9938  *
9939  * Description: Called at the completion of a command to manage busy
9940  *		status for the device. If the device becomes idle the
9941  *		PM framework is notified.
9942  *
9943  *     Context: Kernel thread context
9944  */
9945 
9946 static void
9947 sd_pm_exit(struct sd_lun *un)
9948 {
9949 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9950 	ASSERT(!mutex_owned(&un->un_pm_mutex));
9951 
9952 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
9953 
9954 	/*
9955 	 * After attach the following flag is only read, so don't
9956 	 * take the penalty of acquiring a mutex for it.
9957 	 */
9958 	if (un->un_f_pm_is_enabled == TRUE) {
9959 
9960 		mutex_enter(&un->un_pm_mutex);
9961 		un->un_pm_count--;
9962 
9963 		SD_TRACE(SD_LOG_IO_PM, un,
9964 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
9965 
9966 		ASSERT(un->un_pm_count >= 0);
9967 		if (un->un_pm_count == 0) {
9968 			mutex_exit(&un->un_pm_mutex);
9969 
9970 			SD_TRACE(SD_LOG_IO_PM, un,
9971 			    "sd_pm_exit: idle component\n");
9972 
9973 			(void) pm_idle_component(SD_DEVINFO(un), 0);
9974 
9975 		} else {
9976 			mutex_exit(&un->un_pm_mutex);
9977 		}
9978 	}
9979 
9980 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
9981 }
9982 
9983 
9984 /*
9985  *    Function: sdopen
9986  *
9987  * Description: Driver's open(9e) entry point function.
9988  *
9989  *   Arguments: dev_i   - pointer to device number
9990  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
9991  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9992  *		cred_p  - user credential pointer
9993  *
9994  * Return Code: EINVAL
9995  *		ENXIO
9996  *		EIO
9997  *		EROFS
9998  *		EBUSY
9999  *
10000  *     Context: Kernel thread context
10001  */
10002 /* ARGSUSED */
10003 static int
10004 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
10005 {
10006 	struct sd_lun	*un;
10007 	int		nodelay;
10008 	int		part;
10009 	uint64_t	partmask;
10010 	int		instance;
10011 	dev_t		dev;
10012 	int		rval = EIO;
10013 	diskaddr_t	nblks = 0;
10014 	diskaddr_t	label_cap;
10015 
10016 	/* Validate the open type */
10017 	if (otyp >= OTYPCNT) {
10018 		return (EINVAL);
10019 	}
10020 
10021 	dev = *dev_p;
10022 	instance = SDUNIT(dev);
10023 
10024 	/*
10025 	 * Fail the open if there is no softstate for the instance.
10026 	 */
10027 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
10028 		/*
10029 		 * The probe cache only needs to be cleared when open (9e) fails
10030 		 * with ENXIO (4238046).
10031 		 */
10032 		/*
10033 		 * un-conditionally clearing probe cache is ok with
10034 		 * separate sd/ssd binaries
10035 		 * x86 platform can be an issue with both parallel
10036 		 * and fibre in 1 binary
10037 		 */
10038 		sd_scsi_clear_probe_cache();
10039 		return (ENXIO);
10040 	}
10041 
10042 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
10043 	part	 = SDPART(dev);
10044 	partmask = 1 << part;
10045 
10046 	mutex_enter(SD_MUTEX(un));
10047 
10048 	/*
10049 	 * All device accesses go thru sdstrategy() where we check
10050 	 * on suspend status but there could be a scsi_poll command,
10051 	 * which bypasses sdstrategy(), so we need to check pm
10052 	 * status.
10053 	 */
10054 
10055 	if (!nodelay) {
10056 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10057 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10058 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10059 		}
10060 
10061 		mutex_exit(SD_MUTEX(un));
10062 		if (sd_pm_entry(un) != DDI_SUCCESS) {
10063 			rval = EIO;
10064 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
10065 			    "sdopen: sd_pm_entry failed\n");
10066 			goto open_failed_with_pm;
10067 		}
10068 		mutex_enter(SD_MUTEX(un));
10069 	}
10070 
10071 	/* check for previous exclusive open */
10072 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
10073 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10074 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
10075 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
10076 
10077 	if (un->un_exclopen & (partmask)) {
10078 		goto excl_open_fail;
10079 	}
10080 
10081 	if (flag & FEXCL) {
10082 		int i;
10083 		if (un->un_ocmap.lyropen[part]) {
10084 			goto excl_open_fail;
10085 		}
10086 		for (i = 0; i < (OTYPCNT - 1); i++) {
10087 			if (un->un_ocmap.regopen[i] & (partmask)) {
10088 				goto excl_open_fail;
10089 			}
10090 		}
10091 	}
10092 
10093 	/*
10094 	 * Check the write permission if this is a removable media device,
10095 	 * NDELAY has not been set, and writable permission is requested.
10096 	 *
10097 	 * Note: If NDELAY was set and this is write-protected media the WRITE
10098 	 * attempt will fail with EIO as part of the I/O processing. This is a
10099 	 * more permissive implementation that allows the open to succeed and
10100 	 * WRITE attempts to fail when appropriate.
10101 	 */
10102 	if (un->un_f_chk_wp_open) {
10103 		if ((flag & FWRITE) && (!nodelay)) {
10104 			mutex_exit(SD_MUTEX(un));
10105 			/*
10106 			 * Defer the check for write permission on writable
10107 			 * DVD drive till sdstrategy and will not fail open even
10108 			 * if FWRITE is set as the device can be writable
10109 			 * depending upon the media and the media can change
10110 			 * after the call to open().
10111 			 */
10112 			if (un->un_f_dvdram_writable_device == FALSE) {
10113 				if (ISCD(un) || sr_check_wp(dev)) {
10114 				rval = EROFS;
10115 				mutex_enter(SD_MUTEX(un));
10116 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10117 				    "write to cd or write protected media\n");
10118 				goto open_fail;
10119 				}
10120 			}
10121 			mutex_enter(SD_MUTEX(un));
10122 		}
10123 	}
10124 
10125 	/*
10126 	 * If opening in NDELAY/NONBLOCK mode, just return.
10127 	 * Check if disk is ready and has a valid geometry later.
10128 	 */
10129 	if (!nodelay) {
10130 		sd_ssc_t	*ssc;
10131 
10132 		mutex_exit(SD_MUTEX(un));
10133 		ssc = sd_ssc_init(un);
10134 		rval = sd_ready_and_valid(ssc, part);
10135 		sd_ssc_fini(ssc);
10136 		mutex_enter(SD_MUTEX(un));
10137 		/*
10138 		 * Fail if device is not ready or if the number of disk
10139 		 * blocks is zero or negative for non CD devices.
10140 		 */
10141 
10142 		nblks = 0;
10143 
10144 		if (rval == SD_READY_VALID && (!ISCD(un))) {
10145 			/* if cmlb_partinfo fails, nblks remains 0 */
10146 			mutex_exit(SD_MUTEX(un));
10147 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
10148 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
10149 			mutex_enter(SD_MUTEX(un));
10150 		}
10151 
10152 		if ((rval != SD_READY_VALID) ||
10153 		    (!ISCD(un) && nblks <= 0)) {
10154 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
10155 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10156 			    "device not ready or invalid disk block value\n");
10157 			goto open_fail;
10158 		}
10159 #if defined(__x86)
10160 	} else {
10161 		uchar_t *cp;
10162 		/*
10163 		 * x86 requires special nodelay handling, so that p0 is
10164 		 * always defined and accessible.
10165 		 * Invalidate geometry only if device is not already open.
10166 		 */
10167 		cp = &un->un_ocmap.chkd[0];
10168 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10169 			if (*cp != (uchar_t)0) {
10170 				break;
10171 			}
10172 			cp++;
10173 		}
10174 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10175 			mutex_exit(SD_MUTEX(un));
10176 			cmlb_invalidate(un->un_cmlbhandle,
10177 			    (void *)SD_PATH_DIRECT);
10178 			mutex_enter(SD_MUTEX(un));
10179 		}
10180 
10181 #endif
10182 	}
10183 
10184 	if (otyp == OTYP_LYR) {
10185 		un->un_ocmap.lyropen[part]++;
10186 	} else {
10187 		un->un_ocmap.regopen[otyp] |= partmask;
10188 	}
10189 
10190 	/* Set up open and exclusive open flags */
10191 	if (flag & FEXCL) {
10192 		un->un_exclopen |= (partmask);
10193 	}
10194 
10195 	/*
10196 	 * If the lun is EFI labeled and lun capacity is greater than the
10197 	 * capacity contained in the label, log a sys-event to notify the
10198 	 * interested module.
10199 	 * To avoid an infinite loop of logging sys-event, we only log the
10200 	 * event when the lun is not opened in NDELAY mode. The event handler
10201 	 * should open the lun in NDELAY mode.
10202 	 */
10203 	if (!nodelay) {
10204 		mutex_exit(SD_MUTEX(un));
10205 		if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
10206 		    (void*)SD_PATH_DIRECT) == 0) {
10207 			mutex_enter(SD_MUTEX(un));
10208 			if (un->un_f_blockcount_is_valid &&
10209 			    un->un_blockcount > label_cap &&
10210 			    un->un_f_expnevent == B_FALSE) {
10211 				un->un_f_expnevent = B_TRUE;
10212 				mutex_exit(SD_MUTEX(un));
10213 				sd_log_lun_expansion_event(un,
10214 				    (nodelay ? KM_NOSLEEP : KM_SLEEP));
10215 				mutex_enter(SD_MUTEX(un));
10216 			}
10217 		} else {
10218 			mutex_enter(SD_MUTEX(un));
10219 		}
10220 	}
10221 
10222 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
10223 	    "open of part %d type %d\n", part, otyp);
10224 
10225 	mutex_exit(SD_MUTEX(un));
10226 	if (!nodelay) {
10227 		sd_pm_exit(un);
10228 	}
10229 
10230 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
10231 	return (DDI_SUCCESS);
10232 
10233 excl_open_fail:
10234 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
10235 	rval = EBUSY;
10236 
10237 open_fail:
10238 	mutex_exit(SD_MUTEX(un));
10239 
10240 	/*
10241 	 * On a failed open we must exit the pm management.
10242 	 */
10243 	if (!nodelay) {
10244 		sd_pm_exit(un);
10245 	}
10246 open_failed_with_pm:
10247 
10248 	return (rval);
10249 }
10250 
10251 
10252 /*
10253  *    Function: sdclose
10254  *
10255  * Description: Driver's close(9e) entry point function.
10256  *
10257  *   Arguments: dev    - device number
10258  *		flag   - file status flag, informational only
10259  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
10260  *		cred_p - user credential pointer
10261  *
10262  * Return Code: ENXIO
10263  *
10264  *     Context: Kernel thread context
10265  */
10266 /* ARGSUSED */
10267 static int
10268 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
10269 {
10270 	struct sd_lun	*un;
10271 	uchar_t		*cp;
10272 	int		part;
10273 	int		nodelay;
10274 	int		rval = 0;
10275 
10276 	/* Validate the open type */
10277 	if (otyp >= OTYPCNT) {
10278 		return (ENXIO);
10279 	}
10280 
10281 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10282 		return (ENXIO);
10283 	}
10284 
10285 	part = SDPART(dev);
10286 	nodelay = flag & (FNDELAY | FNONBLOCK);
10287 
10288 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
10289 	    "sdclose: close of part %d type %d\n", part, otyp);
10290 
10291 	mutex_enter(SD_MUTEX(un));
10292 
10293 	/* Don't proceed if power is being changed. */
10294 	while (un->un_state == SD_STATE_PM_CHANGING) {
10295 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10296 	}
10297 
10298 	if (un->un_exclopen & (1 << part)) {
10299 		un->un_exclopen &= ~(1 << part);
10300 	}
10301 
10302 	/* Update the open partition map */
10303 	if (otyp == OTYP_LYR) {
10304 		un->un_ocmap.lyropen[part] -= 1;
10305 	} else {
10306 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
10307 	}
10308 
10309 	cp = &un->un_ocmap.chkd[0];
10310 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
10311 		if (*cp != '\0') {
10312 			break;
10313 		}
10314 		cp++;
10315 	}
10316 
10317 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
10318 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
10319 
10320 		/*
10321 		 * We avoid persistance upon the last close, and set
10322 		 * the throttle back to the maximum.
10323 		 */
10324 		un->un_throttle = un->un_saved_throttle;
10325 
10326 		if (un->un_state == SD_STATE_OFFLINE) {
10327 			if (un->un_f_is_fibre == FALSE) {
10328 				scsi_log(SD_DEVINFO(un), sd_label,
10329 				    CE_WARN, "offline\n");
10330 			}
10331 			mutex_exit(SD_MUTEX(un));
10332 			cmlb_invalidate(un->un_cmlbhandle,
10333 			    (void *)SD_PATH_DIRECT);
10334 			mutex_enter(SD_MUTEX(un));
10335 
10336 		} else {
10337 			/*
10338 			 * Flush any outstanding writes in NVRAM cache.
10339 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
10340 			 * cmd, it may not work for non-Pluto devices.
10341 			 * SYNCHRONIZE CACHE is not required for removables,
10342 			 * except DVD-RAM drives.
10343 			 *
10344 			 * Also note: because SYNCHRONIZE CACHE is currently
10345 			 * the only command issued here that requires the
10346 			 * drive be powered up, only do the power up before
10347 			 * sending the Sync Cache command. If additional
10348 			 * commands are added which require a powered up
10349 			 * drive, the following sequence may have to change.
10350 			 *
10351 			 * And finally, note that parallel SCSI on SPARC
10352 			 * only issues a Sync Cache to DVD-RAM, a newly
10353 			 * supported device.
10354 			 */
10355 #if defined(__x86)
10356 			if ((un->un_f_sync_cache_supported &&
10357 			    un->un_f_sync_cache_required) ||
10358 			    un->un_f_dvdram_writable_device == TRUE) {
10359 #else
10360 			if (un->un_f_dvdram_writable_device == TRUE) {
10361 #endif
10362 				mutex_exit(SD_MUTEX(un));
10363 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10364 					rval =
10365 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
10366 					    NULL);
10367 					/* ignore error if not supported */
10368 					if (rval == ENOTSUP) {
10369 						rval = 0;
10370 					} else if (rval != 0) {
10371 						rval = EIO;
10372 					}
10373 					sd_pm_exit(un);
10374 				} else {
10375 					rval = EIO;
10376 				}
10377 				mutex_enter(SD_MUTEX(un));
10378 			}
10379 
10380 			/*
10381 			 * For devices which supports DOOR_LOCK, send an ALLOW
10382 			 * MEDIA REMOVAL command, but don't get upset if it
10383 			 * fails. We need to raise the power of the drive before
10384 			 * we can call sd_send_scsi_DOORLOCK()
10385 			 */
10386 			if (un->un_f_doorlock_supported) {
10387 				mutex_exit(SD_MUTEX(un));
10388 				if (sd_pm_entry(un) == DDI_SUCCESS) {
10389 					sd_ssc_t	*ssc;
10390 
10391 					ssc = sd_ssc_init(un);
10392 					rval = sd_send_scsi_DOORLOCK(ssc,
10393 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
10394 					if (rval != 0)
10395 						sd_ssc_assessment(ssc,
10396 						    SD_FMT_IGNORE);
10397 					sd_ssc_fini(ssc);
10398 
10399 					sd_pm_exit(un);
10400 					if (ISCD(un) && (rval != 0) &&
10401 					    (nodelay != 0)) {
10402 						rval = ENXIO;
10403 					}
10404 				} else {
10405 					rval = EIO;
10406 				}
10407 				mutex_enter(SD_MUTEX(un));
10408 			}
10409 
10410 			/*
10411 			 * If a device has removable media, invalidate all
10412 			 * parameters related to media, such as geometry,
10413 			 * blocksize, and blockcount.
10414 			 */
10415 			if (un->un_f_has_removable_media) {
10416 				sr_ejected(un);
10417 			}
10418 
10419 			/*
10420 			 * Destroy the cache (if it exists) which was
10421 			 * allocated for the write maps, as long as no
10422 			 * other outstanding commands for the device exist.
10423 			 * (If we don't destroy it here, we will do so later
10424 			 * on detach.  More likely we'll just reuse it on
10425 			 * a future open.)
10426 			 */
10427 			if ((un->un_wm_cache != NULL) &&
10428 			    (un->un_ncmds_in_driver == 0)) {
10429 				kmem_cache_destroy(un->un_wm_cache);
10430 				un->un_wm_cache = NULL;
10431 			}
10432 		}
10433 	}
10434 
10435 	mutex_exit(SD_MUTEX(un));
10436 
10437 	return (rval);
10438 }
10439 
10440 
10441 /*
10442  *    Function: sd_ready_and_valid
10443  *
10444  * Description: Test if device is ready and has a valid geometry.
10445  *
10446  *   Arguments: ssc - sd_ssc_t will contain un
10447  *		un  - driver soft state (unit) structure
10448  *
10449  * Return Code: SD_READY_VALID		ready and valid label
10450  *		SD_NOT_READY_VALID	not ready, no label
10451  *		SD_RESERVED_BY_OTHERS	reservation conflict
10452  *
10453  *     Context: Never called at interrupt context.
10454  */
10455 
10456 static int
10457 sd_ready_and_valid(sd_ssc_t *ssc, int part)
10458 {
10459 	struct sd_errstats	*stp;
10460 	uint64_t		capacity;
10461 	uint_t			lbasize;
10462 	int			rval = SD_READY_VALID;
10463 	char			name_str[48];
10464 	boolean_t		is_valid;
10465 	struct sd_lun		*un;
10466 	int			status;
10467 
10468 	ASSERT(ssc != NULL);
10469 	un = ssc->ssc_un;
10470 	ASSERT(un != NULL);
10471 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10472 
10473 	mutex_enter(SD_MUTEX(un));
10474 	/*
10475 	 * If a device has removable media, we must check if media is
10476 	 * ready when checking if this device is ready and valid.
10477 	 */
10478 	if (un->un_f_has_removable_media) {
10479 		mutex_exit(SD_MUTEX(un));
10480 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10481 
10482 		if (status != 0) {
10483 			rval = SD_NOT_READY_VALID;
10484 			mutex_enter(SD_MUTEX(un));
10485 
10486 			/* Ignore all failed status for removalbe media */
10487 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10488 
10489 			goto done;
10490 		}
10491 
10492 		is_valid = SD_IS_VALID_LABEL(un);
10493 		mutex_enter(SD_MUTEX(un));
10494 		if (!is_valid ||
10495 		    (un->un_f_blockcount_is_valid == FALSE) ||
10496 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
10497 
10498 			/* capacity has to be read every open. */
10499 			mutex_exit(SD_MUTEX(un));
10500 			status = sd_send_scsi_READ_CAPACITY(ssc, &capacity,
10501 			    &lbasize, SD_PATH_DIRECT);
10502 
10503 			if (status != 0) {
10504 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10505 
10506 				cmlb_invalidate(un->un_cmlbhandle,
10507 				    (void *)SD_PATH_DIRECT);
10508 				mutex_enter(SD_MUTEX(un));
10509 				rval = SD_NOT_READY_VALID;
10510 
10511 				goto done;
10512 			} else {
10513 				mutex_enter(SD_MUTEX(un));
10514 				sd_update_block_info(un, lbasize, capacity);
10515 			}
10516 		}
10517 
10518 		/*
10519 		 * Check if the media in the device is writable or not.
10520 		 */
10521 		if (!is_valid && ISCD(un)) {
10522 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
10523 		}
10524 
10525 	} else {
10526 		/*
10527 		 * Do a test unit ready to clear any unit attention from non-cd
10528 		 * devices.
10529 		 */
10530 		mutex_exit(SD_MUTEX(un));
10531 
10532 		status = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10533 		if (status != 0) {
10534 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10535 		}
10536 
10537 		mutex_enter(SD_MUTEX(un));
10538 	}
10539 
10540 
10541 	/*
10542 	 * If this is a non 512 block device, allocate space for
10543 	 * the wmap cache. This is being done here since every time
10544 	 * a media is changed this routine will be called and the
10545 	 * block size is a function of media rather than device.
10546 	 */
10547 	if (((un->un_f_rmw_type != SD_RMW_TYPE_RETURN_ERROR ||
10548 	    un->un_f_non_devbsize_supported) &&
10549 	    un->un_tgt_blocksize != DEV_BSIZE) ||
10550 	    un->un_f_enable_rmw) {
10551 		if (!(un->un_wm_cache)) {
10552 			(void) snprintf(name_str, sizeof (name_str),
10553 			    "%s%d_cache",
10554 			    ddi_driver_name(SD_DEVINFO(un)),
10555 			    ddi_get_instance(SD_DEVINFO(un)));
10556 			un->un_wm_cache = kmem_cache_create(
10557 			    name_str, sizeof (struct sd_w_map),
10558 			    8, sd_wm_cache_constructor,
10559 			    sd_wm_cache_destructor, NULL,
10560 			    (void *)un, NULL, 0);
10561 			if (!(un->un_wm_cache)) {
10562 				rval = ENOMEM;
10563 				goto done;
10564 			}
10565 		}
10566 	}
10567 
10568 	if (un->un_state == SD_STATE_NORMAL) {
10569 		/*
10570 		 * If the target is not yet ready here (defined by a TUR
10571 		 * failure), invalidate the geometry and print an 'offline'
10572 		 * message. This is a legacy message, as the state of the
10573 		 * target is not actually changed to SD_STATE_OFFLINE.
10574 		 *
10575 		 * If the TUR fails for EACCES (Reservation Conflict),
10576 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
10577 		 * reservation conflict. If the TUR fails for other
10578 		 * reasons, SD_NOT_READY_VALID will be returned.
10579 		 */
10580 		int err;
10581 
10582 		mutex_exit(SD_MUTEX(un));
10583 		err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
10584 		mutex_enter(SD_MUTEX(un));
10585 
10586 		if (err != 0) {
10587 			mutex_exit(SD_MUTEX(un));
10588 			cmlb_invalidate(un->un_cmlbhandle,
10589 			    (void *)SD_PATH_DIRECT);
10590 			mutex_enter(SD_MUTEX(un));
10591 			if (err == EACCES) {
10592 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10593 				    "reservation conflict\n");
10594 				rval = SD_RESERVED_BY_OTHERS;
10595 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10596 			} else {
10597 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10598 				    "drive offline\n");
10599 				rval = SD_NOT_READY_VALID;
10600 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
10601 			}
10602 			goto done;
10603 		}
10604 	}
10605 
10606 	if (un->un_f_format_in_progress == FALSE) {
10607 		mutex_exit(SD_MUTEX(un));
10608 
10609 		(void) cmlb_validate(un->un_cmlbhandle, 0,
10610 		    (void *)SD_PATH_DIRECT);
10611 		if (cmlb_partinfo(un->un_cmlbhandle, part, NULL, NULL, NULL,
10612 		    NULL, (void *) SD_PATH_DIRECT) != 0) {
10613 			rval = SD_NOT_READY_VALID;
10614 			mutex_enter(SD_MUTEX(un));
10615 
10616 			goto done;
10617 		}
10618 		if (un->un_f_pkstats_enabled) {
10619 			sd_set_pstats(un);
10620 			SD_TRACE(SD_LOG_IO_PARTITION, un,
10621 			    "sd_ready_and_valid: un:0x%p pstats created and "
10622 			    "set\n", un);
10623 		}
10624 		mutex_enter(SD_MUTEX(un));
10625 	}
10626 
10627 	/*
10628 	 * If this device supports DOOR_LOCK command, try and send
10629 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
10630 	 * if it fails. For a CD, however, it is an error
10631 	 */
10632 	if (un->un_f_doorlock_supported) {
10633 		mutex_exit(SD_MUTEX(un));
10634 		status = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
10635 		    SD_PATH_DIRECT);
10636 
10637 		if ((status != 0) && ISCD(un)) {
10638 			rval = SD_NOT_READY_VALID;
10639 			mutex_enter(SD_MUTEX(un));
10640 
10641 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10642 
10643 			goto done;
10644 		} else if (status != 0)
10645 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
10646 		mutex_enter(SD_MUTEX(un));
10647 	}
10648 
10649 	/* The state has changed, inform the media watch routines */
10650 	un->un_mediastate = DKIO_INSERTED;
10651 	cv_broadcast(&un->un_state_cv);
10652 	rval = SD_READY_VALID;
10653 
10654 done:
10655 
10656 	/*
10657 	 * Initialize the capacity kstat value, if no media previously
10658 	 * (capacity kstat is 0) and a media has been inserted
10659 	 * (un_blockcount > 0).
10660 	 */
10661 	if (un->un_errstats != NULL) {
10662 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
10663 		if ((stp->sd_capacity.value.ui64 == 0) &&
10664 		    (un->un_f_blockcount_is_valid == TRUE)) {
10665 			stp->sd_capacity.value.ui64 =
10666 			    (uint64_t)((uint64_t)un->un_blockcount *
10667 			    un->un_sys_blocksize);
10668 		}
10669 	}
10670 
10671 	mutex_exit(SD_MUTEX(un));
10672 	return (rval);
10673 }
10674 
10675 
10676 /*
10677  *    Function: sdmin
10678  *
10679  * Description: Routine to limit the size of a data transfer. Used in
10680  *		conjunction with physio(9F).
10681  *
10682  *   Arguments: bp - pointer to the indicated buf(9S) struct.
10683  *
10684  *     Context: Kernel thread context.
10685  */
10686 
10687 static void
10688 sdmin(struct buf *bp)
10689 {
10690 	struct sd_lun	*un;
10691 	int		instance;
10692 
10693 	instance = SDUNIT(bp->b_edev);
10694 
10695 	un = ddi_get_soft_state(sd_state, instance);
10696 	ASSERT(un != NULL);
10697 
10698 	/*
10699 	 * We depend on buf breakup to restrict
10700 	 * IO size if it is enabled.
10701 	 */
10702 	if (un->un_buf_breakup_supported) {
10703 		return;
10704 	}
10705 
10706 	if (bp->b_bcount > un->un_max_xfer_size) {
10707 		bp->b_bcount = un->un_max_xfer_size;
10708 	}
10709 }
10710 
10711 
10712 /*
10713  *    Function: sdread
10714  *
10715  * Description: Driver's read(9e) entry point function.
10716  *
10717  *   Arguments: dev   - device number
10718  *		uio   - structure pointer describing where data is to be stored
10719  *			in user's space
10720  *		cred_p  - user credential pointer
10721  *
10722  * Return Code: ENXIO
10723  *		EIO
10724  *		EINVAL
10725  *		value returned by physio
10726  *
10727  *     Context: Kernel thread context.
10728  */
10729 /* ARGSUSED */
10730 static int
10731 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
10732 {
10733 	struct sd_lun	*un = NULL;
10734 	int		secmask;
10735 	int		err = 0;
10736 	sd_ssc_t	*ssc;
10737 
10738 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10739 		return (ENXIO);
10740 	}
10741 
10742 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10743 
10744 
10745 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10746 		mutex_enter(SD_MUTEX(un));
10747 		/*
10748 		 * Because the call to sd_ready_and_valid will issue I/O we
10749 		 * must wait here if either the device is suspended or
10750 		 * if it's power level is changing.
10751 		 */
10752 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10753 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10754 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10755 		}
10756 		un->un_ncmds_in_driver++;
10757 		mutex_exit(SD_MUTEX(un));
10758 
10759 		/* Initialize sd_ssc_t for internal uscsi commands */
10760 		ssc = sd_ssc_init(un);
10761 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10762 			err = EIO;
10763 		} else {
10764 			err = 0;
10765 		}
10766 		sd_ssc_fini(ssc);
10767 
10768 		mutex_enter(SD_MUTEX(un));
10769 		un->un_ncmds_in_driver--;
10770 		ASSERT(un->un_ncmds_in_driver >= 0);
10771 		mutex_exit(SD_MUTEX(un));
10772 		if (err != 0)
10773 			return (err);
10774 	}
10775 
10776 	/*
10777 	 * Read requests are restricted to multiples of the system block size.
10778 	 */
10779 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
10780 	    !un->un_f_enable_rmw)
10781 		secmask = un->un_tgt_blocksize - 1;
10782 	else
10783 		secmask = DEV_BSIZE - 1;
10784 
10785 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10786 		SD_ERROR(SD_LOG_READ_WRITE, un,
10787 		    "sdread: file offset not modulo %d\n",
10788 		    secmask + 1);
10789 		err = EINVAL;
10790 	} else if (uio->uio_iov->iov_len & (secmask)) {
10791 		SD_ERROR(SD_LOG_READ_WRITE, un,
10792 		    "sdread: transfer length not modulo %d\n",
10793 		    secmask + 1);
10794 		err = EINVAL;
10795 	} else {
10796 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
10797 	}
10798 
10799 	return (err);
10800 }
10801 
10802 
10803 /*
10804  *    Function: sdwrite
10805  *
10806  * Description: Driver's write(9e) entry point function.
10807  *
10808  *   Arguments: dev   - device number
10809  *		uio   - structure pointer describing where data is stored in
10810  *			user's space
10811  *		cred_p  - user credential pointer
10812  *
10813  * Return Code: ENXIO
10814  *		EIO
10815  *		EINVAL
10816  *		value returned by physio
10817  *
10818  *     Context: Kernel thread context.
10819  */
10820 /* ARGSUSED */
10821 static int
10822 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
10823 {
10824 	struct sd_lun	*un = NULL;
10825 	int		secmask;
10826 	int		err = 0;
10827 	sd_ssc_t	*ssc;
10828 
10829 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10830 		return (ENXIO);
10831 	}
10832 
10833 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10834 
10835 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10836 		mutex_enter(SD_MUTEX(un));
10837 		/*
10838 		 * Because the call to sd_ready_and_valid will issue I/O we
10839 		 * must wait here if either the device is suspended or
10840 		 * if it's power level is changing.
10841 		 */
10842 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10843 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10844 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10845 		}
10846 		un->un_ncmds_in_driver++;
10847 		mutex_exit(SD_MUTEX(un));
10848 
10849 		/* Initialize sd_ssc_t for internal uscsi commands */
10850 		ssc = sd_ssc_init(un);
10851 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10852 			err = EIO;
10853 		} else {
10854 			err = 0;
10855 		}
10856 		sd_ssc_fini(ssc);
10857 
10858 		mutex_enter(SD_MUTEX(un));
10859 		un->un_ncmds_in_driver--;
10860 		ASSERT(un->un_ncmds_in_driver >= 0);
10861 		mutex_exit(SD_MUTEX(un));
10862 		if (err != 0)
10863 			return (err);
10864 	}
10865 
10866 	/*
10867 	 * Write requests are restricted to multiples of the system block size.
10868 	 */
10869 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
10870 	    !un->un_f_enable_rmw)
10871 		secmask = un->un_tgt_blocksize - 1;
10872 	else
10873 		secmask = DEV_BSIZE - 1;
10874 
10875 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10876 		SD_ERROR(SD_LOG_READ_WRITE, un,
10877 		    "sdwrite: file offset not modulo %d\n",
10878 		    secmask + 1);
10879 		err = EINVAL;
10880 	} else if (uio->uio_iov->iov_len & (secmask)) {
10881 		SD_ERROR(SD_LOG_READ_WRITE, un,
10882 		    "sdwrite: transfer length not modulo %d\n",
10883 		    secmask + 1);
10884 		err = EINVAL;
10885 	} else {
10886 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
10887 	}
10888 
10889 	return (err);
10890 }
10891 
10892 
10893 /*
10894  *    Function: sdaread
10895  *
10896  * Description: Driver's aread(9e) entry point function.
10897  *
10898  *   Arguments: dev   - device number
10899  *		aio   - structure pointer describing where data is to be stored
10900  *		cred_p  - user credential pointer
10901  *
10902  * Return Code: ENXIO
10903  *		EIO
10904  *		EINVAL
10905  *		value returned by aphysio
10906  *
10907  *     Context: Kernel thread context.
10908  */
10909 /* ARGSUSED */
10910 static int
10911 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
10912 {
10913 	struct sd_lun	*un = NULL;
10914 	struct uio	*uio = aio->aio_uio;
10915 	int		secmask;
10916 	int		err = 0;
10917 	sd_ssc_t	*ssc;
10918 
10919 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10920 		return (ENXIO);
10921 	}
10922 
10923 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10924 
10925 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10926 		mutex_enter(SD_MUTEX(un));
10927 		/*
10928 		 * Because the call to sd_ready_and_valid will issue I/O we
10929 		 * must wait here if either the device is suspended or
10930 		 * if it's power level is changing.
10931 		 */
10932 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10933 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10934 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10935 		}
10936 		un->un_ncmds_in_driver++;
10937 		mutex_exit(SD_MUTEX(un));
10938 
10939 		/* Initialize sd_ssc_t for internal uscsi commands */
10940 		ssc = sd_ssc_init(un);
10941 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
10942 			err = EIO;
10943 		} else {
10944 			err = 0;
10945 		}
10946 		sd_ssc_fini(ssc);
10947 
10948 		mutex_enter(SD_MUTEX(un));
10949 		un->un_ncmds_in_driver--;
10950 		ASSERT(un->un_ncmds_in_driver >= 0);
10951 		mutex_exit(SD_MUTEX(un));
10952 		if (err != 0)
10953 			return (err);
10954 	}
10955 
10956 	/*
10957 	 * Read requests are restricted to multiples of the system block size.
10958 	 */
10959 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
10960 	    !un->un_f_enable_rmw)
10961 		secmask = un->un_tgt_blocksize - 1;
10962 	else
10963 		secmask = DEV_BSIZE - 1;
10964 
10965 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10966 		SD_ERROR(SD_LOG_READ_WRITE, un,
10967 		    "sdaread: file offset not modulo %d\n",
10968 		    secmask + 1);
10969 		err = EINVAL;
10970 	} else if (uio->uio_iov->iov_len & (secmask)) {
10971 		SD_ERROR(SD_LOG_READ_WRITE, un,
10972 		    "sdaread: transfer length not modulo %d\n",
10973 		    secmask + 1);
10974 		err = EINVAL;
10975 	} else {
10976 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
10977 	}
10978 
10979 	return (err);
10980 }
10981 
10982 
10983 /*
10984  *    Function: sdawrite
10985  *
10986  * Description: Driver's awrite(9e) entry point function.
10987  *
10988  *   Arguments: dev   - device number
10989  *		aio   - structure pointer describing where data is stored
10990  *		cred_p  - user credential pointer
10991  *
10992  * Return Code: ENXIO
10993  *		EIO
10994  *		EINVAL
10995  *		value returned by aphysio
10996  *
10997  *     Context: Kernel thread context.
10998  */
10999 /* ARGSUSED */
11000 static int
11001 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
11002 {
11003 	struct sd_lun	*un = NULL;
11004 	struct uio	*uio = aio->aio_uio;
11005 	int		secmask;
11006 	int		err = 0;
11007 	sd_ssc_t	*ssc;
11008 
11009 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
11010 		return (ENXIO);
11011 	}
11012 
11013 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11014 
11015 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
11016 		mutex_enter(SD_MUTEX(un));
11017 		/*
11018 		 * Because the call to sd_ready_and_valid will issue I/O we
11019 		 * must wait here if either the device is suspended or
11020 		 * if it's power level is changing.
11021 		 */
11022 		while ((un->un_state == SD_STATE_SUSPENDED) ||
11023 		    (un->un_state == SD_STATE_PM_CHANGING)) {
11024 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11025 		}
11026 		un->un_ncmds_in_driver++;
11027 		mutex_exit(SD_MUTEX(un));
11028 
11029 		/* Initialize sd_ssc_t for internal uscsi commands */
11030 		ssc = sd_ssc_init(un);
11031 		if ((sd_ready_and_valid(ssc, SDPART(dev))) != SD_READY_VALID) {
11032 			err = EIO;
11033 		} else {
11034 			err = 0;
11035 		}
11036 		sd_ssc_fini(ssc);
11037 
11038 		mutex_enter(SD_MUTEX(un));
11039 		un->un_ncmds_in_driver--;
11040 		ASSERT(un->un_ncmds_in_driver >= 0);
11041 		mutex_exit(SD_MUTEX(un));
11042 		if (err != 0)
11043 			return (err);
11044 	}
11045 
11046 	/*
11047 	 * Write requests are restricted to multiples of the system block size.
11048 	 */
11049 	if (un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR &&
11050 	    !un->un_f_enable_rmw)
11051 		secmask = un->un_tgt_blocksize - 1;
11052 	else
11053 		secmask = DEV_BSIZE - 1;
11054 
11055 	if (uio->uio_loffset & ((offset_t)(secmask))) {
11056 		SD_ERROR(SD_LOG_READ_WRITE, un,
11057 		    "sdawrite: file offset not modulo %d\n",
11058 		    secmask + 1);
11059 		err = EINVAL;
11060 	} else if (uio->uio_iov->iov_len & (secmask)) {
11061 		SD_ERROR(SD_LOG_READ_WRITE, un,
11062 		    "sdawrite: transfer length not modulo %d\n",
11063 		    secmask + 1);
11064 		err = EINVAL;
11065 	} else {
11066 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
11067 	}
11068 
11069 	return (err);
11070 }
11071 
11072 
11073 
11074 
11075 
11076 /*
11077  * Driver IO processing follows the following sequence:
11078  *
11079  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
11080  *         |                |                     ^
11081  *         v                v                     |
11082  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
11083  *         |                |                     |                   |
11084  *         v                |                     |                   |
11085  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
11086  *         |                |                     ^                   ^
11087  *         v                v                     |                   |
11088  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
11089  *         |                |                     |                   |
11090  *     +---+                |                     +------------+      +-------+
11091  *     |                    |                                  |              |
11092  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11093  *     |                    v                                  |              |
11094  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
11095  *     |                    |                                  ^              |
11096  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11097  *     |                    v                                  |              |
11098  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
11099  *     |                    |                                  ^              |
11100  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
11101  *     |                    v                                  |              |
11102  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
11103  *     |                    |                                  ^              |
11104  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
11105  *     |                    v                                  |              |
11106  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
11107  *     |                    |                                  ^              |
11108  *     |                    |                                  |              |
11109  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
11110  *                          |                           ^
11111  *                          v                           |
11112  *                   sd_core_iostart()                  |
11113  *                          |                           |
11114  *                          |                           +------>(*destroypkt)()
11115  *                          +-> sd_start_cmds() <-+     |           |
11116  *                          |                     |     |           v
11117  *                          |                     |     |  scsi_destroy_pkt(9F)
11118  *                          |                     |     |
11119  *                          +->(*initpkt)()       +- sdintr()
11120  *                          |  |                        |  |
11121  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
11122  *                          |  +-> scsi_setup_cdb(9F)   |
11123  *                          |                           |
11124  *                          +--> scsi_transport(9F)     |
11125  *                                     |                |
11126  *                                     +----> SCSA ---->+
11127  *
11128  *
11129  * This code is based upon the following presumptions:
11130  *
11131  *   - iostart and iodone functions operate on buf(9S) structures. These
11132  *     functions perform the necessary operations on the buf(9S) and pass
11133  *     them along to the next function in the chain by using the macros
11134  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
11135  *     (for iodone side functions).
11136  *
11137  *   - The iostart side functions may sleep. The iodone side functions
11138  *     are called under interrupt context and may NOT sleep. Therefore
11139  *     iodone side functions also may not call iostart side functions.
11140  *     (NOTE: iostart side functions should NOT sleep for memory, as
11141  *     this could result in deadlock.)
11142  *
11143  *   - An iostart side function may call its corresponding iodone side
11144  *     function directly (if necessary).
11145  *
11146  *   - In the event of an error, an iostart side function can return a buf(9S)
11147  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
11148  *     b_error in the usual way of course).
11149  *
11150  *   - The taskq mechanism may be used by the iodone side functions to dispatch
11151  *     requests to the iostart side functions.  The iostart side functions in
11152  *     this case would be called under the context of a taskq thread, so it's
11153  *     OK for them to block/sleep/spin in this case.
11154  *
11155  *   - iostart side functions may allocate "shadow" buf(9S) structs and
11156  *     pass them along to the next function in the chain.  The corresponding
11157  *     iodone side functions must coalesce the "shadow" bufs and return
11158  *     the "original" buf to the next higher layer.
11159  *
11160  *   - The b_private field of the buf(9S) struct holds a pointer to
11161  *     an sd_xbuf struct, which contains information needed to
11162  *     construct the scsi_pkt for the command.
11163  *
11164  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
11165  *     layer must acquire & release the SD_MUTEX(un) as needed.
11166  */
11167 
11168 
11169 /*
11170  * Create taskq for all targets in the system. This is created at
11171  * _init(9E) and destroyed at _fini(9E).
11172  *
11173  * Note: here we set the minalloc to a reasonably high number to ensure that
11174  * we will have an adequate supply of task entries available at interrupt time.
11175  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
11176  * sd_create_taskq().  Since we do not want to sleep for allocations at
11177  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
11178  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
11179  * requests any one instant in time.
11180  */
11181 #define	SD_TASKQ_NUMTHREADS	8
11182 #define	SD_TASKQ_MINALLOC	256
11183 #define	SD_TASKQ_MAXALLOC	256
11184 
11185 static taskq_t	*sd_tq = NULL;
11186 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
11187 
11188 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
11189 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
11190 
11191 /*
11192  * The following task queue is being created for the write part of
11193  * read-modify-write of non-512 block size devices.
11194  * Limit the number of threads to 1 for now. This number has been chosen
11195  * considering the fact that it applies only to dvd ram drives/MO drives
11196  * currently. Performance for which is not main criteria at this stage.
11197  * Note: It needs to be explored if we can use a single taskq in future
11198  */
11199 #define	SD_WMR_TASKQ_NUMTHREADS	1
11200 static taskq_t	*sd_wmr_tq = NULL;
11201 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
11202 
11203 /*
11204  *    Function: sd_taskq_create
11205  *
11206  * Description: Create taskq thread(s) and preallocate task entries
11207  *
11208  * Return Code: Returns a pointer to the allocated taskq_t.
11209  *
11210  *     Context: Can sleep. Requires blockable context.
11211  *
11212  *       Notes: - The taskq() facility currently is NOT part of the DDI.
11213  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
11214  *		- taskq_create() will block for memory, also it will panic
11215  *		  if it cannot create the requested number of threads.
11216  *		- Currently taskq_create() creates threads that cannot be
11217  *		  swapped.
11218  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
11219  *		  supply of taskq entries at interrupt time (ie, so that we
11220  *		  do not have to sleep for memory)
11221  */
11222 
11223 static void
11224 sd_taskq_create(void)
11225 {
11226 	char	taskq_name[TASKQ_NAMELEN];
11227 
11228 	ASSERT(sd_tq == NULL);
11229 	ASSERT(sd_wmr_tq == NULL);
11230 
11231 	(void) snprintf(taskq_name, sizeof (taskq_name),
11232 	    "%s_drv_taskq", sd_label);
11233 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
11234 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11235 	    TASKQ_PREPOPULATE));
11236 
11237 	(void) snprintf(taskq_name, sizeof (taskq_name),
11238 	    "%s_rmw_taskq", sd_label);
11239 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
11240 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
11241 	    TASKQ_PREPOPULATE));
11242 }
11243 
11244 
11245 /*
11246  *    Function: sd_taskq_delete
11247  *
11248  * Description: Complementary cleanup routine for sd_taskq_create().
11249  *
11250  *     Context: Kernel thread context.
11251  */
11252 
11253 static void
11254 sd_taskq_delete(void)
11255 {
11256 	ASSERT(sd_tq != NULL);
11257 	ASSERT(sd_wmr_tq != NULL);
11258 	taskq_destroy(sd_tq);
11259 	taskq_destroy(sd_wmr_tq);
11260 	sd_tq = NULL;
11261 	sd_wmr_tq = NULL;
11262 }
11263 
11264 
11265 /*
11266  *    Function: sdstrategy
11267  *
11268  * Description: Driver's strategy (9E) entry point function.
11269  *
11270  *   Arguments: bp - pointer to buf(9S)
11271  *
11272  * Return Code: Always returns zero
11273  *
11274  *     Context: Kernel thread context.
11275  */
11276 
11277 static int
11278 sdstrategy(struct buf *bp)
11279 {
11280 	struct sd_lun *un;
11281 
11282 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11283 	if (un == NULL) {
11284 		bioerror(bp, EIO);
11285 		bp->b_resid = bp->b_bcount;
11286 		biodone(bp);
11287 		return (0);
11288 	}
11289 
11290 	/* As was done in the past, fail new cmds. if state is dumping. */
11291 	if (un->un_state == SD_STATE_DUMPING) {
11292 		bioerror(bp, ENXIO);
11293 		bp->b_resid = bp->b_bcount;
11294 		biodone(bp);
11295 		return (0);
11296 	}
11297 
11298 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11299 
11300 	/*
11301 	 * Commands may sneak in while we released the mutex in
11302 	 * DDI_SUSPEND, we should block new commands. However, old
11303 	 * commands that are still in the driver at this point should
11304 	 * still be allowed to drain.
11305 	 */
11306 	mutex_enter(SD_MUTEX(un));
11307 	/*
11308 	 * Must wait here if either the device is suspended or
11309 	 * if it's power level is changing.
11310 	 */
11311 	while ((un->un_state == SD_STATE_SUSPENDED) ||
11312 	    (un->un_state == SD_STATE_PM_CHANGING)) {
11313 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
11314 	}
11315 
11316 	un->un_ncmds_in_driver++;
11317 
11318 	/*
11319 	 * atapi: Since we are running the CD for now in PIO mode we need to
11320 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11321 	 * the HBA's init_pkt routine.
11322 	 */
11323 	if (un->un_f_cfg_is_atapi == TRUE) {
11324 		mutex_exit(SD_MUTEX(un));
11325 		bp_mapin(bp);
11326 		mutex_enter(SD_MUTEX(un));
11327 	}
11328 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
11329 	    un->un_ncmds_in_driver);
11330 
11331 	if (bp->b_flags & B_WRITE)
11332 		un->un_f_sync_cache_required = TRUE;
11333 
11334 	mutex_exit(SD_MUTEX(un));
11335 
11336 	/*
11337 	 * This will (eventually) allocate the sd_xbuf area and
11338 	 * call sd_xbuf_strategy().  We just want to return the
11339 	 * result of ddi_xbuf_qstrategy so that we have an opt-
11340 	 * imized tail call which saves us a stack frame.
11341 	 */
11342 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
11343 }
11344 
11345 
11346 /*
11347  *    Function: sd_xbuf_strategy
11348  *
11349  * Description: Function for initiating IO operations via the
11350  *		ddi_xbuf_qstrategy() mechanism.
11351  *
11352  *     Context: Kernel thread context.
11353  */
11354 
11355 static void
11356 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
11357 {
11358 	struct sd_lun *un = arg;
11359 
11360 	ASSERT(bp != NULL);
11361 	ASSERT(xp != NULL);
11362 	ASSERT(un != NULL);
11363 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11364 
11365 	/*
11366 	 * Initialize the fields in the xbuf and save a pointer to the
11367 	 * xbuf in bp->b_private.
11368 	 */
11369 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
11370 
11371 	/* Send the buf down the iostart chain */
11372 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
11373 }
11374 
11375 
11376 /*
11377  *    Function: sd_xbuf_init
11378  *
11379  * Description: Prepare the given sd_xbuf struct for use.
11380  *
11381  *   Arguments: un - ptr to softstate
11382  *		bp - ptr to associated buf(9S)
11383  *		xp - ptr to associated sd_xbuf
11384  *		chain_type - IO chain type to use:
11385  *			SD_CHAIN_NULL
11386  *			SD_CHAIN_BUFIO
11387  *			SD_CHAIN_USCSI
11388  *			SD_CHAIN_DIRECT
11389  *			SD_CHAIN_DIRECT_PRIORITY
11390  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
11391  *			initialization; may be NULL if none.
11392  *
11393  *     Context: Kernel thread context
11394  */
11395 
11396 static void
11397 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
11398     uchar_t chain_type, void *pktinfop)
11399 {
11400 	int index;
11401 
11402 	ASSERT(un != NULL);
11403 	ASSERT(bp != NULL);
11404 	ASSERT(xp != NULL);
11405 
11406 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
11407 	    bp, chain_type);
11408 
11409 	xp->xb_un	= un;
11410 	xp->xb_pktp	= NULL;
11411 	xp->xb_pktinfo	= pktinfop;
11412 	xp->xb_private	= bp->b_private;
11413 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
11414 
11415 	/*
11416 	 * Set up the iostart and iodone chain indexes in the xbuf, based
11417 	 * upon the specified chain type to use.
11418 	 */
11419 	switch (chain_type) {
11420 	case SD_CHAIN_NULL:
11421 		/*
11422 		 * Fall thru to just use the values for the buf type, even
11423 		 * tho for the NULL chain these values will never be used.
11424 		 */
11425 		/* FALLTHRU */
11426 	case SD_CHAIN_BUFIO:
11427 		index = un->un_buf_chain_type;
11428 		if ((!un->un_f_has_removable_media) &&
11429 		    (un->un_tgt_blocksize != 0) &&
11430 		    (un->un_tgt_blocksize != DEV_BSIZE ||
11431 		    un->un_f_enable_rmw)) {
11432 			int secmask = 0, blknomask = 0;
11433 			if (un->un_f_enable_rmw) {
11434 				blknomask =
11435 				    (un->un_phy_blocksize / DEV_BSIZE) - 1;
11436 				secmask = un->un_phy_blocksize - 1;
11437 			} else {
11438 				blknomask =
11439 				    (un->un_tgt_blocksize / DEV_BSIZE) - 1;
11440 				secmask = un->un_tgt_blocksize - 1;
11441 			}
11442 
11443 			if ((bp->b_lblkno & (blknomask)) ||
11444 			    (bp->b_bcount & (secmask))) {
11445 				if ((un->un_f_rmw_type !=
11446 				    SD_RMW_TYPE_RETURN_ERROR) ||
11447 				    un->un_f_enable_rmw) {
11448 					if (un->un_f_pm_is_enabled == FALSE)
11449 						index =
11450 						    SD_CHAIN_INFO_MSS_DSK_NO_PM;
11451 					else
11452 						index =
11453 						    SD_CHAIN_INFO_MSS_DISK;
11454 				}
11455 			}
11456 		}
11457 		break;
11458 	case SD_CHAIN_USCSI:
11459 		index = un->un_uscsi_chain_type;
11460 		break;
11461 	case SD_CHAIN_DIRECT:
11462 		index = un->un_direct_chain_type;
11463 		break;
11464 	case SD_CHAIN_DIRECT_PRIORITY:
11465 		index = un->un_priority_chain_type;
11466 		break;
11467 	default:
11468 		/* We're really broken if we ever get here... */
11469 		panic("sd_xbuf_init: illegal chain type!");
11470 		/*NOTREACHED*/
11471 	}
11472 
11473 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
11474 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
11475 
11476 	/*
11477 	 * It might be a bit easier to simply bzero the entire xbuf above,
11478 	 * but it turns out that since we init a fair number of members anyway,
11479 	 * we save a fair number cycles by doing explicit assignment of zero.
11480 	 */
11481 	xp->xb_pkt_flags	= 0;
11482 	xp->xb_dma_resid	= 0;
11483 	xp->xb_retry_count	= 0;
11484 	xp->xb_victim_retry_count = 0;
11485 	xp->xb_ua_retry_count	= 0;
11486 	xp->xb_nr_retry_count	= 0;
11487 	xp->xb_sense_bp		= NULL;
11488 	xp->xb_sense_status	= 0;
11489 	xp->xb_sense_state	= 0;
11490 	xp->xb_sense_resid	= 0;
11491 	xp->xb_ena		= 0;
11492 
11493 	bp->b_private	= xp;
11494 	bp->b_flags	&= ~(B_DONE | B_ERROR);
11495 	bp->b_resid	= 0;
11496 	bp->av_forw	= NULL;
11497 	bp->av_back	= NULL;
11498 	bioerror(bp, 0);
11499 
11500 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
11501 }
11502 
11503 
11504 /*
11505  *    Function: sd_uscsi_strategy
11506  *
11507  * Description: Wrapper for calling into the USCSI chain via physio(9F)
11508  *
11509  *   Arguments: bp - buf struct ptr
11510  *
11511  * Return Code: Always returns 0
11512  *
11513  *     Context: Kernel thread context
11514  */
11515 
11516 static int
11517 sd_uscsi_strategy(struct buf *bp)
11518 {
11519 	struct sd_lun		*un;
11520 	struct sd_uscsi_info	*uip;
11521 	struct sd_xbuf		*xp;
11522 	uchar_t			chain_type;
11523 	uchar_t			cmd;
11524 
11525 	ASSERT(bp != NULL);
11526 
11527 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
11528 	if (un == NULL) {
11529 		bioerror(bp, EIO);
11530 		bp->b_resid = bp->b_bcount;
11531 		biodone(bp);
11532 		return (0);
11533 	}
11534 
11535 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11536 
11537 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
11538 
11539 	/*
11540 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
11541 	 */
11542 	ASSERT(bp->b_private != NULL);
11543 	uip = (struct sd_uscsi_info *)bp->b_private;
11544 	cmd = ((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_cdb[0];
11545 
11546 	mutex_enter(SD_MUTEX(un));
11547 	/*
11548 	 * atapi: Since we are running the CD for now in PIO mode we need to
11549 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
11550 	 * the HBA's init_pkt routine.
11551 	 */
11552 	if (un->un_f_cfg_is_atapi == TRUE) {
11553 		mutex_exit(SD_MUTEX(un));
11554 		bp_mapin(bp);
11555 		mutex_enter(SD_MUTEX(un));
11556 	}
11557 	un->un_ncmds_in_driver++;
11558 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
11559 	    un->un_ncmds_in_driver);
11560 
11561 	if ((bp->b_flags & B_WRITE) && (bp->b_bcount != 0) &&
11562 	    (cmd != SCMD_MODE_SELECT) && (cmd != SCMD_MODE_SELECT_G1))
11563 		un->un_f_sync_cache_required = TRUE;
11564 
11565 	mutex_exit(SD_MUTEX(un));
11566 
11567 	switch (uip->ui_flags) {
11568 	case SD_PATH_DIRECT:
11569 		chain_type = SD_CHAIN_DIRECT;
11570 		break;
11571 	case SD_PATH_DIRECT_PRIORITY:
11572 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
11573 		break;
11574 	default:
11575 		chain_type = SD_CHAIN_USCSI;
11576 		break;
11577 	}
11578 
11579 	/*
11580 	 * We may allocate extra buf for external USCSI commands. If the
11581 	 * application asks for bigger than 20-byte sense data via USCSI,
11582 	 * SCSA layer will allocate 252 bytes sense buf for that command.
11583 	 */
11584 	if (((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_rqlen >
11585 	    SENSE_LENGTH) {
11586 		xp = kmem_zalloc(sizeof (struct sd_xbuf) - SENSE_LENGTH +
11587 		    MAX_SENSE_LENGTH, KM_SLEEP);
11588 	} else {
11589 		xp = kmem_zalloc(sizeof (struct sd_xbuf), KM_SLEEP);
11590 	}
11591 
11592 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
11593 
11594 	/* Use the index obtained within xbuf_init */
11595 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
11596 
11597 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
11598 
11599 	return (0);
11600 }
11601 
11602 /*
11603  *    Function: sd_send_scsi_cmd
11604  *
11605  * Description: Runs a USCSI command for user (when called thru sdioctl),
11606  *		or for the driver
11607  *
11608  *   Arguments: dev - the dev_t for the device
11609  *		incmd - ptr to a valid uscsi_cmd struct
11610  *		flag - bit flag, indicating open settings, 32/64 bit type
11611  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11612  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11613  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11614  *			to use the USCSI "direct" chain and bypass the normal
11615  *			command waitq.
11616  *
11617  * Return Code: 0 -  successful completion of the given command
11618  *		EIO - scsi_uscsi_handle_command() failed
11619  *		ENXIO  - soft state not found for specified dev
11620  *		EINVAL
11621  *		EFAULT - copyin/copyout error
11622  *		return code of scsi_uscsi_handle_command():
11623  *			EIO
11624  *			ENXIO
11625  *			EACCES
11626  *
11627  *     Context: Waits for command to complete. Can sleep.
11628  */
11629 
11630 static int
11631 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
11632     enum uio_seg dataspace, int path_flag)
11633 {
11634 	struct sd_lun	*un;
11635 	sd_ssc_t	*ssc;
11636 	int		rval;
11637 
11638 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
11639 	if (un == NULL) {
11640 		return (ENXIO);
11641 	}
11642 
11643 	/*
11644 	 * Using sd_ssc_send to handle uscsi cmd
11645 	 */
11646 	ssc = sd_ssc_init(un);
11647 	rval = sd_ssc_send(ssc, incmd, flag, dataspace, path_flag);
11648 	sd_ssc_fini(ssc);
11649 
11650 	return (rval);
11651 }
11652 
11653 /*
11654  *    Function: sd_ssc_init
11655  *
11656  * Description: Uscsi end-user call this function to initialize necessary
11657  *              fields, such as uscsi_cmd and sd_uscsi_info struct.
11658  *
11659  *              The return value of sd_send_scsi_cmd will be treated as a
11660  *              fault in various conditions. Even it is not Zero, some
11661  *              callers may ignore the return value. That is to say, we can
11662  *              not make an accurate assessment in sdintr, since if a
11663  *              command is failed in sdintr it does not mean the caller of
11664  *              sd_send_scsi_cmd will treat it as a real failure.
11665  *
11666  *              To avoid printing too many error logs for a failed uscsi
11667  *              packet that the caller may not treat it as a failure, the
11668  *              sd will keep silent for handling all uscsi commands.
11669  *
11670  *              During detach->attach and attach-open, for some types of
11671  *              problems, the driver should be providing information about
11672  *              the problem encountered. Device use USCSI_SILENT, which
11673  *              suppresses all driver information. The result is that no
11674  *              information about the problem is available. Being
11675  *              completely silent during this time is inappropriate. The
11676  *              driver needs a more selective filter than USCSI_SILENT, so
11677  *              that information related to faults is provided.
11678  *
11679  *              To make the accurate accessment, the caller  of
11680  *              sd_send_scsi_USCSI_CMD should take the ownership and
11681  *              get necessary information to print error messages.
11682  *
11683  *              If we want to print necessary info of uscsi command, we need to
11684  *              keep the uscsi_cmd and sd_uscsi_info till we can make the
11685  *              assessment. We use sd_ssc_init to alloc necessary
11686  *              structs for sending an uscsi command and we are also
11687  *              responsible for free the memory by calling
11688  *              sd_ssc_fini.
11689  *
11690  *              The calling secquences will look like:
11691  *              sd_ssc_init->
11692  *
11693  *                  ...
11694  *
11695  *                  sd_send_scsi_USCSI_CMD->
11696  *                      sd_ssc_send-> - - - sdintr
11697  *                  ...
11698  *
11699  *                  if we think the return value should be treated as a
11700  *                  failure, we make the accessment here and print out
11701  *                  necessary by retrieving uscsi_cmd and sd_uscsi_info'
11702  *
11703  *                  ...
11704  *
11705  *              sd_ssc_fini
11706  *
11707  *
11708  *   Arguments: un - pointer to driver soft state (unit) structure for this
11709  *                   target.
11710  *
11711  * Return code: sd_ssc_t - pointer to allocated sd_ssc_t struct, it contains
11712  *                         uscsi_cmd and sd_uscsi_info.
11713  *                  NULL - if can not alloc memory for sd_ssc_t struct
11714  *
11715  *     Context: Kernel Thread.
11716  */
11717 static sd_ssc_t *
11718 sd_ssc_init(struct sd_lun *un)
11719 {
11720 	sd_ssc_t		*ssc;
11721 	struct uscsi_cmd	*ucmdp;
11722 	struct sd_uscsi_info	*uip;
11723 
11724 	ASSERT(un != NULL);
11725 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11726 
11727 	/*
11728 	 * Allocate sd_ssc_t structure
11729 	 */
11730 	ssc = kmem_zalloc(sizeof (sd_ssc_t), KM_SLEEP);
11731 
11732 	/*
11733 	 * Allocate uscsi_cmd by calling scsi_uscsi_alloc common routine
11734 	 */
11735 	ucmdp = scsi_uscsi_alloc();
11736 
11737 	/*
11738 	 * Allocate sd_uscsi_info structure
11739 	 */
11740 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
11741 
11742 	ssc->ssc_uscsi_cmd = ucmdp;
11743 	ssc->ssc_uscsi_info = uip;
11744 	ssc->ssc_un = un;
11745 
11746 	return (ssc);
11747 }
11748 
11749 /*
11750  * Function: sd_ssc_fini
11751  *
11752  * Description: To free sd_ssc_t and it's hanging off
11753  *
11754  * Arguments: ssc - struct pointer of sd_ssc_t.
11755  */
11756 static void
11757 sd_ssc_fini(sd_ssc_t *ssc)
11758 {
11759 	scsi_uscsi_free(ssc->ssc_uscsi_cmd);
11760 
11761 	if (ssc->ssc_uscsi_info != NULL) {
11762 		kmem_free(ssc->ssc_uscsi_info, sizeof (struct sd_uscsi_info));
11763 		ssc->ssc_uscsi_info = NULL;
11764 	}
11765 
11766 	kmem_free(ssc, sizeof (sd_ssc_t));
11767 	ssc = NULL;
11768 }
11769 
11770 /*
11771  * Function: sd_ssc_send
11772  *
11773  * Description: Runs a USCSI command for user when called through sdioctl,
11774  *              or for the driver.
11775  *
11776  *   Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
11777  *                    sd_uscsi_info in.
11778  *		incmd - ptr to a valid uscsi_cmd struct
11779  *		flag - bit flag, indicating open settings, 32/64 bit type
11780  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
11781  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
11782  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
11783  *			to use the USCSI "direct" chain and bypass the normal
11784  *			command waitq.
11785  *
11786  * Return Code: 0 -  successful completion of the given command
11787  *		EIO - scsi_uscsi_handle_command() failed
11788  *		ENXIO  - soft state not found for specified dev
11789  *		ECANCELED - command cancelled due to low power
11790  *		EINVAL
11791  *		EFAULT - copyin/copyout error
11792  *		return code of scsi_uscsi_handle_command():
11793  *			EIO
11794  *			ENXIO
11795  *			EACCES
11796  *
11797  *     Context: Kernel Thread;
11798  *              Waits for command to complete. Can sleep.
11799  */
11800 static int
11801 sd_ssc_send(sd_ssc_t *ssc, struct uscsi_cmd *incmd, int flag,
11802     enum uio_seg dataspace, int path_flag)
11803 {
11804 	struct sd_uscsi_info	*uip;
11805 	struct uscsi_cmd	*uscmd;
11806 	struct sd_lun		*un;
11807 	dev_t			dev;
11808 
11809 	int	format = 0;
11810 	int	rval;
11811 
11812 	ASSERT(ssc != NULL);
11813 	un = ssc->ssc_un;
11814 	ASSERT(un != NULL);
11815 	uscmd = ssc->ssc_uscsi_cmd;
11816 	ASSERT(uscmd != NULL);
11817 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11818 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
11819 		/*
11820 		 * If enter here, it indicates that the previous uscsi
11821 		 * command has not been processed by sd_ssc_assessment.
11822 		 * This is violating our rules of FMA telemetry processing.
11823 		 * We should print out this message and the last undisposed
11824 		 * uscsi command.
11825 		 */
11826 		if (uscmd->uscsi_cdb != NULL) {
11827 			SD_INFO(SD_LOG_SDTEST, un,
11828 			    "sd_ssc_send is missing the alternative "
11829 			    "sd_ssc_assessment when running command 0x%x.\n",
11830 			    uscmd->uscsi_cdb[0]);
11831 		}
11832 		/*
11833 		 * Set the ssc_flags to SSC_FLAGS_UNKNOWN, which should be
11834 		 * the initial status.
11835 		 */
11836 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
11837 	}
11838 
11839 	/*
11840 	 * We need to make sure sd_ssc_send will have sd_ssc_assessment
11841 	 * followed to avoid missing FMA telemetries.
11842 	 */
11843 	ssc->ssc_flags |= SSC_FLAGS_NEED_ASSESSMENT;
11844 
11845 	/*
11846 	 * if USCSI_PMFAILFAST is set and un is in low power, fail the
11847 	 * command immediately.
11848 	 */
11849 	mutex_enter(SD_MUTEX(un));
11850 	mutex_enter(&un->un_pm_mutex);
11851 	if ((uscmd->uscsi_flags & USCSI_PMFAILFAST) &&
11852 	    SD_DEVICE_IS_IN_LOW_POWER(un)) {
11853 		SD_TRACE(SD_LOG_IO, un, "sd_ssc_send:"
11854 		    "un:0x%p is in low power\n", un);
11855 		mutex_exit(&un->un_pm_mutex);
11856 		mutex_exit(SD_MUTEX(un));
11857 		return (ECANCELED);
11858 	}
11859 	mutex_exit(&un->un_pm_mutex);
11860 	mutex_exit(SD_MUTEX(un));
11861 
11862 #ifdef SDDEBUG
11863 	switch (dataspace) {
11864 	case UIO_USERSPACE:
11865 		SD_TRACE(SD_LOG_IO, un,
11866 		    "sd_ssc_send: entry: un:0x%p UIO_USERSPACE\n", un);
11867 		break;
11868 	case UIO_SYSSPACE:
11869 		SD_TRACE(SD_LOG_IO, un,
11870 		    "sd_ssc_send: entry: un:0x%p UIO_SYSSPACE\n", un);
11871 		break;
11872 	default:
11873 		SD_TRACE(SD_LOG_IO, un,
11874 		    "sd_ssc_send: entry: un:0x%p UNEXPECTED SPACE\n", un);
11875 		break;
11876 	}
11877 #endif
11878 
11879 	rval = scsi_uscsi_copyin((intptr_t)incmd, flag,
11880 	    SD_ADDRESS(un), &uscmd);
11881 	if (rval != 0) {
11882 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
11883 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
11884 		return (rval);
11885 	}
11886 
11887 	if ((uscmd->uscsi_cdb != NULL) &&
11888 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
11889 		mutex_enter(SD_MUTEX(un));
11890 		un->un_f_format_in_progress = TRUE;
11891 		mutex_exit(SD_MUTEX(un));
11892 		format = 1;
11893 	}
11894 
11895 	/*
11896 	 * Allocate an sd_uscsi_info struct and fill it with the info
11897 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
11898 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
11899 	 * since we allocate the buf here in this function, we do not
11900 	 * need to preserve the prior contents of b_private.
11901 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
11902 	 */
11903 	uip = ssc->ssc_uscsi_info;
11904 	uip->ui_flags = path_flag;
11905 	uip->ui_cmdp = uscmd;
11906 
11907 	/*
11908 	 * Commands sent with priority are intended for error recovery
11909 	 * situations, and do not have retries performed.
11910 	 */
11911 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
11912 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
11913 	}
11914 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
11915 
11916 	dev = SD_GET_DEV(un);
11917 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
11918 	    sd_uscsi_strategy, NULL, uip);
11919 
11920 	/*
11921 	 * mark ssc_flags right after handle_cmd to make sure
11922 	 * the uscsi has been sent
11923 	 */
11924 	ssc->ssc_flags |= SSC_FLAGS_CMD_ISSUED;
11925 
11926 #ifdef SDDEBUG
11927 	SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
11928 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
11929 	    uscmd->uscsi_status, uscmd->uscsi_resid);
11930 	if (uscmd->uscsi_bufaddr != NULL) {
11931 		SD_INFO(SD_LOG_IO, un, "sd_ssc_send: "
11932 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
11933 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
11934 		if (dataspace == UIO_SYSSPACE) {
11935 			SD_DUMP_MEMORY(un, SD_LOG_IO,
11936 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
11937 			    uscmd->uscsi_buflen, SD_LOG_HEX);
11938 		}
11939 	}
11940 #endif
11941 
11942 	if (format == 1) {
11943 		mutex_enter(SD_MUTEX(un));
11944 		un->un_f_format_in_progress = FALSE;
11945 		mutex_exit(SD_MUTEX(un));
11946 	}
11947 
11948 	(void) scsi_uscsi_copyout((intptr_t)incmd, uscmd);
11949 
11950 	return (rval);
11951 }
11952 
11953 /*
11954  *     Function: sd_ssc_print
11955  *
11956  * Description: Print information available to the console.
11957  *
11958  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
11959  *                    sd_uscsi_info in.
11960  *            sd_severity - log level.
11961  *     Context: Kernel thread or interrupt context.
11962  */
11963 static void
11964 sd_ssc_print(sd_ssc_t *ssc, int sd_severity)
11965 {
11966 	struct uscsi_cmd	*ucmdp;
11967 	struct scsi_device	*devp;
11968 	dev_info_t		*devinfo;
11969 	uchar_t			*sensep;
11970 	int			senlen;
11971 	union scsi_cdb		*cdbp;
11972 	uchar_t			com;
11973 	extern struct scsi_key_strings scsi_cmds[];
11974 
11975 	ASSERT(ssc != NULL);
11976 	ASSERT(ssc->ssc_un != NULL);
11977 
11978 	if (SD_FM_LOG(ssc->ssc_un) != SD_FM_LOG_EREPORT)
11979 		return;
11980 	ucmdp = ssc->ssc_uscsi_cmd;
11981 	devp = SD_SCSI_DEVP(ssc->ssc_un);
11982 	devinfo = SD_DEVINFO(ssc->ssc_un);
11983 	ASSERT(ucmdp != NULL);
11984 	ASSERT(devp != NULL);
11985 	ASSERT(devinfo != NULL);
11986 	sensep = (uint8_t *)ucmdp->uscsi_rqbuf;
11987 	senlen = ucmdp->uscsi_rqlen - ucmdp->uscsi_rqresid;
11988 	cdbp = (union scsi_cdb *)ucmdp->uscsi_cdb;
11989 
11990 	/* In certain case (like DOORLOCK), the cdb could be NULL. */
11991 	if (cdbp == NULL)
11992 		return;
11993 	/* We don't print log if no sense data available. */
11994 	if (senlen == 0)
11995 		sensep = NULL;
11996 	com = cdbp->scc_cmd;
11997 	scsi_generic_errmsg(devp, sd_label, sd_severity, 0, 0, com,
11998 	    scsi_cmds, sensep, ssc->ssc_un->un_additional_codes, NULL);
11999 }
12000 
12001 /*
12002  *     Function: sd_ssc_assessment
12003  *
12004  * Description: We use this function to make an assessment at the point
12005  *              where SD driver may encounter a potential error.
12006  *
12007  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12008  *                  sd_uscsi_info in.
12009  *            tp_assess - a hint of strategy for ereport posting.
12010  *            Possible values of tp_assess include:
12011  *                SD_FMT_IGNORE - we don't post any ereport because we're
12012  *                sure that it is ok to ignore the underlying problems.
12013  *                SD_FMT_IGNORE_COMPROMISE - we don't post any ereport for now
12014  *                but it might be not correct to ignore the underlying hardware
12015  *                error.
12016  *                SD_FMT_STATUS_CHECK - we will post an ereport with the
12017  *                payload driver-assessment of value "fail" or
12018  *                "fatal"(depending on what information we have here). This
12019  *                assessment value is usually set when SD driver think there
12020  *                is a potential error occurred(Typically, when return value
12021  *                of the SCSI command is EIO).
12022  *                SD_FMT_STANDARD - we will post an ereport with the payload
12023  *                driver-assessment of value "info". This assessment value is
12024  *                set when the SCSI command returned successfully and with
12025  *                sense data sent back.
12026  *
12027  *     Context: Kernel thread.
12028  */
12029 static void
12030 sd_ssc_assessment(sd_ssc_t *ssc, enum sd_type_assessment tp_assess)
12031 {
12032 	int senlen = 0;
12033 	struct uscsi_cmd *ucmdp = NULL;
12034 	struct sd_lun *un;
12035 
12036 	ASSERT(ssc != NULL);
12037 	un = ssc->ssc_un;
12038 	ASSERT(un != NULL);
12039 	ucmdp = ssc->ssc_uscsi_cmd;
12040 	ASSERT(ucmdp != NULL);
12041 
12042 	if (ssc->ssc_flags & SSC_FLAGS_NEED_ASSESSMENT) {
12043 		ssc->ssc_flags &= ~SSC_FLAGS_NEED_ASSESSMENT;
12044 	} else {
12045 		/*
12046 		 * If enter here, it indicates that we have a wrong
12047 		 * calling sequence of sd_ssc_send and sd_ssc_assessment,
12048 		 * both of which should be called in a pair in case of
12049 		 * loss of FMA telemetries.
12050 		 */
12051 		if (ucmdp->uscsi_cdb != NULL) {
12052 			SD_INFO(SD_LOG_SDTEST, un,
12053 			    "sd_ssc_assessment is missing the "
12054 			    "alternative sd_ssc_send when running 0x%x, "
12055 			    "or there are superfluous sd_ssc_assessment for "
12056 			    "the same sd_ssc_send.\n",
12057 			    ucmdp->uscsi_cdb[0]);
12058 		}
12059 		/*
12060 		 * Set the ssc_flags to the initial value to avoid passing
12061 		 * down dirty flags to the following sd_ssc_send function.
12062 		 */
12063 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12064 		return;
12065 	}
12066 
12067 	/*
12068 	 * Only handle an issued command which is waiting for assessment.
12069 	 * A command which is not issued will not have
12070 	 * SSC_FLAGS_INVALID_DATA set, so it'ok we just return here.
12071 	 */
12072 	if (!(ssc->ssc_flags & SSC_FLAGS_CMD_ISSUED)) {
12073 		sd_ssc_print(ssc, SCSI_ERR_INFO);
12074 		return;
12075 	} else {
12076 		/*
12077 		 * For an issued command, we should clear this flag in
12078 		 * order to make the sd_ssc_t structure be used off
12079 		 * multiple uscsi commands.
12080 		 */
12081 		ssc->ssc_flags &= ~SSC_FLAGS_CMD_ISSUED;
12082 	}
12083 
12084 	/*
12085 	 * We will not deal with non-retryable(flag USCSI_DIAGNOSE set)
12086 	 * commands here. And we should clear the ssc_flags before return.
12087 	 */
12088 	if (ucmdp->uscsi_flags & USCSI_DIAGNOSE) {
12089 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12090 		return;
12091 	}
12092 
12093 	switch (tp_assess) {
12094 	case SD_FMT_IGNORE:
12095 	case SD_FMT_IGNORE_COMPROMISE:
12096 		break;
12097 	case SD_FMT_STATUS_CHECK:
12098 		/*
12099 		 * For a failed command(including the succeeded command
12100 		 * with invalid data sent back).
12101 		 */
12102 		sd_ssc_post(ssc, SD_FM_DRV_FATAL);
12103 		break;
12104 	case SD_FMT_STANDARD:
12105 		/*
12106 		 * Always for the succeeded commands probably with sense
12107 		 * data sent back.
12108 		 * Limitation:
12109 		 *	We can only handle a succeeded command with sense
12110 		 *	data sent back when auto-request-sense is enabled.
12111 		 */
12112 		senlen = ssc->ssc_uscsi_cmd->uscsi_rqlen -
12113 		    ssc->ssc_uscsi_cmd->uscsi_rqresid;
12114 		if ((ssc->ssc_uscsi_info->ui_pkt_state & STATE_ARQ_DONE) &&
12115 		    (un->un_f_arq_enabled == TRUE) &&
12116 		    senlen > 0 &&
12117 		    ssc->ssc_uscsi_cmd->uscsi_rqbuf != NULL) {
12118 			sd_ssc_post(ssc, SD_FM_DRV_NOTICE);
12119 		}
12120 		break;
12121 	default:
12122 		/*
12123 		 * Should not have other type of assessment.
12124 		 */
12125 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
12126 		    "sd_ssc_assessment got wrong "
12127 		    "sd_type_assessment %d.\n", tp_assess);
12128 		break;
12129 	}
12130 	/*
12131 	 * Clear up the ssc_flags before return.
12132 	 */
12133 	ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12134 }
12135 
12136 /*
12137  *    Function: sd_ssc_post
12138  *
12139  * Description: 1. read the driver property to get fm-scsi-log flag.
12140  *              2. print log if fm_log_capable is non-zero.
12141  *              3. call sd_ssc_ereport_post to post ereport if possible.
12142  *
12143  *    Context: May be called from kernel thread or interrupt context.
12144  */
12145 static void
12146 sd_ssc_post(sd_ssc_t *ssc, enum sd_driver_assessment sd_assess)
12147 {
12148 	struct sd_lun	*un;
12149 	int		sd_severity;
12150 
12151 	ASSERT(ssc != NULL);
12152 	un = ssc->ssc_un;
12153 	ASSERT(un != NULL);
12154 
12155 	/*
12156 	 * We may enter here from sd_ssc_assessment(for USCSI command) or
12157 	 * by directly called from sdintr context.
12158 	 * We don't handle a non-disk drive(CD-ROM, removable media).
12159 	 * Clear the ssc_flags before return in case we've set
12160 	 * SSC_FLAGS_INVALID_XXX which should be skipped for a non-disk
12161 	 * driver.
12162 	 */
12163 	if (ISCD(un) || un->un_f_has_removable_media) {
12164 		ssc->ssc_flags = SSC_FLAGS_UNKNOWN;
12165 		return;
12166 	}
12167 
12168 	switch (sd_assess) {
12169 		case SD_FM_DRV_FATAL:
12170 			sd_severity = SCSI_ERR_FATAL;
12171 			break;
12172 		case SD_FM_DRV_RECOVERY:
12173 			sd_severity = SCSI_ERR_RECOVERED;
12174 			break;
12175 		case SD_FM_DRV_RETRY:
12176 			sd_severity = SCSI_ERR_RETRYABLE;
12177 			break;
12178 		case SD_FM_DRV_NOTICE:
12179 			sd_severity = SCSI_ERR_INFO;
12180 			break;
12181 		default:
12182 			sd_severity = SCSI_ERR_UNKNOWN;
12183 	}
12184 	/* print log */
12185 	sd_ssc_print(ssc, sd_severity);
12186 
12187 	/* always post ereport */
12188 	sd_ssc_ereport_post(ssc, sd_assess);
12189 }
12190 
12191 /*
12192  *    Function: sd_ssc_set_info
12193  *
12194  * Description: Mark ssc_flags and set ssc_info which would be the
12195  *              payload of uderr ereport. This function will cause
12196  *              sd_ssc_ereport_post to post uderr ereport only.
12197  *              Besides, when ssc_flags == SSC_FLAGS_INVALID_DATA(USCSI),
12198  *              the function will also call SD_ERROR or scsi_log for a
12199  *              CDROM/removable-media/DDI_FM_NOT_CAPABLE device.
12200  *
12201  * Arguments: ssc - the struct of sd_ssc_t will bring uscsi_cmd and
12202  *                  sd_uscsi_info in.
12203  *            ssc_flags - indicate the sub-category of a uderr.
12204  *            comp - this argument is meaningful only when
12205  *                   ssc_flags == SSC_FLAGS_INVALID_DATA, and its possible
12206  *                   values include:
12207  *                   > 0, SD_ERROR is used with comp as the driver logging
12208  *                   component;
12209  *                   = 0, scsi-log is used to log error telemetries;
12210  *                   < 0, no log available for this telemetry.
12211  *
12212  *    Context: Kernel thread or interrupt context
12213  */
12214 static void
12215 sd_ssc_set_info(sd_ssc_t *ssc, int ssc_flags, uint_t comp, const char *fmt, ...)
12216 {
12217 	va_list	ap;
12218 
12219 	ASSERT(ssc != NULL);
12220 	ASSERT(ssc->ssc_un != NULL);
12221 
12222 	ssc->ssc_flags |= ssc_flags;
12223 	va_start(ap, fmt);
12224 	(void) vsnprintf(ssc->ssc_info, sizeof (ssc->ssc_info), fmt, ap);
12225 	va_end(ap);
12226 
12227 	/*
12228 	 * If SSC_FLAGS_INVALID_DATA is set, it should be a uscsi command
12229 	 * with invalid data sent back. For non-uscsi command, the
12230 	 * following code will be bypassed.
12231 	 */
12232 	if (ssc_flags & SSC_FLAGS_INVALID_DATA) {
12233 		if (SD_FM_LOG(ssc->ssc_un) == SD_FM_LOG_NSUP) {
12234 			/*
12235 			 * If the error belong to certain component and we
12236 			 * do not want it to show up on the console, we
12237 			 * will use SD_ERROR, otherwise scsi_log is
12238 			 * preferred.
12239 			 */
12240 			if (comp > 0) {
12241 				SD_ERROR(comp, ssc->ssc_un, ssc->ssc_info);
12242 			} else if (comp == 0) {
12243 				scsi_log(SD_DEVINFO(ssc->ssc_un), sd_label,
12244 				    CE_WARN, ssc->ssc_info);
12245 			}
12246 		}
12247 	}
12248 }
12249 
12250 /*
12251  *    Function: sd_buf_iodone
12252  *
12253  * Description: Frees the sd_xbuf & returns the buf to its originator.
12254  *
12255  *     Context: May be called from interrupt context.
12256  */
12257 /* ARGSUSED */
12258 static void
12259 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
12260 {
12261 	struct sd_xbuf *xp;
12262 
12263 	ASSERT(un != NULL);
12264 	ASSERT(bp != NULL);
12265 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12266 
12267 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
12268 
12269 	xp = SD_GET_XBUF(bp);
12270 	ASSERT(xp != NULL);
12271 
12272 	/* xbuf is gone after this */
12273 	if (ddi_xbuf_done(bp, un->un_xbuf_attr)) {
12274 		mutex_enter(SD_MUTEX(un));
12275 
12276 		/*
12277 		 * Grab time when the cmd completed.
12278 		 * This is used for determining if the system has been
12279 		 * idle long enough to make it idle to the PM framework.
12280 		 * This is for lowering the overhead, and therefore improving
12281 		 * performance per I/O operation.
12282 		 */
12283 		un->un_pm_idle_time = gethrtime();
12284 
12285 		un->un_ncmds_in_driver--;
12286 		ASSERT(un->un_ncmds_in_driver >= 0);
12287 		SD_INFO(SD_LOG_IO, un,
12288 		    "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
12289 		    un->un_ncmds_in_driver);
12290 
12291 		mutex_exit(SD_MUTEX(un));
12292 	}
12293 
12294 	biodone(bp);				/* bp is gone after this */
12295 
12296 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
12297 }
12298 
12299 
12300 /*
12301  *    Function: sd_uscsi_iodone
12302  *
12303  * Description: Frees the sd_xbuf & returns the buf to its originator.
12304  *
12305  *     Context: May be called from interrupt context.
12306  */
12307 /* ARGSUSED */
12308 static void
12309 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
12310 {
12311 	struct sd_xbuf *xp;
12312 
12313 	ASSERT(un != NULL);
12314 	ASSERT(bp != NULL);
12315 
12316 	xp = SD_GET_XBUF(bp);
12317 	ASSERT(xp != NULL);
12318 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12319 
12320 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
12321 
12322 	bp->b_private = xp->xb_private;
12323 
12324 	mutex_enter(SD_MUTEX(un));
12325 
12326 	/*
12327 	 * Grab time when the cmd completed.
12328 	 * This is used for determining if the system has been
12329 	 * idle long enough to make it idle to the PM framework.
12330 	 * This is for lowering the overhead, and therefore improving
12331 	 * performance per I/O operation.
12332 	 */
12333 	un->un_pm_idle_time = gethrtime();
12334 
12335 	un->un_ncmds_in_driver--;
12336 	ASSERT(un->un_ncmds_in_driver >= 0);
12337 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
12338 	    un->un_ncmds_in_driver);
12339 
12340 	mutex_exit(SD_MUTEX(un));
12341 
12342 	if (((struct uscsi_cmd *)(xp->xb_pktinfo))->uscsi_rqlen >
12343 	    SENSE_LENGTH) {
12344 		kmem_free(xp, sizeof (struct sd_xbuf) - SENSE_LENGTH +
12345 		    MAX_SENSE_LENGTH);
12346 	} else {
12347 		kmem_free(xp, sizeof (struct sd_xbuf));
12348 	}
12349 
12350 	biodone(bp);
12351 
12352 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
12353 }
12354 
12355 
12356 /*
12357  *    Function: sd_mapblockaddr_iostart
12358  *
12359  * Description: Verify request lies within the partition limits for
12360  *		the indicated minor device.  Issue "overrun" buf if
12361  *		request would exceed partition range.  Converts
12362  *		partition-relative block address to absolute.
12363  *
12364  *              Upon exit of this function:
12365  *              1.I/O is aligned
12366  *                 xp->xb_blkno represents the absolute sector address
12367  *              2.I/O is misaligned
12368  *                 xp->xb_blkno represents the absolute logical block address
12369  *                 based on DEV_BSIZE. The logical block address will be
12370  *                 converted to physical sector address in sd_mapblocksize_\
12371  *                 iostart.
12372  *              3.I/O is misaligned but is aligned in "overrun" buf
12373  *                 xp->xb_blkno represents the absolute logical block address
12374  *                 based on DEV_BSIZE. The logical block address will be
12375  *                 converted to physical sector address in sd_mapblocksize_\
12376  *                 iostart. But no RMW will be issued in this case.
12377  *
12378  *     Context: Can sleep
12379  *
12380  *      Issues: This follows what the old code did, in terms of accessing
12381  *		some of the partition info in the unit struct without holding
12382  *		the mutext.  This is a general issue, if the partition info
12383  *		can be altered while IO is in progress... as soon as we send
12384  *		a buf, its partitioning can be invalid before it gets to the
12385  *		device.  Probably the right fix is to move partitioning out
12386  *		of the driver entirely.
12387  */
12388 
12389 static void
12390 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
12391 {
12392 	diskaddr_t	nblocks;	/* #blocks in the given partition */
12393 	daddr_t	blocknum;	/* Block number specified by the buf */
12394 	size_t	requested_nblocks;
12395 	size_t	available_nblocks;
12396 	int	partition;
12397 	diskaddr_t	partition_offset;
12398 	struct sd_xbuf *xp;
12399 	int secmask = 0, blknomask = 0;
12400 	ushort_t is_aligned = TRUE;
12401 
12402 	ASSERT(un != NULL);
12403 	ASSERT(bp != NULL);
12404 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12405 
12406 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12407 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
12408 
12409 	xp = SD_GET_XBUF(bp);
12410 	ASSERT(xp != NULL);
12411 
12412 	/*
12413 	 * If the geometry is not indicated as valid, attempt to access
12414 	 * the unit & verify the geometry/label. This can be the case for
12415 	 * removable-media devices, of if the device was opened in
12416 	 * NDELAY/NONBLOCK mode.
12417 	 */
12418 	partition = SDPART(bp->b_edev);
12419 
12420 	if (!SD_IS_VALID_LABEL(un)) {
12421 		sd_ssc_t *ssc;
12422 		/*
12423 		 * Initialize sd_ssc_t for internal uscsi commands
12424 		 * In case of potential porformance issue, we need
12425 		 * to alloc memory only if there is invalid label
12426 		 */
12427 		ssc = sd_ssc_init(un);
12428 
12429 		if (sd_ready_and_valid(ssc, partition) != SD_READY_VALID) {
12430 			/*
12431 			 * For removable devices it is possible to start an
12432 			 * I/O without a media by opening the device in nodelay
12433 			 * mode. Also for writable CDs there can be many
12434 			 * scenarios where there is no geometry yet but volume
12435 			 * manager is trying to issue a read() just because
12436 			 * it can see TOC on the CD. So do not print a message
12437 			 * for removables.
12438 			 */
12439 			if (!un->un_f_has_removable_media) {
12440 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12441 				    "i/o to invalid geometry\n");
12442 			}
12443 			bioerror(bp, EIO);
12444 			bp->b_resid = bp->b_bcount;
12445 			SD_BEGIN_IODONE(index, un, bp);
12446 
12447 			sd_ssc_fini(ssc);
12448 			return;
12449 		}
12450 		sd_ssc_fini(ssc);
12451 	}
12452 
12453 	nblocks = 0;
12454 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
12455 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
12456 
12457 	if (un->un_f_enable_rmw) {
12458 		blknomask = (un->un_phy_blocksize / DEV_BSIZE) - 1;
12459 		secmask = un->un_phy_blocksize - 1;
12460 	} else {
12461 		blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
12462 		secmask = un->un_tgt_blocksize - 1;
12463 	}
12464 
12465 	if ((bp->b_lblkno & (blknomask)) || (bp->b_bcount & (secmask))) {
12466 		is_aligned = FALSE;
12467 	}
12468 
12469 	if (!(NOT_DEVBSIZE(un)) || un->un_f_enable_rmw) {
12470 		/*
12471 		 * If I/O is aligned, no need to involve RMW(Read Modify Write)
12472 		 * Convert the logical block number to target's physical sector
12473 		 * number.
12474 		 */
12475 		if (is_aligned) {
12476 			xp->xb_blkno = SD_SYS2TGTBLOCK(un, xp->xb_blkno);
12477 		} else {
12478 			/*
12479 			 * There is no RMW if we're just reading, so don't
12480 			 * warn or error out because of it.
12481 			 */
12482 			if (bp->b_flags & B_READ) {
12483 				/*EMPTY*/
12484 			} else if (!un->un_f_enable_rmw &&
12485 			    un->un_f_rmw_type == SD_RMW_TYPE_RETURN_ERROR) {
12486 				bp->b_flags |= B_ERROR;
12487 				goto error_exit;
12488 			} else if (un->un_f_rmw_type == SD_RMW_TYPE_DEFAULT) {
12489 				mutex_enter(SD_MUTEX(un));
12490 				if (!un->un_f_enable_rmw &&
12491 				    un->un_rmw_msg_timeid == NULL) {
12492 					scsi_log(SD_DEVINFO(un), sd_label,
12493 					    CE_WARN, "I/O request is not "
12494 					    "aligned with %d disk sector size. "
12495 					    "It is handled through Read Modify "
12496 					    "Write but the performance is "
12497 					    "very low.\n",
12498 					    un->un_tgt_blocksize);
12499 					un->un_rmw_msg_timeid =
12500 					    timeout(sd_rmw_msg_print_handler,
12501 					    un, SD_RMW_MSG_PRINT_TIMEOUT);
12502 				} else {
12503 					un->un_rmw_incre_count ++;
12504 				}
12505 				mutex_exit(SD_MUTEX(un));
12506 			}
12507 
12508 			nblocks = SD_TGT2SYSBLOCK(un, nblocks);
12509 			partition_offset = SD_TGT2SYSBLOCK(un,
12510 			    partition_offset);
12511 		}
12512 	}
12513 
12514 	/*
12515 	 * blocknum is the starting block number of the request. At this
12516 	 * point it is still relative to the start of the minor device.
12517 	 */
12518 	blocknum = xp->xb_blkno;
12519 
12520 	/*
12521 	 * Legacy: If the starting block number is one past the last block
12522 	 * in the partition, do not set B_ERROR in the buf.
12523 	 */
12524 	if (blocknum == nblocks)  {
12525 		goto error_exit;
12526 	}
12527 
12528 	/*
12529 	 * Confirm that the first block of the request lies within the
12530 	 * partition limits. Also the requested number of bytes must be
12531 	 * a multiple of the system block size.
12532 	 */
12533 	if ((blocknum < 0) || (blocknum >= nblocks) ||
12534 	    ((bp->b_bcount & (DEV_BSIZE - 1)) != 0)) {
12535 		bp->b_flags |= B_ERROR;
12536 		goto error_exit;
12537 	}
12538 
12539 	/*
12540 	 * If the requsted # blocks exceeds the available # blocks, that
12541 	 * is an overrun of the partition.
12542 	 */
12543 	if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12544 		requested_nblocks = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
12545 	} else {
12546 		requested_nblocks = SD_BYTES2SYSBLOCKS(bp->b_bcount);
12547 	}
12548 
12549 	available_nblocks = (size_t)(nblocks - blocknum);
12550 	ASSERT(nblocks >= blocknum);
12551 
12552 	if (requested_nblocks > available_nblocks) {
12553 		size_t resid;
12554 
12555 		/*
12556 		 * Allocate an "overrun" buf to allow the request to proceed
12557 		 * for the amount of space available in the partition. The
12558 		 * amount not transferred will be added into the b_resid
12559 		 * when the operation is complete. The overrun buf
12560 		 * replaces the original buf here, and the original buf
12561 		 * is saved inside the overrun buf, for later use.
12562 		 */
12563 		if ((!NOT_DEVBSIZE(un)) && is_aligned) {
12564 			resid = SD_TGTBLOCKS2BYTES(un,
12565 			    (offset_t)(requested_nblocks - available_nblocks));
12566 		} else {
12567 			resid = SD_SYSBLOCKS2BYTES(
12568 			    (offset_t)(requested_nblocks - available_nblocks));
12569 		}
12570 
12571 		size_t count = bp->b_bcount - resid;
12572 		/*
12573 		 * Note: count is an unsigned entity thus it'll NEVER
12574 		 * be less than 0 so ASSERT the original values are
12575 		 * correct.
12576 		 */
12577 		ASSERT(bp->b_bcount >= resid);
12578 
12579 		bp = sd_bioclone_alloc(bp, count, blocknum,
12580 		    (int (*)(struct buf *))(uintptr_t)sd_mapblockaddr_iodone);
12581 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
12582 		ASSERT(xp != NULL);
12583 	}
12584 
12585 	/* At this point there should be no residual for this buf. */
12586 	ASSERT(bp->b_resid == 0);
12587 
12588 	/* Convert the block number to an absolute address. */
12589 	xp->xb_blkno += partition_offset;
12590 
12591 	SD_NEXT_IOSTART(index, un, bp);
12592 
12593 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12594 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
12595 
12596 	return;
12597 
12598 error_exit:
12599 	bp->b_resid = bp->b_bcount;
12600 	SD_BEGIN_IODONE(index, un, bp);
12601 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12602 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
12603 }
12604 
12605 
12606 /*
12607  *    Function: sd_mapblockaddr_iodone
12608  *
12609  * Description: Completion-side processing for partition management.
12610  *
12611  *     Context: May be called under interrupt context
12612  */
12613 
12614 static void
12615 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
12616 {
12617 	/* int	partition; */	/* Not used, see below. */
12618 	ASSERT(un != NULL);
12619 	ASSERT(bp != NULL);
12620 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12621 
12622 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12623 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
12624 
12625 	if ((uintptr_t)bp->b_iodone == (uintptr_t)sd_mapblockaddr_iodone) {
12626 		/*
12627 		 * We have an "overrun" buf to deal with...
12628 		 */
12629 		struct sd_xbuf	*xp;
12630 		struct buf	*obp;	/* ptr to the original buf */
12631 
12632 		xp = SD_GET_XBUF(bp);
12633 		ASSERT(xp != NULL);
12634 
12635 		/* Retrieve the pointer to the original buf */
12636 		obp = (struct buf *)xp->xb_private;
12637 		ASSERT(obp != NULL);
12638 
12639 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
12640 		bioerror(obp, bp->b_error);
12641 
12642 		sd_bioclone_free(bp);
12643 
12644 		/*
12645 		 * Get back the original buf.
12646 		 * Note that since the restoration of xb_blkno below
12647 		 * was removed, the sd_xbuf is not needed.
12648 		 */
12649 		bp = obp;
12650 		/*
12651 		 * xp = SD_GET_XBUF(bp);
12652 		 * ASSERT(xp != NULL);
12653 		 */
12654 	}
12655 
12656 	/*
12657 	 * Convert sd->xb_blkno back to a minor-device relative value.
12658 	 * Note: this has been commented out, as it is not needed in the
12659 	 * current implementation of the driver (ie, since this function
12660 	 * is at the top of the layering chains, so the info will be
12661 	 * discarded) and it is in the "hot" IO path.
12662 	 *
12663 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
12664 	 * xp->xb_blkno -= un->un_offset[partition];
12665 	 */
12666 
12667 	SD_NEXT_IODONE(index, un, bp);
12668 
12669 	SD_TRACE(SD_LOG_IO_PARTITION, un,
12670 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
12671 }
12672 
12673 
12674 /*
12675  *    Function: sd_mapblocksize_iostart
12676  *
12677  * Description: Convert between system block size (un->un_sys_blocksize)
12678  *		and target block size (un->un_tgt_blocksize).
12679  *
12680  *     Context: Can sleep to allocate resources.
12681  *
12682  * Assumptions: A higher layer has already performed any partition validation,
12683  *		and converted the xp->xb_blkno to an absolute value relative
12684  *		to the start of the device.
12685  *
12686  *		It is also assumed that the higher layer has implemented
12687  *		an "overrun" mechanism for the case where the request would
12688  *		read/write beyond the end of a partition.  In this case we
12689  *		assume (and ASSERT) that bp->b_resid == 0.
12690  *
12691  *		Note: The implementation for this routine assumes the target
12692  *		block size remains constant between allocation and transport.
12693  */
12694 
12695 static void
12696 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
12697 {
12698 	struct sd_mapblocksize_info	*bsp;
12699 	struct sd_xbuf			*xp;
12700 	offset_t first_byte;
12701 	daddr_t	start_block, end_block;
12702 	daddr_t	request_bytes;
12703 	ushort_t is_aligned = FALSE;
12704 
12705 	ASSERT(un != NULL);
12706 	ASSERT(bp != NULL);
12707 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12708 	ASSERT(bp->b_resid == 0);
12709 
12710 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12711 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
12712 
12713 	/*
12714 	 * For a non-writable CD, a write request is an error
12715 	 */
12716 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
12717 	    (un->un_f_mmc_writable_media == FALSE)) {
12718 		bioerror(bp, EIO);
12719 		bp->b_resid = bp->b_bcount;
12720 		SD_BEGIN_IODONE(index, un, bp);
12721 		return;
12722 	}
12723 
12724 	/*
12725 	 * We do not need a shadow buf if the device is using
12726 	 * un->un_sys_blocksize as its block size or if bcount == 0.
12727 	 * In this case there is no layer-private data block allocated.
12728 	 */
12729 	if ((un->un_tgt_blocksize == DEV_BSIZE && !un->un_f_enable_rmw) ||
12730 	    (bp->b_bcount == 0)) {
12731 		goto done;
12732 	}
12733 
12734 #if defined(__x86)
12735 	/* We do not support non-block-aligned transfers for ROD devices */
12736 	ASSERT(!ISROD(un));
12737 #endif
12738 
12739 	xp = SD_GET_XBUF(bp);
12740 	ASSERT(xp != NULL);
12741 
12742 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12743 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
12744 	    un->un_tgt_blocksize, DEV_BSIZE);
12745 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12746 	    "request start block:0x%x\n", xp->xb_blkno);
12747 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
12748 	    "request len:0x%x\n", bp->b_bcount);
12749 
12750 	/*
12751 	 * Allocate the layer-private data area for the mapblocksize layer.
12752 	 * Layers are allowed to use the xp_private member of the sd_xbuf
12753 	 * struct to store the pointer to their layer-private data block, but
12754 	 * each layer also has the responsibility of restoring the prior
12755 	 * contents of xb_private before returning the buf/xbuf to the
12756 	 * higher layer that sent it.
12757 	 *
12758 	 * Here we save the prior contents of xp->xb_private into the
12759 	 * bsp->mbs_oprivate field of our layer-private data area. This value
12760 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
12761 	 * the layer-private area and returning the buf/xbuf to the layer
12762 	 * that sent it.
12763 	 *
12764 	 * Note that here we use kmem_zalloc for the allocation as there are
12765 	 * parts of the mapblocksize code that expect certain fields to be
12766 	 * zero unless explicitly set to a required value.
12767 	 */
12768 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12769 	bsp->mbs_oprivate = xp->xb_private;
12770 	xp->xb_private = bsp;
12771 
12772 	/*
12773 	 * This treats the data on the disk (target) as an array of bytes.
12774 	 * first_byte is the byte offset, from the beginning of the device,
12775 	 * to the location of the request. This is converted from a
12776 	 * un->un_sys_blocksize block address to a byte offset, and then back
12777 	 * to a block address based upon a un->un_tgt_blocksize block size.
12778 	 *
12779 	 * xp->xb_blkno should be absolute upon entry into this function,
12780 	 * but, but it is based upon partitions that use the "system"
12781 	 * block size. It must be adjusted to reflect the block size of
12782 	 * the target.
12783 	 *
12784 	 * Note that end_block is actually the block that follows the last
12785 	 * block of the request, but that's what is needed for the computation.
12786 	 */
12787 	first_byte  = SD_SYSBLOCKS2BYTES((offset_t)xp->xb_blkno);
12788 	if (un->un_f_enable_rmw) {
12789 		start_block = xp->xb_blkno =
12790 		    (first_byte / un->un_phy_blocksize) *
12791 		    (un->un_phy_blocksize / DEV_BSIZE);
12792 		end_block   = ((first_byte + bp->b_bcount +
12793 		    un->un_phy_blocksize - 1) / un->un_phy_blocksize) *
12794 		    (un->un_phy_blocksize / DEV_BSIZE);
12795 	} else {
12796 		start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
12797 		end_block   = (first_byte + bp->b_bcount +
12798 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
12799 	}
12800 
12801 	/* request_bytes is rounded up to a multiple of the target block size */
12802 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
12803 
12804 	/*
12805 	 * See if the starting address of the request and the request
12806 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
12807 	 * then we do not need to allocate a shadow buf to handle the request.
12808 	 */
12809 	if (un->un_f_enable_rmw) {
12810 		if (((first_byte % un->un_phy_blocksize) == 0) &&
12811 		    ((bp->b_bcount % un->un_phy_blocksize) == 0)) {
12812 			is_aligned = TRUE;
12813 		}
12814 	} else {
12815 		if (((first_byte % un->un_tgt_blocksize) == 0) &&
12816 		    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
12817 			is_aligned = TRUE;
12818 		}
12819 	}
12820 
12821 	if ((bp->b_flags & B_READ) == 0) {
12822 		/*
12823 		 * Lock the range for a write operation. An aligned request is
12824 		 * considered a simple write; otherwise the request must be a
12825 		 * read-modify-write.
12826 		 */
12827 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
12828 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
12829 	}
12830 
12831 	/*
12832 	 * Alloc a shadow buf if the request is not aligned. Also, this is
12833 	 * where the READ command is generated for a read-modify-write. (The
12834 	 * write phase is deferred until after the read completes.)
12835 	 */
12836 	if (is_aligned == FALSE) {
12837 
12838 		struct sd_mapblocksize_info	*shadow_bsp;
12839 		struct sd_xbuf	*shadow_xp;
12840 		struct buf	*shadow_bp;
12841 
12842 		/*
12843 		 * Allocate the shadow buf and it associated xbuf. Note that
12844 		 * after this call the xb_blkno value in both the original
12845 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
12846 		 * same: absolute relative to the start of the device, and
12847 		 * adjusted for the target block size. The b_blkno in the
12848 		 * shadow buf will also be set to this value. We should never
12849 		 * change b_blkno in the original bp however.
12850 		 *
12851 		 * Note also that the shadow buf will always need to be a
12852 		 * READ command, regardless of whether the incoming command
12853 		 * is a READ or a WRITE.
12854 		 */
12855 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
12856 		    xp->xb_blkno,
12857 		    (int (*)(struct buf *))(uintptr_t)sd_mapblocksize_iodone);
12858 
12859 		shadow_xp = SD_GET_XBUF(shadow_bp);
12860 
12861 		/*
12862 		 * Allocate the layer-private data for the shadow buf.
12863 		 * (No need to preserve xb_private in the shadow xbuf.)
12864 		 */
12865 		shadow_xp->xb_private = shadow_bsp =
12866 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
12867 
12868 		/*
12869 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
12870 		 * to figure out where the start of the user data is (based upon
12871 		 * the system block size) in the data returned by the READ
12872 		 * command (which will be based upon the target blocksize). Note
12873 		 * that this is only really used if the request is unaligned.
12874 		 */
12875 		if (un->un_f_enable_rmw) {
12876 			bsp->mbs_copy_offset = (ssize_t)(first_byte -
12877 			    ((offset_t)xp->xb_blkno * un->un_sys_blocksize));
12878 			ASSERT((bsp->mbs_copy_offset >= 0) &&
12879 			    (bsp->mbs_copy_offset < un->un_phy_blocksize));
12880 		} else {
12881 			bsp->mbs_copy_offset = (ssize_t)(first_byte -
12882 			    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
12883 			ASSERT((bsp->mbs_copy_offset >= 0) &&
12884 			    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
12885 		}
12886 
12887 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
12888 
12889 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
12890 
12891 		/* Transfer the wmap (if any) to the shadow buf */
12892 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
12893 		bsp->mbs_wmp = NULL;
12894 
12895 		/*
12896 		 * The shadow buf goes on from here in place of the
12897 		 * original buf.
12898 		 */
12899 		shadow_bsp->mbs_orig_bp = bp;
12900 		bp = shadow_bp;
12901 	}
12902 
12903 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12904 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
12905 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12906 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
12907 	    request_bytes);
12908 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
12909 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
12910 
12911 done:
12912 	SD_NEXT_IOSTART(index, un, bp);
12913 
12914 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12915 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
12916 }
12917 
12918 
12919 /*
12920  *    Function: sd_mapblocksize_iodone
12921  *
12922  * Description: Completion side processing for block-size mapping.
12923  *
12924  *     Context: May be called under interrupt context
12925  */
12926 
12927 static void
12928 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
12929 {
12930 	struct sd_mapblocksize_info	*bsp;
12931 	struct sd_xbuf	*xp;
12932 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
12933 	struct buf	*orig_bp;	/* ptr to the original buf */
12934 	offset_t	shadow_end;
12935 	offset_t	request_end;
12936 	offset_t	shadow_start;
12937 	ssize_t		copy_offset;
12938 	size_t		copy_length;
12939 	size_t		shortfall;
12940 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
12941 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
12942 
12943 	ASSERT(un != NULL);
12944 	ASSERT(bp != NULL);
12945 
12946 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
12947 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
12948 
12949 	/*
12950 	 * There is no shadow buf or layer-private data if the target is
12951 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
12952 	 */
12953 	if ((un->un_tgt_blocksize == DEV_BSIZE && !un->un_f_enable_rmw) ||
12954 	    (bp->b_bcount == 0)) {
12955 		goto exit;
12956 	}
12957 
12958 	xp = SD_GET_XBUF(bp);
12959 	ASSERT(xp != NULL);
12960 
12961 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
12962 	bsp = xp->xb_private;
12963 
12964 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
12965 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
12966 
12967 	if (is_write) {
12968 		/*
12969 		 * For a WRITE request we must free up the block range that
12970 		 * we have locked up.  This holds regardless of whether this is
12971 		 * an aligned write request or a read-modify-write request.
12972 		 */
12973 		sd_range_unlock(un, bsp->mbs_wmp);
12974 		bsp->mbs_wmp = NULL;
12975 	}
12976 
12977 	if ((uintptr_t)bp->b_iodone != (uintptr_t)sd_mapblocksize_iodone) {
12978 		/*
12979 		 * An aligned read or write command will have no shadow buf;
12980 		 * there is not much else to do with it.
12981 		 */
12982 		goto done;
12983 	}
12984 
12985 	orig_bp = bsp->mbs_orig_bp;
12986 	ASSERT(orig_bp != NULL);
12987 	orig_xp = SD_GET_XBUF(orig_bp);
12988 	ASSERT(orig_xp != NULL);
12989 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12990 
12991 	if (!is_write && has_wmap) {
12992 		/*
12993 		 * A READ with a wmap means this is the READ phase of a
12994 		 * read-modify-write. If an error occurred on the READ then
12995 		 * we do not proceed with the WRITE phase or copy any data.
12996 		 * Just release the write maps and return with an error.
12997 		 */
12998 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
12999 			orig_bp->b_resid = orig_bp->b_bcount;
13000 			bioerror(orig_bp, bp->b_error);
13001 			sd_range_unlock(un, bsp->mbs_wmp);
13002 			goto freebuf_done;
13003 		}
13004 	}
13005 
13006 	/*
13007 	 * Here is where we set up to copy the data from the shadow buf
13008 	 * into the space associated with the original buf.
13009 	 *
13010 	 * To deal with the conversion between block sizes, these
13011 	 * computations treat the data as an array of bytes, with the
13012 	 * first byte (byte 0) corresponding to the first byte in the
13013 	 * first block on the disk.
13014 	 */
13015 
13016 	/*
13017 	 * shadow_start and shadow_len indicate the location and size of
13018 	 * the data returned with the shadow IO request.
13019 	 */
13020 	if (un->un_f_enable_rmw) {
13021 		shadow_start  = SD_SYSBLOCKS2BYTES((offset_t)xp->xb_blkno);
13022 	} else {
13023 		shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
13024 	}
13025 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
13026 
13027 	/*
13028 	 * copy_offset gives the offset (in bytes) from the start of the first
13029 	 * block of the READ request to the beginning of the data.  We retrieve
13030 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
13031 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
13032 	 * data to be copied (in bytes).
13033 	 */
13034 	copy_offset  = bsp->mbs_copy_offset;
13035 	if (un->un_f_enable_rmw) {
13036 		ASSERT((copy_offset >= 0) &&
13037 		    (copy_offset < un->un_phy_blocksize));
13038 	} else {
13039 		ASSERT((copy_offset >= 0) &&
13040 		    (copy_offset < un->un_tgt_blocksize));
13041 	}
13042 
13043 	copy_length  = orig_bp->b_bcount;
13044 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
13045 
13046 	/*
13047 	 * Set up the resid and error fields of orig_bp as appropriate.
13048 	 */
13049 	if (shadow_end >= request_end) {
13050 		/* We got all the requested data; set resid to zero */
13051 		orig_bp->b_resid = 0;
13052 	} else {
13053 		/*
13054 		 * We failed to get enough data to fully satisfy the original
13055 		 * request. Just copy back whatever data we got and set
13056 		 * up the residual and error code as required.
13057 		 *
13058 		 * 'shortfall' is the amount by which the data received with the
13059 		 * shadow buf has "fallen short" of the requested amount.
13060 		 */
13061 		shortfall = (size_t)(request_end - shadow_end);
13062 
13063 		if (shortfall > orig_bp->b_bcount) {
13064 			/*
13065 			 * We did not get enough data to even partially
13066 			 * fulfill the original request.  The residual is
13067 			 * equal to the amount requested.
13068 			 */
13069 			orig_bp->b_resid = orig_bp->b_bcount;
13070 		} else {
13071 			/*
13072 			 * We did not get all the data that we requested
13073 			 * from the device, but we will try to return what
13074 			 * portion we did get.
13075 			 */
13076 			orig_bp->b_resid = shortfall;
13077 		}
13078 		ASSERT(copy_length >= orig_bp->b_resid);
13079 		copy_length  -= orig_bp->b_resid;
13080 	}
13081 
13082 	/* Propagate the error code from the shadow buf to the original buf */
13083 	bioerror(orig_bp, bp->b_error);
13084 
13085 	if (is_write) {
13086 		goto freebuf_done;	/* No data copying for a WRITE */
13087 	}
13088 
13089 	if (has_wmap) {
13090 		/*
13091 		 * This is a READ command from the READ phase of a
13092 		 * read-modify-write request. We have to copy the data given
13093 		 * by the user OVER the data returned by the READ command,
13094 		 * then convert the command from a READ to a WRITE and send
13095 		 * it back to the target.
13096 		 */
13097 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
13098 		    copy_length);
13099 
13100 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
13101 
13102 		/*
13103 		 * Dispatch the WRITE command to the taskq thread, which
13104 		 * will in turn send the command to the target. When the
13105 		 * WRITE command completes, we (sd_mapblocksize_iodone())
13106 		 * will get called again as part of the iodone chain
13107 		 * processing for it. Note that we will still be dealing
13108 		 * with the shadow buf at that point.
13109 		 */
13110 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
13111 		    KM_NOSLEEP) != TASKQID_INVALID) {
13112 			/*
13113 			 * Dispatch was successful so we are done. Return
13114 			 * without going any higher up the iodone chain. Do
13115 			 * not free up any layer-private data until after the
13116 			 * WRITE completes.
13117 			 */
13118 			return;
13119 		}
13120 
13121 		/*
13122 		 * Dispatch of the WRITE command failed; set up the error
13123 		 * condition and send this IO back up the iodone chain.
13124 		 */
13125 		bioerror(orig_bp, EIO);
13126 		orig_bp->b_resid = orig_bp->b_bcount;
13127 
13128 	} else {
13129 		/*
13130 		 * This is a regular READ request (ie, not a RMW). Copy the
13131 		 * data from the shadow buf into the original buf. The
13132 		 * copy_offset compensates for any "misalignment" between the
13133 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
13134 		 * original buf (with its un->un_sys_blocksize blocks).
13135 		 */
13136 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
13137 		    copy_length);
13138 	}
13139 
13140 freebuf_done:
13141 
13142 	/*
13143 	 * At this point we still have both the shadow buf AND the original
13144 	 * buf to deal with, as well as the layer-private data area in each.
13145 	 * Local variables are as follows:
13146 	 *
13147 	 * bp -- points to shadow buf
13148 	 * xp -- points to xbuf of shadow buf
13149 	 * bsp -- points to layer-private data area of shadow buf
13150 	 * orig_bp -- points to original buf
13151 	 *
13152 	 * First free the shadow buf and its associated xbuf, then free the
13153 	 * layer-private data area from the shadow buf. There is no need to
13154 	 * restore xb_private in the shadow xbuf.
13155 	 */
13156 	sd_shadow_buf_free(bp);
13157 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13158 
13159 	/*
13160 	 * Now update the local variables to point to the original buf, xbuf,
13161 	 * and layer-private area.
13162 	 */
13163 	bp = orig_bp;
13164 	xp = SD_GET_XBUF(bp);
13165 	ASSERT(xp != NULL);
13166 	ASSERT(xp == orig_xp);
13167 	bsp = xp->xb_private;
13168 	ASSERT(bsp != NULL);
13169 
13170 done:
13171 	/*
13172 	 * Restore xb_private to whatever it was set to by the next higher
13173 	 * layer in the chain, then free the layer-private data area.
13174 	 */
13175 	xp->xb_private = bsp->mbs_oprivate;
13176 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
13177 
13178 exit:
13179 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
13180 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
13181 
13182 	SD_NEXT_IODONE(index, un, bp);
13183 }
13184 
13185 
13186 /*
13187  *    Function: sd_checksum_iostart
13188  *
13189  * Description: A stub function for a layer that's currently not used.
13190  *		For now just a placeholder.
13191  *
13192  *     Context: Kernel thread context
13193  */
13194 
13195 static void
13196 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
13197 {
13198 	ASSERT(un != NULL);
13199 	ASSERT(bp != NULL);
13200 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13201 	SD_NEXT_IOSTART(index, un, bp);
13202 }
13203 
13204 
13205 /*
13206  *    Function: sd_checksum_iodone
13207  *
13208  * Description: A stub function for a layer that's currently not used.
13209  *		For now just a placeholder.
13210  *
13211  *     Context: May be called under interrupt context
13212  */
13213 
13214 static void
13215 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
13216 {
13217 	ASSERT(un != NULL);
13218 	ASSERT(bp != NULL);
13219 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13220 	SD_NEXT_IODONE(index, un, bp);
13221 }
13222 
13223 
13224 /*
13225  *    Function: sd_checksum_uscsi_iostart
13226  *
13227  * Description: A stub function for a layer that's currently not used.
13228  *		For now just a placeholder.
13229  *
13230  *     Context: Kernel thread context
13231  */
13232 
13233 static void
13234 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
13235 {
13236 	ASSERT(un != NULL);
13237 	ASSERT(bp != NULL);
13238 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13239 	SD_NEXT_IOSTART(index, un, bp);
13240 }
13241 
13242 
13243 /*
13244  *    Function: sd_checksum_uscsi_iodone
13245  *
13246  * Description: A stub function for a layer that's currently not used.
13247  *		For now just a placeholder.
13248  *
13249  *     Context: May be called under interrupt context
13250  */
13251 
13252 static void
13253 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
13254 {
13255 	ASSERT(un != NULL);
13256 	ASSERT(bp != NULL);
13257 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13258 	SD_NEXT_IODONE(index, un, bp);
13259 }
13260 
13261 
13262 /*
13263  *    Function: sd_pm_iostart
13264  *
13265  * Description: iostart-side routine for Power mangement.
13266  *
13267  *     Context: Kernel thread context
13268  */
13269 
13270 static void
13271 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
13272 {
13273 	ASSERT(un != NULL);
13274 	ASSERT(bp != NULL);
13275 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13276 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13277 
13278 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
13279 
13280 	if (sd_pm_entry(un) != DDI_SUCCESS) {
13281 		/*
13282 		 * Set up to return the failed buf back up the 'iodone'
13283 		 * side of the calling chain.
13284 		 */
13285 		bioerror(bp, EIO);
13286 		bp->b_resid = bp->b_bcount;
13287 
13288 		SD_BEGIN_IODONE(index, un, bp);
13289 
13290 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13291 		return;
13292 	}
13293 
13294 	SD_NEXT_IOSTART(index, un, bp);
13295 
13296 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
13297 }
13298 
13299 
13300 /*
13301  *    Function: sd_pm_iodone
13302  *
13303  * Description: iodone-side routine for power mangement.
13304  *
13305  *     Context: may be called from interrupt context
13306  */
13307 
13308 static void
13309 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
13310 {
13311 	ASSERT(un != NULL);
13312 	ASSERT(bp != NULL);
13313 	ASSERT(!mutex_owned(&un->un_pm_mutex));
13314 
13315 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
13316 
13317 	/*
13318 	 * After attach the following flag is only read, so don't
13319 	 * take the penalty of acquiring a mutex for it.
13320 	 */
13321 	if (un->un_f_pm_is_enabled == TRUE) {
13322 		sd_pm_exit(un);
13323 	}
13324 
13325 	SD_NEXT_IODONE(index, un, bp);
13326 
13327 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
13328 }
13329 
13330 
13331 /*
13332  *    Function: sd_core_iostart
13333  *
13334  * Description: Primary driver function for enqueuing buf(9S) structs from
13335  *		the system and initiating IO to the target device
13336  *
13337  *     Context: Kernel thread context. Can sleep.
13338  *
13339  * Assumptions:  - The given xp->xb_blkno is absolute
13340  *		   (ie, relative to the start of the device).
13341  *		 - The IO is to be done using the native blocksize of
13342  *		   the device, as specified in un->un_tgt_blocksize.
13343  */
13344 /* ARGSUSED */
13345 static void
13346 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
13347 {
13348 	struct sd_xbuf *xp;
13349 
13350 	ASSERT(un != NULL);
13351 	ASSERT(bp != NULL);
13352 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13353 	ASSERT(bp->b_resid == 0);
13354 
13355 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
13356 
13357 	xp = SD_GET_XBUF(bp);
13358 	ASSERT(xp != NULL);
13359 
13360 	mutex_enter(SD_MUTEX(un));
13361 
13362 	/*
13363 	 * If we are currently in the failfast state, fail any new IO
13364 	 * that has B_FAILFAST set, then return.
13365 	 */
13366 	if ((bp->b_flags & B_FAILFAST) &&
13367 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
13368 		mutex_exit(SD_MUTEX(un));
13369 		bioerror(bp, EIO);
13370 		bp->b_resid = bp->b_bcount;
13371 		SD_BEGIN_IODONE(index, un, bp);
13372 		return;
13373 	}
13374 
13375 	if (SD_IS_DIRECT_PRIORITY(xp)) {
13376 		/*
13377 		 * Priority command -- transport it immediately.
13378 		 *
13379 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
13380 		 * because all direct priority commands should be associated
13381 		 * with error recovery actions which we don't want to retry.
13382 		 */
13383 		sd_start_cmds(un, bp);
13384 	} else {
13385 		/*
13386 		 * Normal command -- add it to the wait queue, then start
13387 		 * transporting commands from the wait queue.
13388 		 */
13389 		sd_add_buf_to_waitq(un, bp);
13390 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13391 		sd_start_cmds(un, NULL);
13392 	}
13393 
13394 	mutex_exit(SD_MUTEX(un));
13395 
13396 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
13397 }
13398 
13399 
13400 /*
13401  *    Function: sd_init_cdb_limits
13402  *
13403  * Description: This is to handle scsi_pkt initialization differences
13404  *		between the driver platforms.
13405  *
13406  *		Legacy behaviors:
13407  *
13408  *		If the block number or the sector count exceeds the
13409  *		capabilities of a Group 0 command, shift over to a
13410  *		Group 1 command. We don't blindly use Group 1
13411  *		commands because a) some drives (CDC Wren IVs) get a
13412  *		bit confused, and b) there is probably a fair amount
13413  *		of speed difference for a target to receive and decode
13414  *		a 10 byte command instead of a 6 byte command.
13415  *
13416  *		The xfer time difference of 6 vs 10 byte CDBs is
13417  *		still significant so this code is still worthwhile.
13418  *		10 byte CDBs are very inefficient with the fas HBA driver
13419  *		and older disks. Each CDB byte took 1 usec with some
13420  *		popular disks.
13421  *
13422  *     Context: Must be called at attach time
13423  */
13424 
13425 static void
13426 sd_init_cdb_limits(struct sd_lun *un)
13427 {
13428 	int hba_cdb_limit;
13429 
13430 	/*
13431 	 * Use CDB_GROUP1 commands for most devices except for
13432 	 * parallel SCSI fixed drives in which case we get better
13433 	 * performance using CDB_GROUP0 commands (where applicable).
13434 	 */
13435 	un->un_mincdb = SD_CDB_GROUP1;
13436 #if !defined(__fibre)
13437 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
13438 	    !un->un_f_has_removable_media) {
13439 		un->un_mincdb = SD_CDB_GROUP0;
13440 	}
13441 #endif
13442 
13443 	/*
13444 	 * Try to read the max-cdb-length supported by HBA.
13445 	 */
13446 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
13447 	if (0 >= un->un_max_hba_cdb) {
13448 		un->un_max_hba_cdb = CDB_GROUP4;
13449 		hba_cdb_limit = SD_CDB_GROUP4;
13450 	} else if (0 < un->un_max_hba_cdb &&
13451 	    un->un_max_hba_cdb < CDB_GROUP1) {
13452 		hba_cdb_limit = SD_CDB_GROUP0;
13453 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
13454 	    un->un_max_hba_cdb < CDB_GROUP5) {
13455 		hba_cdb_limit = SD_CDB_GROUP1;
13456 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
13457 	    un->un_max_hba_cdb < CDB_GROUP4) {
13458 		hba_cdb_limit = SD_CDB_GROUP5;
13459 	} else {
13460 		hba_cdb_limit = SD_CDB_GROUP4;
13461 	}
13462 
13463 	/*
13464 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
13465 	 * commands for fixed disks unless we are building for a 32 bit
13466 	 * kernel.
13467 	 */
13468 #ifdef _LP64
13469 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13470 	    min(hba_cdb_limit, SD_CDB_GROUP4);
13471 #else
13472 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
13473 	    min(hba_cdb_limit, SD_CDB_GROUP1);
13474 #endif
13475 
13476 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
13477 	    ? sizeof (struct scsi_arq_status) : 1);
13478 	if (!ISCD(un))
13479 		un->un_cmd_timeout = (ushort_t)sd_io_time;
13480 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
13481 }
13482 
13483 
13484 /*
13485  *    Function: sd_initpkt_for_buf
13486  *
13487  * Description: Allocate and initialize for transport a scsi_pkt struct,
13488  *		based upon the info specified in the given buf struct.
13489  *
13490  *		Assumes the xb_blkno in the request is absolute (ie,
13491  *		relative to the start of the device (NOT partition!).
13492  *		Also assumes that the request is using the native block
13493  *		size of the device (as returned by the READ CAPACITY
13494  *		command).
13495  *
13496  * Return Code: SD_PKT_ALLOC_SUCCESS
13497  *		SD_PKT_ALLOC_FAILURE
13498  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13499  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13500  *
13501  *     Context: Kernel thread and may be called from software interrupt context
13502  *		as part of a sdrunout callback. This function may not block or
13503  *		call routines that block
13504  */
13505 
13506 static int
13507 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
13508 {
13509 	struct sd_xbuf	*xp;
13510 	struct scsi_pkt *pktp = NULL;
13511 	struct sd_lun	*un;
13512 	size_t		blockcount;
13513 	daddr_t		startblock;
13514 	int		rval;
13515 	int		cmd_flags;
13516 
13517 	ASSERT(bp != NULL);
13518 	ASSERT(pktpp != NULL);
13519 	xp = SD_GET_XBUF(bp);
13520 	ASSERT(xp != NULL);
13521 	un = SD_GET_UN(bp);
13522 	ASSERT(un != NULL);
13523 	ASSERT(mutex_owned(SD_MUTEX(un)));
13524 	ASSERT(bp->b_resid == 0);
13525 
13526 	SD_TRACE(SD_LOG_IO_CORE, un,
13527 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
13528 
13529 	mutex_exit(SD_MUTEX(un));
13530 
13531 #if defined(__x86)	/* DMAFREE for x86 only */
13532 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
13533 		/*
13534 		 * Already have a scsi_pkt -- just need DMA resources.
13535 		 * We must recompute the CDB in case the mapping returns
13536 		 * a nonzero pkt_resid.
13537 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
13538 		 * that is being retried, the unmap/remap of the DMA resouces
13539 		 * will result in the entire transfer starting over again
13540 		 * from the very first block.
13541 		 */
13542 		ASSERT(xp->xb_pktp != NULL);
13543 		pktp = xp->xb_pktp;
13544 	} else {
13545 		pktp = NULL;
13546 	}
13547 #endif /* __x86 */
13548 
13549 	startblock = xp->xb_blkno;	/* Absolute block num. */
13550 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
13551 
13552 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
13553 
13554 	/*
13555 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
13556 	 * call scsi_init_pkt, and build the CDB.
13557 	 */
13558 	rval = sd_setup_rw_pkt(un, &pktp, bp,
13559 	    cmd_flags, sdrunout, (caddr_t)un,
13560 	    startblock, blockcount);
13561 
13562 	if (rval == 0) {
13563 		/*
13564 		 * Success.
13565 		 *
13566 		 * If partial DMA is being used and required for this transfer.
13567 		 * set it up here.
13568 		 */
13569 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
13570 		    (pktp->pkt_resid != 0)) {
13571 
13572 			/*
13573 			 * Save the CDB length and pkt_resid for the
13574 			 * next xfer
13575 			 */
13576 			xp->xb_dma_resid = pktp->pkt_resid;
13577 
13578 			/* rezero resid */
13579 			pktp->pkt_resid = 0;
13580 
13581 		} else {
13582 			xp->xb_dma_resid = 0;
13583 		}
13584 
13585 		pktp->pkt_flags = un->un_tagflags;
13586 		pktp->pkt_time  = un->un_cmd_timeout;
13587 		pktp->pkt_comp  = sdintr;
13588 
13589 		pktp->pkt_private = bp;
13590 		*pktpp = pktp;
13591 
13592 		SD_TRACE(SD_LOG_IO_CORE, un,
13593 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
13594 
13595 #if defined(__x86)	/* DMAFREE for x86 only */
13596 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
13597 #endif
13598 
13599 		mutex_enter(SD_MUTEX(un));
13600 		return (SD_PKT_ALLOC_SUCCESS);
13601 
13602 	}
13603 
13604 	/*
13605 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
13606 	 * from sd_setup_rw_pkt.
13607 	 */
13608 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
13609 
13610 	if (rval == SD_PKT_ALLOC_FAILURE) {
13611 		*pktpp = NULL;
13612 		/*
13613 		 * Set the driver state to RWAIT to indicate the driver
13614 		 * is waiting on resource allocations. The driver will not
13615 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13616 		 */
13617 		mutex_enter(SD_MUTEX(un));
13618 		New_state(un, SD_STATE_RWAIT);
13619 
13620 		SD_ERROR(SD_LOG_IO_CORE, un,
13621 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
13622 
13623 		if ((bp->b_flags & B_ERROR) != 0) {
13624 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13625 		}
13626 		return (SD_PKT_ALLOC_FAILURE);
13627 	} else {
13628 		/*
13629 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13630 		 *
13631 		 * This should never happen.  Maybe someone messed with the
13632 		 * kernel's minphys?
13633 		 */
13634 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13635 		    "Request rejected: too large for CDB: "
13636 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
13637 		SD_ERROR(SD_LOG_IO_CORE, un,
13638 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
13639 		mutex_enter(SD_MUTEX(un));
13640 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13641 
13642 	}
13643 }
13644 
13645 
13646 /*
13647  *    Function: sd_destroypkt_for_buf
13648  *
13649  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
13650  *
13651  *     Context: Kernel thread or interrupt context
13652  */
13653 
13654 static void
13655 sd_destroypkt_for_buf(struct buf *bp)
13656 {
13657 	ASSERT(bp != NULL);
13658 	ASSERT(SD_GET_UN(bp) != NULL);
13659 
13660 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13661 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
13662 
13663 	ASSERT(SD_GET_PKTP(bp) != NULL);
13664 	scsi_destroy_pkt(SD_GET_PKTP(bp));
13665 
13666 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
13667 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
13668 }
13669 
13670 /*
13671  *    Function: sd_setup_rw_pkt
13672  *
13673  * Description: Determines appropriate CDB group for the requested LBA
13674  *		and transfer length, calls scsi_init_pkt, and builds
13675  *		the CDB.  Do not use for partial DMA transfers except
13676  *		for the initial transfer since the CDB size must
13677  *		remain constant.
13678  *
13679  *     Context: Kernel thread and may be called from software interrupt
13680  *		context as part of a sdrunout callback. This function may not
13681  *		block or call routines that block
13682  */
13683 
13684 
13685 int
13686 sd_setup_rw_pkt(struct sd_lun *un,
13687     struct scsi_pkt **pktpp, struct buf *bp, int flags,
13688     int (*callback)(caddr_t), caddr_t callback_arg,
13689     diskaddr_t lba, uint32_t blockcount)
13690 {
13691 	struct scsi_pkt *return_pktp;
13692 	union scsi_cdb *cdbp;
13693 	struct sd_cdbinfo *cp = NULL;
13694 	int i;
13695 
13696 	/*
13697 	 * See which size CDB to use, based upon the request.
13698 	 */
13699 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
13700 
13701 		/*
13702 		 * Check lba and block count against sd_cdbtab limits.
13703 		 * In the partial DMA case, we have to use the same size
13704 		 * CDB for all the transfers.  Check lba + blockcount
13705 		 * against the max LBA so we know that segment of the
13706 		 * transfer can use the CDB we select.
13707 		 */
13708 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
13709 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
13710 
13711 			/*
13712 			 * The command will fit into the CDB type
13713 			 * specified by sd_cdbtab[i].
13714 			 */
13715 			cp = sd_cdbtab + i;
13716 
13717 			/*
13718 			 * Call scsi_init_pkt so we can fill in the
13719 			 * CDB.
13720 			 */
13721 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
13722 			    bp, cp->sc_grpcode, un->un_status_len, 0,
13723 			    flags, callback, callback_arg);
13724 
13725 			if (return_pktp != NULL) {
13726 
13727 				/*
13728 				 * Return new value of pkt
13729 				 */
13730 				*pktpp = return_pktp;
13731 
13732 				/*
13733 				 * To be safe, zero the CDB insuring there is
13734 				 * no leftover data from a previous command.
13735 				 */
13736 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
13737 
13738 				/*
13739 				 * Handle partial DMA mapping
13740 				 */
13741 				if (return_pktp->pkt_resid != 0) {
13742 
13743 					/*
13744 					 * Not going to xfer as many blocks as
13745 					 * originally expected
13746 					 */
13747 					blockcount -=
13748 					    SD_BYTES2TGTBLOCKS(un,
13749 					    return_pktp->pkt_resid);
13750 				}
13751 
13752 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
13753 
13754 				/*
13755 				 * Set command byte based on the CDB
13756 				 * type we matched.
13757 				 */
13758 				cdbp->scc_cmd = cp->sc_grpmask |
13759 				    ((bp->b_flags & B_READ) ?
13760 				    SCMD_READ : SCMD_WRITE);
13761 
13762 				SD_FILL_SCSI1_LUN(un, return_pktp);
13763 
13764 				/*
13765 				 * Fill in LBA and length
13766 				 */
13767 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
13768 				    (cp->sc_grpcode == CDB_GROUP4) ||
13769 				    (cp->sc_grpcode == CDB_GROUP0) ||
13770 				    (cp->sc_grpcode == CDB_GROUP5));
13771 
13772 				if (cp->sc_grpcode == CDB_GROUP1) {
13773 					FORMG1ADDR(cdbp, lba);
13774 					FORMG1COUNT(cdbp, blockcount);
13775 					return (0);
13776 				} else if (cp->sc_grpcode == CDB_GROUP4) {
13777 					FORMG4LONGADDR(cdbp, lba);
13778 					FORMG4COUNT(cdbp, blockcount);
13779 					return (0);
13780 				} else if (cp->sc_grpcode == CDB_GROUP0) {
13781 					FORMG0ADDR(cdbp, lba);
13782 					FORMG0COUNT(cdbp, blockcount);
13783 					return (0);
13784 				} else if (cp->sc_grpcode == CDB_GROUP5) {
13785 					FORMG5ADDR(cdbp, lba);
13786 					FORMG5COUNT(cdbp, blockcount);
13787 					return (0);
13788 				}
13789 
13790 				/*
13791 				 * It should be impossible to not match one
13792 				 * of the CDB types above, so we should never
13793 				 * reach this point.  Set the CDB command byte
13794 				 * to test-unit-ready to avoid writing
13795 				 * to somewhere we don't intend.
13796 				 */
13797 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
13798 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13799 			} else {
13800 				/*
13801 				 * Couldn't get scsi_pkt
13802 				 */
13803 				return (SD_PKT_ALLOC_FAILURE);
13804 			}
13805 		}
13806 	}
13807 
13808 	/*
13809 	 * None of the available CDB types were suitable.  This really
13810 	 * should never happen:  on a 64 bit system we support
13811 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
13812 	 * and on a 32 bit system we will refuse to bind to a device
13813 	 * larger than 2TB so addresses will never be larger than 32 bits.
13814 	 */
13815 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13816 }
13817 
13818 /*
13819  *    Function: sd_setup_next_rw_pkt
13820  *
13821  * Description: Setup packet for partial DMA transfers, except for the
13822  *		initial transfer.  sd_setup_rw_pkt should be used for
13823  *		the initial transfer.
13824  *
13825  *     Context: Kernel thread and may be called from interrupt context.
13826  */
13827 
13828 int
13829 sd_setup_next_rw_pkt(struct sd_lun *un,
13830     struct scsi_pkt *pktp, struct buf *bp,
13831     diskaddr_t lba, uint32_t blockcount)
13832 {
13833 	uchar_t com;
13834 	union scsi_cdb *cdbp;
13835 	uchar_t cdb_group_id;
13836 
13837 	ASSERT(pktp != NULL);
13838 	ASSERT(pktp->pkt_cdbp != NULL);
13839 
13840 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
13841 	com = cdbp->scc_cmd;
13842 	cdb_group_id = CDB_GROUPID(com);
13843 
13844 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
13845 	    (cdb_group_id == CDB_GROUPID_1) ||
13846 	    (cdb_group_id == CDB_GROUPID_4) ||
13847 	    (cdb_group_id == CDB_GROUPID_5));
13848 
13849 	/*
13850 	 * Move pkt to the next portion of the xfer.
13851 	 * func is NULL_FUNC so we do not have to release
13852 	 * the disk mutex here.
13853 	 */
13854 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
13855 	    NULL_FUNC, NULL) == pktp) {
13856 		/* Success.  Handle partial DMA */
13857 		if (pktp->pkt_resid != 0) {
13858 			blockcount -=
13859 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
13860 		}
13861 
13862 		cdbp->scc_cmd = com;
13863 		SD_FILL_SCSI1_LUN(un, pktp);
13864 		if (cdb_group_id == CDB_GROUPID_1) {
13865 			FORMG1ADDR(cdbp, lba);
13866 			FORMG1COUNT(cdbp, blockcount);
13867 			return (0);
13868 		} else if (cdb_group_id == CDB_GROUPID_4) {
13869 			FORMG4LONGADDR(cdbp, lba);
13870 			FORMG4COUNT(cdbp, blockcount);
13871 			return (0);
13872 		} else if (cdb_group_id == CDB_GROUPID_0) {
13873 			FORMG0ADDR(cdbp, lba);
13874 			FORMG0COUNT(cdbp, blockcount);
13875 			return (0);
13876 		} else if (cdb_group_id == CDB_GROUPID_5) {
13877 			FORMG5ADDR(cdbp, lba);
13878 			FORMG5COUNT(cdbp, blockcount);
13879 			return (0);
13880 		}
13881 
13882 		/* Unreachable */
13883 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
13884 	}
13885 
13886 	/*
13887 	 * Error setting up next portion of cmd transfer.
13888 	 * Something is definitely very wrong and this
13889 	 * should not happen.
13890 	 */
13891 	return (SD_PKT_ALLOC_FAILURE);
13892 }
13893 
13894 /*
13895  *    Function: sd_initpkt_for_uscsi
13896  *
13897  * Description: Allocate and initialize for transport a scsi_pkt struct,
13898  *		based upon the info specified in the given uscsi_cmd struct.
13899  *
13900  * Return Code: SD_PKT_ALLOC_SUCCESS
13901  *		SD_PKT_ALLOC_FAILURE
13902  *		SD_PKT_ALLOC_FAILURE_NO_DMA
13903  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
13904  *
13905  *     Context: Kernel thread and may be called from software interrupt context
13906  *		as part of a sdrunout callback. This function may not block or
13907  *		call routines that block
13908  */
13909 
13910 static int
13911 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
13912 {
13913 	struct uscsi_cmd *uscmd;
13914 	struct sd_xbuf	*xp;
13915 	struct scsi_pkt	*pktp;
13916 	struct sd_lun	*un;
13917 	uint32_t	flags = 0;
13918 
13919 	ASSERT(bp != NULL);
13920 	ASSERT(pktpp != NULL);
13921 	xp = SD_GET_XBUF(bp);
13922 	ASSERT(xp != NULL);
13923 	un = SD_GET_UN(bp);
13924 	ASSERT(un != NULL);
13925 	ASSERT(mutex_owned(SD_MUTEX(un)));
13926 
13927 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
13928 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
13929 	ASSERT(uscmd != NULL);
13930 
13931 	SD_TRACE(SD_LOG_IO_CORE, un,
13932 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
13933 
13934 	/*
13935 	 * Allocate the scsi_pkt for the command.
13936 	 *
13937 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
13938 	 *	 during scsi_init_pkt time and will continue to use the
13939 	 *	 same path as long as the same scsi_pkt is used without
13940 	 *	 intervening scsi_dmafree(). Since uscsi command does
13941 	 *	 not call scsi_dmafree() before retry failed command, it
13942 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
13943 	 *	 set such that scsi_vhci can use other available path for
13944 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
13945 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
13946 	 *
13947 	 *	 More fundamentally, we can't support breaking up this DMA into
13948 	 *	 multiple windows on x86. There is, in general, no guarantee
13949 	 *	 that arbitrary SCSI commands are idempotent, which is required
13950 	 *	 if we want to use multiple windows for a given command.
13951 	 */
13952 	if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
13953 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
13954 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
13955 		    ((int)(uscmd->uscsi_rqlen) + sizeof (struct scsi_arq_status)
13956 		    - sizeof (struct scsi_extended_sense)), 0,
13957 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL) | PKT_XARQ,
13958 		    sdrunout, (caddr_t)un);
13959 	} else {
13960 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
13961 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
13962 		    sizeof (struct scsi_arq_status), 0,
13963 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
13964 		    sdrunout, (caddr_t)un);
13965 	}
13966 
13967 	if (pktp == NULL) {
13968 		*pktpp = NULL;
13969 		/*
13970 		 * Set the driver state to RWAIT to indicate the driver
13971 		 * is waiting on resource allocations. The driver will not
13972 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
13973 		 */
13974 		New_state(un, SD_STATE_RWAIT);
13975 
13976 		SD_ERROR(SD_LOG_IO_CORE, un,
13977 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
13978 
13979 		if ((bp->b_flags & B_ERROR) != 0) {
13980 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
13981 		}
13982 		return (SD_PKT_ALLOC_FAILURE);
13983 	}
13984 
13985 	/*
13986 	 * We do not do DMA breakup for USCSI commands, so return failure
13987 	 * here if all the needed DMA resources were not allocated.
13988 	 */
13989 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
13990 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
13991 		scsi_destroy_pkt(pktp);
13992 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
13993 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
13994 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
13995 	}
13996 
13997 	/* Init the cdb from the given uscsi struct */
13998 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
13999 	    uscmd->uscsi_cdb[0], 0, 0, 0);
14000 
14001 	SD_FILL_SCSI1_LUN(un, pktp);
14002 
14003 	/*
14004 	 * Set up the optional USCSI flags. See the uscsi(4I) man page
14005 	 * for listing of the supported flags.
14006 	 */
14007 
14008 	if (uscmd->uscsi_flags & USCSI_SILENT) {
14009 		flags |= FLAG_SILENT;
14010 	}
14011 
14012 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
14013 		flags |= FLAG_DIAGNOSE;
14014 	}
14015 
14016 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
14017 		flags |= FLAG_ISOLATE;
14018 	}
14019 
14020 	if (un->un_f_is_fibre == FALSE) {
14021 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
14022 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
14023 		}
14024 	}
14025 
14026 	/*
14027 	 * Set the pkt flags here so we save time later.
14028 	 * Note: These flags are NOT in the uscsi man page!!!
14029 	 */
14030 	if (uscmd->uscsi_flags & USCSI_HEAD) {
14031 		flags |= FLAG_HEAD;
14032 	}
14033 
14034 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
14035 		flags |= FLAG_NOINTR;
14036 	}
14037 
14038 	/*
14039 	 * For tagged queueing, things get a bit complicated.
14040 	 * Check first for head of queue and last for ordered queue.
14041 	 * If neither head nor order, use the default driver tag flags.
14042 	 */
14043 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
14044 		if (uscmd->uscsi_flags & USCSI_HTAG) {
14045 			flags |= FLAG_HTAG;
14046 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
14047 			flags |= FLAG_OTAG;
14048 		} else {
14049 			flags |= un->un_tagflags & FLAG_TAGMASK;
14050 		}
14051 	}
14052 
14053 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
14054 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
14055 	}
14056 
14057 	pktp->pkt_flags = flags;
14058 
14059 	/* Transfer uscsi information to scsi_pkt */
14060 	(void) scsi_uscsi_pktinit(uscmd, pktp);
14061 
14062 	/* Copy the caller's CDB into the pkt... */
14063 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
14064 
14065 	if (uscmd->uscsi_timeout == 0) {
14066 		pktp->pkt_time = un->un_uscsi_timeout;
14067 	} else {
14068 		pktp->pkt_time = uscmd->uscsi_timeout;
14069 	}
14070 
14071 	/* need it later to identify USCSI request in sdintr */
14072 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
14073 
14074 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
14075 
14076 	pktp->pkt_private = bp;
14077 	pktp->pkt_comp = sdintr;
14078 	*pktpp = pktp;
14079 
14080 	SD_TRACE(SD_LOG_IO_CORE, un,
14081 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
14082 
14083 	return (SD_PKT_ALLOC_SUCCESS);
14084 }
14085 
14086 
14087 /*
14088  *    Function: sd_destroypkt_for_uscsi
14089  *
14090  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
14091  *		IOs.. Also saves relevant info into the associated uscsi_cmd
14092  *		struct.
14093  *
14094  *     Context: May be called under interrupt context
14095  */
14096 
14097 static void
14098 sd_destroypkt_for_uscsi(struct buf *bp)
14099 {
14100 	struct uscsi_cmd *uscmd;
14101 	struct sd_xbuf	*xp;
14102 	struct scsi_pkt	*pktp;
14103 	struct sd_lun	*un;
14104 	struct sd_uscsi_info *suip;
14105 
14106 	ASSERT(bp != NULL);
14107 	xp = SD_GET_XBUF(bp);
14108 	ASSERT(xp != NULL);
14109 	un = SD_GET_UN(bp);
14110 	ASSERT(un != NULL);
14111 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14112 	pktp = SD_GET_PKTP(bp);
14113 	ASSERT(pktp != NULL);
14114 
14115 	SD_TRACE(SD_LOG_IO_CORE, un,
14116 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
14117 
14118 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
14119 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
14120 	ASSERT(uscmd != NULL);
14121 
14122 	/* Save the status and the residual into the uscsi_cmd struct */
14123 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
14124 	uscmd->uscsi_resid  = bp->b_resid;
14125 
14126 	/* Transfer scsi_pkt information to uscsi */
14127 	(void) scsi_uscsi_pktfini(pktp, uscmd);
14128 
14129 	/*
14130 	 * If enabled, copy any saved sense data into the area specified
14131 	 * by the uscsi command.
14132 	 */
14133 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
14134 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
14135 		/*
14136 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
14137 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
14138 		 */
14139 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
14140 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
14141 		if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
14142 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14143 			    MAX_SENSE_LENGTH);
14144 		} else {
14145 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
14146 			    SENSE_LENGTH);
14147 		}
14148 	}
14149 	/*
14150 	 * The following assignments are for SCSI FMA.
14151 	 */
14152 	ASSERT(xp->xb_private != NULL);
14153 	suip = (struct sd_uscsi_info *)xp->xb_private;
14154 	suip->ui_pkt_reason = pktp->pkt_reason;
14155 	suip->ui_pkt_state = pktp->pkt_state;
14156 	suip->ui_pkt_statistics = pktp->pkt_statistics;
14157 	suip->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
14158 
14159 	/* We are done with the scsi_pkt; free it now */
14160 	ASSERT(SD_GET_PKTP(bp) != NULL);
14161 	scsi_destroy_pkt(SD_GET_PKTP(bp));
14162 
14163 	SD_TRACE(SD_LOG_IO_CORE, un,
14164 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
14165 }
14166 
14167 
14168 /*
14169  *    Function: sd_bioclone_alloc
14170  *
14171  * Description: Allocate a buf(9S) and init it as per the given buf
14172  *		and the various arguments.  The associated sd_xbuf
14173  *		struct is (nearly) duplicated.  The struct buf *bp
14174  *		argument is saved in new_xp->xb_private.
14175  *
14176  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14177  *		datalen - size of data area for the shadow bp
14178  *		blkno - starting LBA
14179  *		func - function pointer for b_iodone in the shadow buf. (May
14180  *			be NULL if none.)
14181  *
14182  * Return Code: Pointer to allocates buf(9S) struct
14183  *
14184  *     Context: Can sleep.
14185  */
14186 
14187 static struct buf *
14188 sd_bioclone_alloc(struct buf *bp, size_t datalen, daddr_t blkno,
14189     int (*func)(struct buf *))
14190 {
14191 	struct	sd_lun	*un;
14192 	struct	sd_xbuf	*xp;
14193 	struct	sd_xbuf	*new_xp;
14194 	struct	buf	*new_bp;
14195 
14196 	ASSERT(bp != NULL);
14197 	xp = SD_GET_XBUF(bp);
14198 	ASSERT(xp != NULL);
14199 	un = SD_GET_UN(bp);
14200 	ASSERT(un != NULL);
14201 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14202 
14203 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
14204 	    NULL, KM_SLEEP);
14205 
14206 	new_bp->b_lblkno	= blkno;
14207 
14208 	/*
14209 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14210 	 * original xbuf into it.
14211 	 */
14212 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14213 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14214 
14215 	/*
14216 	 * The given bp is automatically saved in the xb_private member
14217 	 * of the new xbuf.  Callers are allowed to depend on this.
14218 	 */
14219 	new_xp->xb_private = bp;
14220 
14221 	new_bp->b_private  = new_xp;
14222 
14223 	return (new_bp);
14224 }
14225 
14226 /*
14227  *    Function: sd_shadow_buf_alloc
14228  *
14229  * Description: Allocate a buf(9S) and init it as per the given buf
14230  *		and the various arguments.  The associated sd_xbuf
14231  *		struct is (nearly) duplicated.  The struct buf *bp
14232  *		argument is saved in new_xp->xb_private.
14233  *
14234  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
14235  *		datalen - size of data area for the shadow bp
14236  *		bflags - B_READ or B_WRITE (pseudo flag)
14237  *		blkno - starting LBA
14238  *		func - function pointer for b_iodone in the shadow buf. (May
14239  *			be NULL if none.)
14240  *
14241  * Return Code: Pointer to allocates buf(9S) struct
14242  *
14243  *     Context: Can sleep.
14244  */
14245 
14246 static struct buf *
14247 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
14248     daddr_t blkno, int (*func)(struct buf *))
14249 {
14250 	struct	sd_lun	*un;
14251 	struct	sd_xbuf	*xp;
14252 	struct	sd_xbuf	*new_xp;
14253 	struct	buf	*new_bp;
14254 
14255 	ASSERT(bp != NULL);
14256 	xp = SD_GET_XBUF(bp);
14257 	ASSERT(xp != NULL);
14258 	un = SD_GET_UN(bp);
14259 	ASSERT(un != NULL);
14260 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14261 
14262 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
14263 		bp_mapin(bp);
14264 	}
14265 
14266 	bflags &= (B_READ | B_WRITE);
14267 #if defined(__x86)
14268 	new_bp = getrbuf(KM_SLEEP);
14269 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
14270 	new_bp->b_bcount = datalen;
14271 	new_bp->b_flags = bflags |
14272 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
14273 #else
14274 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
14275 	    datalen, bflags, SLEEP_FUNC, NULL);
14276 #endif
14277 	new_bp->av_forw	= NULL;
14278 	new_bp->av_back	= NULL;
14279 	new_bp->b_dev	= bp->b_dev;
14280 	new_bp->b_blkno	= blkno;
14281 	new_bp->b_iodone = func;
14282 	new_bp->b_edev	= bp->b_edev;
14283 	new_bp->b_resid	= 0;
14284 
14285 	/* We need to preserve the B_FAILFAST flag */
14286 	if (bp->b_flags & B_FAILFAST) {
14287 		new_bp->b_flags |= B_FAILFAST;
14288 	}
14289 
14290 	/*
14291 	 * Allocate an xbuf for the shadow bp and copy the contents of the
14292 	 * original xbuf into it.
14293 	 */
14294 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14295 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
14296 
14297 	/* Need later to copy data between the shadow buf & original buf! */
14298 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
14299 
14300 	/*
14301 	 * The given bp is automatically saved in the xb_private member
14302 	 * of the new xbuf.  Callers are allowed to depend on this.
14303 	 */
14304 	new_xp->xb_private = bp;
14305 
14306 	new_bp->b_private  = new_xp;
14307 
14308 	return (new_bp);
14309 }
14310 
14311 /*
14312  *    Function: sd_bioclone_free
14313  *
14314  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
14315  *		in the larger than partition operation.
14316  *
14317  *     Context: May be called under interrupt context
14318  */
14319 
14320 static void
14321 sd_bioclone_free(struct buf *bp)
14322 {
14323 	struct sd_xbuf	*xp;
14324 
14325 	ASSERT(bp != NULL);
14326 	xp = SD_GET_XBUF(bp);
14327 	ASSERT(xp != NULL);
14328 
14329 	/*
14330 	 * Call bp_mapout() before freeing the buf,  in case a lower
14331 	 * layer or HBA  had done a bp_mapin().  we must do this here
14332 	 * as we are the "originator" of the shadow buf.
14333 	 */
14334 	bp_mapout(bp);
14335 
14336 	/*
14337 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14338 	 * never gets confused by a stale value in this field. (Just a little
14339 	 * extra defensiveness here.)
14340 	 */
14341 	bp->b_iodone = NULL;
14342 
14343 	freerbuf(bp);
14344 
14345 	kmem_free(xp, sizeof (struct sd_xbuf));
14346 }
14347 
14348 /*
14349  *    Function: sd_shadow_buf_free
14350  *
14351  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
14352  *
14353  *     Context: May be called under interrupt context
14354  */
14355 
14356 static void
14357 sd_shadow_buf_free(struct buf *bp)
14358 {
14359 	struct sd_xbuf	*xp;
14360 
14361 	ASSERT(bp != NULL);
14362 	xp = SD_GET_XBUF(bp);
14363 	ASSERT(xp != NULL);
14364 
14365 #if defined(__sparc)
14366 	/*
14367 	 * Call bp_mapout() before freeing the buf,  in case a lower
14368 	 * layer or HBA  had done a bp_mapin().  we must do this here
14369 	 * as we are the "originator" of the shadow buf.
14370 	 */
14371 	bp_mapout(bp);
14372 #endif
14373 
14374 	/*
14375 	 * Null out b_iodone before freeing the bp, to ensure that the driver
14376 	 * never gets confused by a stale value in this field. (Just a little
14377 	 * extra defensiveness here.)
14378 	 */
14379 	bp->b_iodone = NULL;
14380 
14381 #if defined(__x86)
14382 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
14383 	freerbuf(bp);
14384 #else
14385 	scsi_free_consistent_buf(bp);
14386 #endif
14387 
14388 	kmem_free(xp, sizeof (struct sd_xbuf));
14389 }
14390 
14391 
14392 /*
14393  *    Function: sd_print_transport_rejected_message
14394  *
14395  * Description: This implements the ludicrously complex rules for printing
14396  *		a "transport rejected" message.  This is to address the
14397  *		specific problem of having a flood of this error message
14398  *		produced when a failover occurs.
14399  *
14400  *     Context: Any.
14401  */
14402 
14403 static void
14404 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
14405     int code)
14406 {
14407 	ASSERT(un != NULL);
14408 	ASSERT(mutex_owned(SD_MUTEX(un)));
14409 	ASSERT(xp != NULL);
14410 
14411 	/*
14412 	 * Print the "transport rejected" message under the following
14413 	 * conditions:
14414 	 *
14415 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
14416 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
14417 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
14418 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
14419 	 *   scsi_transport(9F) (which indicates that the target might have
14420 	 *   gone off-line).  This uses the un->un_tran_fatal_count
14421 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
14422 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
14423 	 *   from scsi_transport().
14424 	 *
14425 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
14426 	 * the preceeding cases in order for the message to be printed.
14427 	 */
14428 	if (((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) &&
14429 	    (SD_FM_LOG(un) == SD_FM_LOG_NSUP)) {
14430 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
14431 		    (code != TRAN_FATAL_ERROR) ||
14432 		    (un->un_tran_fatal_count == 1)) {
14433 			switch (code) {
14434 			case TRAN_BADPKT:
14435 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14436 				    "transport rejected bad packet\n");
14437 				break;
14438 			case TRAN_FATAL_ERROR:
14439 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14440 				    "transport rejected fatal error\n");
14441 				break;
14442 			default:
14443 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14444 				    "transport rejected (%d)\n", code);
14445 				break;
14446 			}
14447 		}
14448 	}
14449 }
14450 
14451 
14452 /*
14453  *    Function: sd_add_buf_to_waitq
14454  *
14455  * Description: Add the given buf(9S) struct to the wait queue for the
14456  *		instance.  If sorting is enabled, then the buf is added
14457  *		to the queue via an elevator sort algorithm (a la
14458  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
14459  *		If sorting is not enabled, then the buf is just added
14460  *		to the end of the wait queue.
14461  *
14462  * Return Code: void
14463  *
14464  *     Context: Does not sleep/block, therefore technically can be called
14465  *		from any context.  However if sorting is enabled then the
14466  *		execution time is indeterminate, and may take long if
14467  *		the wait queue grows large.
14468  */
14469 
14470 static void
14471 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
14472 {
14473 	struct buf *ap;
14474 
14475 	ASSERT(bp != NULL);
14476 	ASSERT(un != NULL);
14477 	ASSERT(mutex_owned(SD_MUTEX(un)));
14478 
14479 	/* If the queue is empty, add the buf as the only entry & return. */
14480 	if (un->un_waitq_headp == NULL) {
14481 		ASSERT(un->un_waitq_tailp == NULL);
14482 		un->un_waitq_headp = un->un_waitq_tailp = bp;
14483 		bp->av_forw = NULL;
14484 		return;
14485 	}
14486 
14487 	ASSERT(un->un_waitq_tailp != NULL);
14488 
14489 	/*
14490 	 * If sorting is disabled, just add the buf to the tail end of
14491 	 * the wait queue and return.
14492 	 */
14493 	if (un->un_f_disksort_disabled || un->un_f_enable_rmw) {
14494 		un->un_waitq_tailp->av_forw = bp;
14495 		un->un_waitq_tailp = bp;
14496 		bp->av_forw = NULL;
14497 		return;
14498 	}
14499 
14500 	/*
14501 	 * Sort thru the list of requests currently on the wait queue
14502 	 * and add the new buf request at the appropriate position.
14503 	 *
14504 	 * The un->un_waitq_headp is an activity chain pointer on which
14505 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
14506 	 * first queue holds those requests which are positioned after
14507 	 * the current SD_GET_BLKNO() (in the first request); the second holds
14508 	 * requests which came in after their SD_GET_BLKNO() number was passed.
14509 	 * Thus we implement a one way scan, retracting after reaching
14510 	 * the end of the drive to the first request on the second
14511 	 * queue, at which time it becomes the first queue.
14512 	 * A one-way scan is natural because of the way UNIX read-ahead
14513 	 * blocks are allocated.
14514 	 *
14515 	 * If we lie after the first request, then we must locate the
14516 	 * second request list and add ourselves to it.
14517 	 */
14518 	ap = un->un_waitq_headp;
14519 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
14520 		while (ap->av_forw != NULL) {
14521 			/*
14522 			 * Look for an "inversion" in the (normally
14523 			 * ascending) block numbers. This indicates
14524 			 * the start of the second request list.
14525 			 */
14526 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
14527 				/*
14528 				 * Search the second request list for the
14529 				 * first request at a larger block number.
14530 				 * We go before that; however if there is
14531 				 * no such request, we go at the end.
14532 				 */
14533 				do {
14534 					if (SD_GET_BLKNO(bp) <
14535 					    SD_GET_BLKNO(ap->av_forw)) {
14536 						goto insert;
14537 					}
14538 					ap = ap->av_forw;
14539 				} while (ap->av_forw != NULL);
14540 				goto insert;		/* after last */
14541 			}
14542 			ap = ap->av_forw;
14543 		}
14544 
14545 		/*
14546 		 * No inversions... we will go after the last, and
14547 		 * be the first request in the second request list.
14548 		 */
14549 		goto insert;
14550 	}
14551 
14552 	/*
14553 	 * Request is at/after the current request...
14554 	 * sort in the first request list.
14555 	 */
14556 	while (ap->av_forw != NULL) {
14557 		/*
14558 		 * We want to go after the current request (1) if
14559 		 * there is an inversion after it (i.e. it is the end
14560 		 * of the first request list), or (2) if the next
14561 		 * request is a larger block no. than our request.
14562 		 */
14563 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
14564 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
14565 			goto insert;
14566 		}
14567 		ap = ap->av_forw;
14568 	}
14569 
14570 	/*
14571 	 * Neither a second list nor a larger request, therefore
14572 	 * we go at the end of the first list (which is the same
14573 	 * as the end of the whole schebang).
14574 	 */
14575 insert:
14576 	bp->av_forw = ap->av_forw;
14577 	ap->av_forw = bp;
14578 
14579 	/*
14580 	 * If we inserted onto the tail end of the waitq, make sure the
14581 	 * tail pointer is updated.
14582 	 */
14583 	if (ap == un->un_waitq_tailp) {
14584 		un->un_waitq_tailp = bp;
14585 	}
14586 }
14587 
14588 
14589 /*
14590  *    Function: sd_start_cmds
14591  *
14592  * Description: Remove and transport cmds from the driver queues.
14593  *
14594  *   Arguments: un - pointer to the unit (soft state) struct for the target.
14595  *
14596  *		immed_bp - ptr to a buf to be transported immediately. Only
14597  *		the immed_bp is transported; bufs on the waitq are not
14598  *		processed and the un_retry_bp is not checked.  If immed_bp is
14599  *		NULL, then normal queue processing is performed.
14600  *
14601  *     Context: May be called from kernel thread context, interrupt context,
14602  *		or runout callback context. This function may not block or
14603  *		call routines that block.
14604  */
14605 
14606 static void
14607 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
14608 {
14609 	struct	sd_xbuf	*xp;
14610 	struct	buf	*bp;
14611 	void	(*statp)(kstat_io_t *);
14612 #if defined(__x86)	/* DMAFREE for x86 only */
14613 	void	(*saved_statp)(kstat_io_t *);
14614 #endif
14615 	int	rval;
14616 	struct sd_fm_internal *sfip = NULL;
14617 
14618 	ASSERT(un != NULL);
14619 	ASSERT(mutex_owned(SD_MUTEX(un)));
14620 	ASSERT(un->un_ncmds_in_transport >= 0);
14621 	ASSERT(un->un_throttle >= 0);
14622 
14623 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
14624 
14625 	do {
14626 #if defined(__x86)	/* DMAFREE for x86 only */
14627 		saved_statp = NULL;
14628 #endif
14629 
14630 		/*
14631 		 * If we are syncing or dumping, fail the command to
14632 		 * avoid recursively calling back into scsi_transport().
14633 		 * The dump I/O itself uses a separate code path so this
14634 		 * only prevents non-dump I/O from being sent while dumping.
14635 		 * File system sync takes place before dumping begins.
14636 		 * During panic, filesystem I/O is allowed provided
14637 		 * un_in_callback is <= 1.  This is to prevent recursion
14638 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
14639 		 * sd_start_cmds and so on.  See panic.c for more information
14640 		 * about the states the system can be in during panic.
14641 		 */
14642 		if ((un->un_state == SD_STATE_DUMPING) ||
14643 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
14644 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14645 			    "sd_start_cmds: panicking\n");
14646 			goto exit;
14647 		}
14648 
14649 		if ((bp = immed_bp) != NULL) {
14650 			/*
14651 			 * We have a bp that must be transported immediately.
14652 			 * It's OK to transport the immed_bp here without doing
14653 			 * the throttle limit check because the immed_bp is
14654 			 * always used in a retry/recovery case. This means
14655 			 * that we know we are not at the throttle limit by
14656 			 * virtue of the fact that to get here we must have
14657 			 * already gotten a command back via sdintr(). This also
14658 			 * relies on (1) the command on un_retry_bp preventing
14659 			 * further commands from the waitq from being issued;
14660 			 * and (2) the code in sd_retry_command checking the
14661 			 * throttle limit before issuing a delayed or immediate
14662 			 * retry. This holds even if the throttle limit is
14663 			 * currently ratcheted down from its maximum value.
14664 			 */
14665 			statp = kstat_runq_enter;
14666 			if (bp == un->un_retry_bp) {
14667 				ASSERT((un->un_retry_statp == NULL) ||
14668 				    (un->un_retry_statp == kstat_waitq_enter) ||
14669 				    (un->un_retry_statp ==
14670 				    kstat_runq_back_to_waitq));
14671 				/*
14672 				 * If the waitq kstat was incremented when
14673 				 * sd_set_retry_bp() queued this bp for a retry,
14674 				 * then we must set up statp so that the waitq
14675 				 * count will get decremented correctly below.
14676 				 * Also we must clear un->un_retry_statp to
14677 				 * ensure that we do not act on a stale value
14678 				 * in this field.
14679 				 */
14680 				if ((un->un_retry_statp == kstat_waitq_enter) ||
14681 				    (un->un_retry_statp ==
14682 				    kstat_runq_back_to_waitq)) {
14683 					statp = kstat_waitq_to_runq;
14684 				}
14685 #if defined(__x86)	/* DMAFREE for x86 only */
14686 				saved_statp = un->un_retry_statp;
14687 #endif
14688 				un->un_retry_statp = NULL;
14689 
14690 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14691 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
14692 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
14693 				    un, un->un_retry_bp, un->un_throttle,
14694 				    un->un_ncmds_in_transport);
14695 			} else {
14696 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
14697 				    "processing priority bp:0x%p\n", bp);
14698 			}
14699 
14700 		} else if ((bp = un->un_waitq_headp) != NULL) {
14701 			/*
14702 			 * A command on the waitq is ready to go, but do not
14703 			 * send it if:
14704 			 *
14705 			 * (1) the throttle limit has been reached, or
14706 			 * (2) a retry is pending, or
14707 			 * (3) a START_STOP_UNIT callback pending, or
14708 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
14709 			 *	command is pending.
14710 			 *
14711 			 * For all of these conditions, IO processing will
14712 			 * restart after the condition is cleared.
14713 			 */
14714 			if (un->un_ncmds_in_transport >= un->un_throttle) {
14715 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14716 				    "sd_start_cmds: exiting, "
14717 				    "throttle limit reached!\n");
14718 				goto exit;
14719 			}
14720 			if (un->un_retry_bp != NULL) {
14721 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14722 				    "sd_start_cmds: exiting, retry pending!\n");
14723 				goto exit;
14724 			}
14725 			if (un->un_startstop_timeid != NULL) {
14726 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14727 				    "sd_start_cmds: exiting, "
14728 				    "START_STOP pending!\n");
14729 				goto exit;
14730 			}
14731 			if (un->un_direct_priority_timeid != NULL) {
14732 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14733 				    "sd_start_cmds: exiting, "
14734 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
14735 				goto exit;
14736 			}
14737 
14738 			/* Dequeue the command */
14739 			un->un_waitq_headp = bp->av_forw;
14740 			if (un->un_waitq_headp == NULL) {
14741 				un->un_waitq_tailp = NULL;
14742 			}
14743 			bp->av_forw = NULL;
14744 			statp = kstat_waitq_to_runq;
14745 			SD_TRACE(SD_LOG_IO_CORE, un,
14746 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
14747 
14748 		} else {
14749 			/* No work to do so bail out now */
14750 			SD_TRACE(SD_LOG_IO_CORE, un,
14751 			    "sd_start_cmds: no more work, exiting!\n");
14752 			goto exit;
14753 		}
14754 
14755 		/*
14756 		 * Reset the state to normal. This is the mechanism by which
14757 		 * the state transitions from either SD_STATE_RWAIT or
14758 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
14759 		 * If state is SD_STATE_PM_CHANGING then this command is
14760 		 * part of the device power control and the state must
14761 		 * not be put back to normal. Doing so would would
14762 		 * allow new commands to proceed when they shouldn't,
14763 		 * the device may be going off.
14764 		 */
14765 		if ((un->un_state != SD_STATE_SUSPENDED) &&
14766 		    (un->un_state != SD_STATE_PM_CHANGING)) {
14767 			New_state(un, SD_STATE_NORMAL);
14768 		}
14769 
14770 		xp = SD_GET_XBUF(bp);
14771 		ASSERT(xp != NULL);
14772 
14773 #if defined(__x86)	/* DMAFREE for x86 only */
14774 		/*
14775 		 * Allocate the scsi_pkt if we need one, or attach DMA
14776 		 * resources if we have a scsi_pkt that needs them. The
14777 		 * latter should only occur for commands that are being
14778 		 * retried.
14779 		 */
14780 		if ((xp->xb_pktp == NULL) ||
14781 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
14782 #else
14783 		if (xp->xb_pktp == NULL) {
14784 #endif
14785 			/*
14786 			 * There is no scsi_pkt allocated for this buf. Call
14787 			 * the initpkt function to allocate & init one.
14788 			 *
14789 			 * The scsi_init_pkt runout callback functionality is
14790 			 * implemented as follows:
14791 			 *
14792 			 * 1) The initpkt function always calls
14793 			 *    scsi_init_pkt(9F) with sdrunout specified as the
14794 			 *    callback routine.
14795 			 * 2) A successful packet allocation is initialized and
14796 			 *    the I/O is transported.
14797 			 * 3) The I/O associated with an allocation resource
14798 			 *    failure is left on its queue to be retried via
14799 			 *    runout or the next I/O.
14800 			 * 4) The I/O associated with a DMA error is removed
14801 			 *    from the queue and failed with EIO. Processing of
14802 			 *    the transport queues is also halted to be
14803 			 *    restarted via runout or the next I/O.
14804 			 * 5) The I/O associated with a CDB size or packet
14805 			 *    size error is removed from the queue and failed
14806 			 *    with EIO. Processing of the transport queues is
14807 			 *    continued.
14808 			 *
14809 			 * Note: there is no interface for canceling a runout
14810 			 * callback. To prevent the driver from detaching or
14811 			 * suspending while a runout is pending the driver
14812 			 * state is set to SD_STATE_RWAIT
14813 			 *
14814 			 * Note: using the scsi_init_pkt callback facility can
14815 			 * result in an I/O request persisting at the head of
14816 			 * the list which cannot be satisfied even after
14817 			 * multiple retries. In the future the driver may
14818 			 * implement some kind of maximum runout count before
14819 			 * failing an I/O.
14820 			 *
14821 			 * Note: the use of funcp below may seem superfluous,
14822 			 * but it helps warlock figure out the correct
14823 			 * initpkt function calls (see [s]sd.wlcmd).
14824 			 */
14825 			struct scsi_pkt	*pktp;
14826 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
14827 
14828 			ASSERT(bp != un->un_rqs_bp);
14829 
14830 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
14831 			switch ((*funcp)(bp, &pktp)) {
14832 			case  SD_PKT_ALLOC_SUCCESS:
14833 				xp->xb_pktp = pktp;
14834 				SD_TRACE(SD_LOG_IO_CORE, un,
14835 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
14836 				    pktp);
14837 				goto got_pkt;
14838 
14839 			case SD_PKT_ALLOC_FAILURE:
14840 				/*
14841 				 * Temporary (hopefully) resource depletion.
14842 				 * Since retries and RQS commands always have a
14843 				 * scsi_pkt allocated, these cases should never
14844 				 * get here. So the only cases this needs to
14845 				 * handle is a bp from the waitq (which we put
14846 				 * back onto the waitq for sdrunout), or a bp
14847 				 * sent as an immed_bp (which we just fail).
14848 				 */
14849 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14850 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
14851 
14852 #if defined(__x86)	/* DMAFREE for x86 only */
14853 
14854 				if (bp == immed_bp) {
14855 					/*
14856 					 * If SD_XB_DMA_FREED is clear, then
14857 					 * this is a failure to allocate a
14858 					 * scsi_pkt, and we must fail the
14859 					 * command.
14860 					 */
14861 					if ((xp->xb_pkt_flags &
14862 					    SD_XB_DMA_FREED) == 0) {
14863 						break;
14864 					}
14865 
14866 					/*
14867 					 * If this immediate command is NOT our
14868 					 * un_retry_bp, then we must fail it.
14869 					 */
14870 					if (bp != un->un_retry_bp) {
14871 						break;
14872 					}
14873 
14874 					/*
14875 					 * We get here if this cmd is our
14876 					 * un_retry_bp that was DMAFREED, but
14877 					 * scsi_init_pkt() failed to reallocate
14878 					 * DMA resources when we attempted to
14879 					 * retry it. This can happen when an
14880 					 * mpxio failover is in progress, but
14881 					 * we don't want to just fail the
14882 					 * command in this case.
14883 					 *
14884 					 * Use timeout(9F) to restart it after
14885 					 * a 100ms delay.  We don't want to
14886 					 * let sdrunout() restart it, because
14887 					 * sdrunout() is just supposed to start
14888 					 * commands that are sitting on the
14889 					 * wait queue.  The un_retry_bp stays
14890 					 * set until the command completes, but
14891 					 * sdrunout can be called many times
14892 					 * before that happens.  Since sdrunout
14893 					 * cannot tell if the un_retry_bp is
14894 					 * already in the transport, it could
14895 					 * end up calling scsi_transport() for
14896 					 * the un_retry_bp multiple times.
14897 					 *
14898 					 * Also: don't schedule the callback
14899 					 * if some other callback is already
14900 					 * pending.
14901 					 */
14902 					if (un->un_retry_statp == NULL) {
14903 						/*
14904 						 * restore the kstat pointer to
14905 						 * keep kstat counts coherent
14906 						 * when we do retry the command.
14907 						 */
14908 						un->un_retry_statp =
14909 						    saved_statp;
14910 					}
14911 
14912 					if ((un->un_startstop_timeid == NULL) &&
14913 					    (un->un_retry_timeid == NULL) &&
14914 					    (un->un_direct_priority_timeid ==
14915 					    NULL)) {
14916 
14917 						un->un_retry_timeid =
14918 						    timeout(
14919 						    sd_start_retry_command,
14920 						    un, SD_RESTART_TIMEOUT);
14921 					}
14922 					goto exit;
14923 				}
14924 
14925 #else
14926 				if (bp == immed_bp) {
14927 					break;	/* Just fail the command */
14928 				}
14929 #endif
14930 
14931 				/* Add the buf back to the head of the waitq */
14932 				bp->av_forw = un->un_waitq_headp;
14933 				un->un_waitq_headp = bp;
14934 				if (un->un_waitq_tailp == NULL) {
14935 					un->un_waitq_tailp = bp;
14936 				}
14937 				goto exit;
14938 
14939 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
14940 				/*
14941 				 * HBA DMA resource failure. Fail the command
14942 				 * and continue processing of the queues.
14943 				 */
14944 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14945 				    "sd_start_cmds: "
14946 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
14947 				break;
14948 
14949 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
14950 				/*
14951 				 * Note:x86: Partial DMA mapping not supported
14952 				 * for USCSI commands, and all the needed DMA
14953 				 * resources were not allocated.
14954 				 */
14955 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14956 				    "sd_start_cmds: "
14957 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
14958 				break;
14959 
14960 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
14961 				/*
14962 				 * Note:x86: Request cannot fit into CDB based
14963 				 * on lba and len.
14964 				 */
14965 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14966 				    "sd_start_cmds: "
14967 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
14968 				break;
14969 
14970 			default:
14971 				/* Should NEVER get here! */
14972 				panic("scsi_initpkt error");
14973 				/*NOTREACHED*/
14974 			}
14975 
14976 			/*
14977 			 * Fatal error in allocating a scsi_pkt for this buf.
14978 			 * Update kstats & return the buf with an error code.
14979 			 * We must use sd_return_failed_command_no_restart() to
14980 			 * avoid a recursive call back into sd_start_cmds().
14981 			 * However this also means that we must keep processing
14982 			 * the waitq here in order to avoid stalling.
14983 			 */
14984 			if (statp == kstat_waitq_to_runq) {
14985 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
14986 			}
14987 			sd_return_failed_command_no_restart(un, bp, EIO);
14988 			if (bp == immed_bp) {
14989 				/* immed_bp is gone by now, so clear this */
14990 				immed_bp = NULL;
14991 			}
14992 			continue;
14993 		}
14994 got_pkt:
14995 		if (bp == immed_bp) {
14996 			/* goto the head of the class.... */
14997 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
14998 		}
14999 
15000 		un->un_ncmds_in_transport++;
15001 		SD_UPDATE_KSTATS(un, statp, bp);
15002 
15003 		/*
15004 		 * Call scsi_transport() to send the command to the target.
15005 		 * According to SCSA architecture, we must drop the mutex here
15006 		 * before calling scsi_transport() in order to avoid deadlock.
15007 		 * Note that the scsi_pkt's completion routine can be executed
15008 		 * (from interrupt context) even before the call to
15009 		 * scsi_transport() returns.
15010 		 */
15011 		SD_TRACE(SD_LOG_IO_CORE, un,
15012 		    "sd_start_cmds: calling scsi_transport()\n");
15013 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
15014 
15015 		mutex_exit(SD_MUTEX(un));
15016 		rval = scsi_transport(xp->xb_pktp);
15017 		mutex_enter(SD_MUTEX(un));
15018 
15019 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15020 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
15021 
15022 		switch (rval) {
15023 		case TRAN_ACCEPT:
15024 			/* Clear this with every pkt accepted by the HBA */
15025 			un->un_tran_fatal_count = 0;
15026 			break;	/* Success; try the next cmd (if any) */
15027 
15028 		case TRAN_BUSY:
15029 			un->un_ncmds_in_transport--;
15030 			ASSERT(un->un_ncmds_in_transport >= 0);
15031 
15032 			/*
15033 			 * Don't retry request sense, the sense data
15034 			 * is lost when another request is sent.
15035 			 * Free up the rqs buf and retry
15036 			 * the original failed cmd.  Update kstat.
15037 			 */
15038 			if (bp == un->un_rqs_bp) {
15039 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15040 				bp = sd_mark_rqs_idle(un, xp);
15041 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15042 				    NULL, NULL, EIO, un->un_busy_timeout / 500,
15043 				    kstat_waitq_enter);
15044 				goto exit;
15045 			}
15046 
15047 #if defined(__x86)	/* DMAFREE for x86 only */
15048 			/*
15049 			 * Free the DMA resources for the  scsi_pkt. This will
15050 			 * allow mpxio to select another path the next time
15051 			 * we call scsi_transport() with this scsi_pkt.
15052 			 * See sdintr() for the rationalization behind this.
15053 			 */
15054 			if ((un->un_f_is_fibre == TRUE) &&
15055 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
15056 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
15057 				scsi_dmafree(xp->xb_pktp);
15058 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
15059 			}
15060 #endif
15061 
15062 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
15063 				/*
15064 				 * Commands that are SD_PATH_DIRECT_PRIORITY
15065 				 * are for error recovery situations. These do
15066 				 * not use the normal command waitq, so if they
15067 				 * get a TRAN_BUSY we cannot put them back onto
15068 				 * the waitq for later retry. One possible
15069 				 * problem is that there could already be some
15070 				 * other command on un_retry_bp that is waiting
15071 				 * for this one to complete, so we would be
15072 				 * deadlocked if we put this command back onto
15073 				 * the waitq for later retry (since un_retry_bp
15074 				 * must complete before the driver gets back to
15075 				 * commands on the waitq).
15076 				 *
15077 				 * To avoid deadlock we must schedule a callback
15078 				 * that will restart this command after a set
15079 				 * interval.  This should keep retrying for as
15080 				 * long as the underlying transport keeps
15081 				 * returning TRAN_BUSY (just like for other
15082 				 * commands).  Use the same timeout interval as
15083 				 * for the ordinary TRAN_BUSY retry.
15084 				 */
15085 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15086 				    "sd_start_cmds: scsi_transport() returned "
15087 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
15088 
15089 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15090 				un->un_direct_priority_timeid =
15091 				    timeout(sd_start_direct_priority_command,
15092 				    bp, un->un_busy_timeout / 500);
15093 
15094 				goto exit;
15095 			}
15096 
15097 			/*
15098 			 * For TRAN_BUSY, we want to reduce the throttle value,
15099 			 * unless we are retrying a command.
15100 			 */
15101 			if (bp != un->un_retry_bp) {
15102 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
15103 			}
15104 
15105 			/*
15106 			 * Set up the bp to be tried again 10 ms later.
15107 			 * Note:x86: Is there a timeout value in the sd_lun
15108 			 * for this condition?
15109 			 */
15110 			sd_set_retry_bp(un, bp, un->un_busy_timeout / 500,
15111 			    kstat_runq_back_to_waitq);
15112 			goto exit;
15113 
15114 		case TRAN_FATAL_ERROR:
15115 			un->un_tran_fatal_count++;
15116 			/* FALLTHRU */
15117 
15118 		case TRAN_BADPKT:
15119 		default:
15120 			un->un_ncmds_in_transport--;
15121 			ASSERT(un->un_ncmds_in_transport >= 0);
15122 
15123 			/*
15124 			 * If this is our REQUEST SENSE command with a
15125 			 * transport error, we must get back the pointers
15126 			 * to the original buf, and mark the REQUEST
15127 			 * SENSE command as "available".
15128 			 */
15129 			if (bp == un->un_rqs_bp) {
15130 				bp = sd_mark_rqs_idle(un, xp);
15131 				xp = SD_GET_XBUF(bp);
15132 			} else {
15133 				/*
15134 				 * Legacy behavior: do not update transport
15135 				 * error count for request sense commands.
15136 				 */
15137 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
15138 			}
15139 
15140 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
15141 			sd_print_transport_rejected_message(un, xp, rval);
15142 
15143 			/*
15144 			 * This command will be terminated by SD driver due
15145 			 * to a fatal transport error. We should post
15146 			 * ereport.io.scsi.cmd.disk.tran with driver-assessment
15147 			 * of "fail" for any command to indicate this
15148 			 * situation.
15149 			 */
15150 			if (xp->xb_ena > 0) {
15151 				ASSERT(un->un_fm_private != NULL);
15152 				sfip = un->un_fm_private;
15153 				sfip->fm_ssc.ssc_flags |= SSC_FLAGS_TRAN_ABORT;
15154 				sd_ssc_extract_info(&sfip->fm_ssc, un,
15155 				    xp->xb_pktp, bp, xp);
15156 				sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15157 			}
15158 
15159 			/*
15160 			 * We must use sd_return_failed_command_no_restart() to
15161 			 * avoid a recursive call back into sd_start_cmds().
15162 			 * However this also means that we must keep processing
15163 			 * the waitq here in order to avoid stalling.
15164 			 */
15165 			sd_return_failed_command_no_restart(un, bp, EIO);
15166 
15167 			/*
15168 			 * Notify any threads waiting in sd_ddi_suspend() that
15169 			 * a command completion has occurred.
15170 			 */
15171 			if (un->un_state == SD_STATE_SUSPENDED) {
15172 				cv_broadcast(&un->un_disk_busy_cv);
15173 			}
15174 
15175 			if (bp == immed_bp) {
15176 				/* immed_bp is gone by now, so clear this */
15177 				immed_bp = NULL;
15178 			}
15179 			break;
15180 		}
15181 
15182 	} while (immed_bp == NULL);
15183 
15184 exit:
15185 	ASSERT(mutex_owned(SD_MUTEX(un)));
15186 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
15187 }
15188 
15189 
15190 /*
15191  *    Function: sd_return_command
15192  *
15193  * Description: Returns a command to its originator (with or without an
15194  *		error).  Also starts commands waiting to be transported
15195  *		to the target.
15196  *
15197  *     Context: May be called from interrupt, kernel, or timeout context
15198  */
15199 
15200 static void
15201 sd_return_command(struct sd_lun *un, struct buf *bp)
15202 {
15203 	struct sd_xbuf *xp;
15204 	struct scsi_pkt *pktp;
15205 	struct sd_fm_internal *sfip;
15206 
15207 	ASSERT(bp != NULL);
15208 	ASSERT(un != NULL);
15209 	ASSERT(mutex_owned(SD_MUTEX(un)));
15210 	ASSERT(bp != un->un_rqs_bp);
15211 	xp = SD_GET_XBUF(bp);
15212 	ASSERT(xp != NULL);
15213 
15214 	pktp = SD_GET_PKTP(bp);
15215 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15216 	ASSERT(sfip != NULL);
15217 
15218 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
15219 
15220 	/*
15221 	 * Note: check for the "sdrestart failed" case.
15222 	 */
15223 	if ((un->un_partial_dma_supported == 1) &&
15224 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
15225 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
15226 	    (xp->xb_pktp->pkt_resid == 0)) {
15227 
15228 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
15229 			/*
15230 			 * Successfully set up next portion of cmd
15231 			 * transfer, try sending it
15232 			 */
15233 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
15234 			    NULL, NULL, 0, (clock_t)0, NULL);
15235 			sd_start_cmds(un, NULL);
15236 			return;	/* Note:x86: need a return here? */
15237 		}
15238 	}
15239 
15240 	/*
15241 	 * If this is the failfast bp, clear it from un_failfast_bp. This
15242 	 * can happen if upon being re-tried the failfast bp either
15243 	 * succeeded or encountered another error (possibly even a different
15244 	 * error than the one that precipitated the failfast state, but in
15245 	 * that case it would have had to exhaust retries as well). Regardless,
15246 	 * this should not occur whenever the instance is in the active
15247 	 * failfast state.
15248 	 */
15249 	if (bp == un->un_failfast_bp) {
15250 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15251 		un->un_failfast_bp = NULL;
15252 	}
15253 
15254 	/*
15255 	 * Clear the failfast state upon successful completion of ANY cmd.
15256 	 */
15257 	if (bp->b_error == 0) {
15258 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15259 		/*
15260 		 * If this is a successful command, but used to be retried,
15261 		 * we will take it as a recovered command and post an
15262 		 * ereport with driver-assessment of "recovered".
15263 		 */
15264 		if (xp->xb_ena > 0) {
15265 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15266 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RECOVERY);
15267 		}
15268 	} else {
15269 		/*
15270 		 * If this is a failed non-USCSI command we will post an
15271 		 * ereport with driver-assessment set accordingly("fail" or
15272 		 * "fatal").
15273 		 */
15274 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15275 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15276 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_FATAL);
15277 		}
15278 	}
15279 
15280 	/*
15281 	 * This is used if the command was retried one or more times. Show that
15282 	 * we are done with it, and allow processing of the waitq to resume.
15283 	 */
15284 	if (bp == un->un_retry_bp) {
15285 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15286 		    "sd_return_command: un:0x%p: "
15287 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15288 		un->un_retry_bp = NULL;
15289 		un->un_retry_statp = NULL;
15290 	}
15291 
15292 	SD_UPDATE_RDWR_STATS(un, bp);
15293 	SD_UPDATE_PARTITION_STATS(un, bp);
15294 
15295 	switch (un->un_state) {
15296 	case SD_STATE_SUSPENDED:
15297 		/*
15298 		 * Notify any threads waiting in sd_ddi_suspend() that
15299 		 * a command completion has occurred.
15300 		 */
15301 		cv_broadcast(&un->un_disk_busy_cv);
15302 		break;
15303 	default:
15304 		sd_start_cmds(un, NULL);
15305 		break;
15306 	}
15307 
15308 	/* Return this command up the iodone chain to its originator. */
15309 	mutex_exit(SD_MUTEX(un));
15310 
15311 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15312 	xp->xb_pktp = NULL;
15313 
15314 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15315 
15316 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15317 	mutex_enter(SD_MUTEX(un));
15318 
15319 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
15320 }
15321 
15322 
15323 /*
15324  *    Function: sd_return_failed_command
15325  *
15326  * Description: Command completion when an error occurred.
15327  *
15328  *     Context: May be called from interrupt context
15329  */
15330 
15331 static void
15332 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
15333 {
15334 	ASSERT(bp != NULL);
15335 	ASSERT(un != NULL);
15336 	ASSERT(mutex_owned(SD_MUTEX(un)));
15337 
15338 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15339 	    "sd_return_failed_command: entry\n");
15340 
15341 	/*
15342 	 * b_resid could already be nonzero due to a partial data
15343 	 * transfer, so do not change it here.
15344 	 */
15345 	SD_BIOERROR(bp, errcode);
15346 
15347 	sd_return_command(un, bp);
15348 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15349 	    "sd_return_failed_command: exit\n");
15350 }
15351 
15352 
15353 /*
15354  *    Function: sd_return_failed_command_no_restart
15355  *
15356  * Description: Same as sd_return_failed_command, but ensures that no
15357  *		call back into sd_start_cmds will be issued.
15358  *
15359  *     Context: May be called from interrupt context
15360  */
15361 
15362 static void
15363 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
15364     int errcode)
15365 {
15366 	struct sd_xbuf *xp;
15367 
15368 	ASSERT(bp != NULL);
15369 	ASSERT(un != NULL);
15370 	ASSERT(mutex_owned(SD_MUTEX(un)));
15371 	xp = SD_GET_XBUF(bp);
15372 	ASSERT(xp != NULL);
15373 	ASSERT(errcode != 0);
15374 
15375 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15376 	    "sd_return_failed_command_no_restart: entry\n");
15377 
15378 	/*
15379 	 * b_resid could already be nonzero due to a partial data
15380 	 * transfer, so do not change it here.
15381 	 */
15382 	SD_BIOERROR(bp, errcode);
15383 
15384 	/*
15385 	 * If this is the failfast bp, clear it. This can happen if the
15386 	 * failfast bp encounterd a fatal error when we attempted to
15387 	 * re-try it (such as a scsi_transport(9F) failure).  However
15388 	 * we should NOT be in an active failfast state if the failfast
15389 	 * bp is not NULL.
15390 	 */
15391 	if (bp == un->un_failfast_bp) {
15392 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
15393 		un->un_failfast_bp = NULL;
15394 	}
15395 
15396 	if (bp == un->un_retry_bp) {
15397 		/*
15398 		 * This command was retried one or more times. Show that we are
15399 		 * done with it, and allow processing of the waitq to resume.
15400 		 */
15401 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15402 		    "sd_return_failed_command_no_restart: "
15403 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
15404 		un->un_retry_bp = NULL;
15405 		un->un_retry_statp = NULL;
15406 	}
15407 
15408 	SD_UPDATE_RDWR_STATS(un, bp);
15409 	SD_UPDATE_PARTITION_STATS(un, bp);
15410 
15411 	mutex_exit(SD_MUTEX(un));
15412 
15413 	if (xp->xb_pktp != NULL) {
15414 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
15415 		xp->xb_pktp = NULL;
15416 	}
15417 
15418 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
15419 
15420 	mutex_enter(SD_MUTEX(un));
15421 
15422 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15423 	    "sd_return_failed_command_no_restart: exit\n");
15424 }
15425 
15426 
15427 /*
15428  *    Function: sd_retry_command
15429  *
15430  * Description: queue up a command for retry, or (optionally) fail it
15431  *		if retry counts are exhausted.
15432  *
15433  *   Arguments: un - Pointer to the sd_lun struct for the target.
15434  *
15435  *		bp - Pointer to the buf for the command to be retried.
15436  *
15437  *		retry_check_flag - Flag to see which (if any) of the retry
15438  *		   counts should be decremented/checked. If the indicated
15439  *		   retry count is exhausted, then the command will not be
15440  *		   retried; it will be failed instead. This should use a
15441  *		   value equal to one of the following:
15442  *
15443  *			SD_RETRIES_NOCHECK
15444  *			SD_RESD_RETRIES_STANDARD
15445  *			SD_RETRIES_VICTIM
15446  *
15447  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
15448  *		   if the check should be made to see of FLAG_ISOLATE is set
15449  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
15450  *		   not retried, it is simply failed.
15451  *
15452  *		user_funcp - Ptr to function to call before dispatching the
15453  *		   command. May be NULL if no action needs to be performed.
15454  *		   (Primarily intended for printing messages.)
15455  *
15456  *		user_arg - Optional argument to be passed along to
15457  *		   the user_funcp call.
15458  *
15459  *		failure_code - errno return code to set in the bp if the
15460  *		   command is going to be failed.
15461  *
15462  *		retry_delay - Retry delay interval in (clock_t) units. May
15463  *		   be zero which indicates that the retry should be retried
15464  *		   immediately (ie, without an intervening delay).
15465  *
15466  *		statp - Ptr to kstat function to be updated if the command
15467  *		   is queued for a delayed retry. May be NULL if no kstat
15468  *		   update is desired.
15469  *
15470  *     Context: May be called from interrupt context.
15471  */
15472 
15473 static void
15474 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
15475     void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int code),
15476     void *user_arg, int failure_code, clock_t retry_delay,
15477     void (*statp)(kstat_io_t *))
15478 {
15479 	struct sd_xbuf	*xp;
15480 	struct scsi_pkt	*pktp;
15481 	struct sd_fm_internal *sfip;
15482 
15483 	ASSERT(un != NULL);
15484 	ASSERT(mutex_owned(SD_MUTEX(un)));
15485 	ASSERT(bp != NULL);
15486 	xp = SD_GET_XBUF(bp);
15487 	ASSERT(xp != NULL);
15488 	pktp = SD_GET_PKTP(bp);
15489 	ASSERT(pktp != NULL);
15490 
15491 	sfip = (struct sd_fm_internal *)un->un_fm_private;
15492 	ASSERT(sfip != NULL);
15493 
15494 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15495 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
15496 
15497 	/*
15498 	 * If we are syncing or dumping, fail the command to avoid
15499 	 * recursively calling back into scsi_transport().
15500 	 */
15501 	if (ddi_in_panic()) {
15502 		goto fail_command_no_log;
15503 	}
15504 
15505 	/*
15506 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
15507 	 * log an error and fail the command.
15508 	 */
15509 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
15510 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
15511 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
15512 		sd_dump_memory(un, SD_LOG_IO, "CDB",
15513 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15514 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15515 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15516 		goto fail_command;
15517 	}
15518 
15519 	/*
15520 	 * If we are suspended, then put the command onto head of the
15521 	 * wait queue since we don't want to start more commands, and
15522 	 * clear the un_retry_bp. Next time when we are resumed, will
15523 	 * handle the command in the wait queue.
15524 	 */
15525 	switch (un->un_state) {
15526 	case SD_STATE_SUSPENDED:
15527 	case SD_STATE_DUMPING:
15528 		bp->av_forw = un->un_waitq_headp;
15529 		un->un_waitq_headp = bp;
15530 		if (un->un_waitq_tailp == NULL) {
15531 			un->un_waitq_tailp = bp;
15532 		}
15533 		if (bp == un->un_retry_bp) {
15534 			un->un_retry_bp = NULL;
15535 			un->un_retry_statp = NULL;
15536 		}
15537 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
15538 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
15539 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
15540 		return;
15541 	default:
15542 		break;
15543 	}
15544 
15545 	/*
15546 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
15547 	 * is set; if it is then we do not want to retry the command.
15548 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
15549 	 */
15550 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
15551 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
15552 			goto fail_command;
15553 		}
15554 	}
15555 
15556 
15557 	/*
15558 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
15559 	 * command timeout or a selection timeout has occurred. This means
15560 	 * that we were unable to establish an kind of communication with
15561 	 * the target, and subsequent retries and/or commands are likely
15562 	 * to encounter similar results and take a long time to complete.
15563 	 *
15564 	 * If this is a failfast error condition, we need to update the
15565 	 * failfast state, even if this bp does not have B_FAILFAST set.
15566 	 */
15567 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
15568 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
15569 			ASSERT(un->un_failfast_bp == NULL);
15570 			/*
15571 			 * If we are already in the active failfast state, and
15572 			 * another failfast error condition has been detected,
15573 			 * then fail this command if it has B_FAILFAST set.
15574 			 * If B_FAILFAST is clear, then maintain the legacy
15575 			 * behavior of retrying heroically, even tho this will
15576 			 * take a lot more time to fail the command.
15577 			 */
15578 			if (bp->b_flags & B_FAILFAST) {
15579 				goto fail_command;
15580 			}
15581 		} else {
15582 			/*
15583 			 * We're not in the active failfast state, but we
15584 			 * have a failfast error condition, so we must begin
15585 			 * transition to the next state. We do this regardless
15586 			 * of whether or not this bp has B_FAILFAST set.
15587 			 */
15588 			if (un->un_failfast_bp == NULL) {
15589 				/*
15590 				 * This is the first bp to meet a failfast
15591 				 * condition so save it on un_failfast_bp &
15592 				 * do normal retry processing. Do not enter
15593 				 * active failfast state yet. This marks
15594 				 * entry into the "failfast pending" state.
15595 				 */
15596 				un->un_failfast_bp = bp;
15597 
15598 			} else if (un->un_failfast_bp == bp) {
15599 				/*
15600 				 * This is the second time *this* bp has
15601 				 * encountered a failfast error condition,
15602 				 * so enter active failfast state & flush
15603 				 * queues as appropriate.
15604 				 */
15605 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
15606 				un->un_failfast_bp = NULL;
15607 				sd_failfast_flushq(un);
15608 
15609 				/*
15610 				 * Fail this bp now if B_FAILFAST set;
15611 				 * otherwise continue with retries. (It would
15612 				 * be pretty ironic if this bp succeeded on a
15613 				 * subsequent retry after we just flushed all
15614 				 * the queues).
15615 				 */
15616 				if (bp->b_flags & B_FAILFAST) {
15617 					goto fail_command;
15618 				}
15619 
15620 #if !defined(lint) && !defined(__lint)
15621 			} else {
15622 				/*
15623 				 * If neither of the preceeding conditionals
15624 				 * was true, it means that there is some
15625 				 * *other* bp that has met an inital failfast
15626 				 * condition and is currently either being
15627 				 * retried or is waiting to be retried. In
15628 				 * that case we should perform normal retry
15629 				 * processing on *this* bp, since there is a
15630 				 * chance that the current failfast condition
15631 				 * is transient and recoverable. If that does
15632 				 * not turn out to be the case, then retries
15633 				 * will be cleared when the wait queue is
15634 				 * flushed anyway.
15635 				 */
15636 #endif
15637 			}
15638 		}
15639 	} else {
15640 		/*
15641 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
15642 		 * likely were able to at least establish some level of
15643 		 * communication with the target and subsequent commands
15644 		 * and/or retries are likely to get through to the target,
15645 		 * In this case we want to be aggressive about clearing
15646 		 * the failfast state. Note that this does not affect
15647 		 * the "failfast pending" condition.
15648 		 */
15649 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
15650 	}
15651 
15652 
15653 	/*
15654 	 * Check the specified retry count to see if we can still do
15655 	 * any retries with this pkt before we should fail it.
15656 	 */
15657 	switch (retry_check_flag & SD_RETRIES_MASK) {
15658 	case SD_RETRIES_VICTIM:
15659 		/*
15660 		 * Check the victim retry count. If exhausted, then fall
15661 		 * thru & check against the standard retry count.
15662 		 */
15663 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
15664 			/* Increment count & proceed with the retry */
15665 			xp->xb_victim_retry_count++;
15666 			break;
15667 		}
15668 		/* Victim retries exhausted, fall back to std. retries... */
15669 		/* FALLTHRU */
15670 
15671 	case SD_RETRIES_STANDARD:
15672 		if (xp->xb_retry_count >= un->un_retry_count) {
15673 			/* Retries exhausted, fail the command */
15674 			SD_TRACE(SD_LOG_IO_CORE, un,
15675 			    "sd_retry_command: retries exhausted!\n");
15676 			/*
15677 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
15678 			 * commands with nonzero pkt_resid.
15679 			 */
15680 			if ((pktp->pkt_reason == CMD_CMPLT) &&
15681 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
15682 			    (pktp->pkt_resid != 0)) {
15683 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
15684 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
15685 					SD_UPDATE_B_RESID(bp, pktp);
15686 				}
15687 			}
15688 			goto fail_command;
15689 		}
15690 		xp->xb_retry_count++;
15691 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15692 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15693 		break;
15694 
15695 	case SD_RETRIES_UA:
15696 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
15697 			/* Retries exhausted, fail the command */
15698 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15699 			    "Unit Attention retries exhausted. "
15700 			    "Check the target.\n");
15701 			goto fail_command;
15702 		}
15703 		xp->xb_ua_retry_count++;
15704 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15705 		    "sd_retry_command: retry count:%d\n",
15706 		    xp->xb_ua_retry_count);
15707 		break;
15708 
15709 	case SD_RETRIES_BUSY:
15710 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
15711 			/* Retries exhausted, fail the command */
15712 			SD_TRACE(SD_LOG_IO_CORE, un,
15713 			    "sd_retry_command: retries exhausted!\n");
15714 			goto fail_command;
15715 		}
15716 		xp->xb_retry_count++;
15717 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15718 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
15719 		break;
15720 
15721 	case SD_RETRIES_NOCHECK:
15722 	default:
15723 		/* No retry count to check. Just proceed with the retry */
15724 		break;
15725 	}
15726 
15727 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
15728 
15729 	/*
15730 	 * If this is a non-USCSI command being retried
15731 	 * during execution last time, we should post an ereport with
15732 	 * driver-assessment of the value "retry".
15733 	 * For partial DMA, request sense and STATUS_QFULL, there are no
15734 	 * hardware errors, we bypass ereport posting.
15735 	 */
15736 	if (failure_code != 0) {
15737 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
15738 			sd_ssc_extract_info(&sfip->fm_ssc, un, pktp, bp, xp);
15739 			sd_ssc_post(&sfip->fm_ssc, SD_FM_DRV_RETRY);
15740 		}
15741 	}
15742 
15743 	/*
15744 	 * If we were given a zero timeout, we must attempt to retry the
15745 	 * command immediately (ie, without a delay).
15746 	 */
15747 	if (retry_delay == 0) {
15748 		/*
15749 		 * Check some limiting conditions to see if we can actually
15750 		 * do the immediate retry.  If we cannot, then we must
15751 		 * fall back to queueing up a delayed retry.
15752 		 */
15753 		if (un->un_ncmds_in_transport >= un->un_throttle) {
15754 			/*
15755 			 * We are at the throttle limit for the target,
15756 			 * fall back to delayed retry.
15757 			 */
15758 			retry_delay = un->un_busy_timeout;
15759 			statp = kstat_waitq_enter;
15760 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15761 			    "sd_retry_command: immed. retry hit "
15762 			    "throttle!\n");
15763 		} else {
15764 			/*
15765 			 * We're clear to proceed with the immediate retry.
15766 			 * First call the user-provided function (if any)
15767 			 */
15768 			if (user_funcp != NULL) {
15769 				(*user_funcp)(un, bp, user_arg,
15770 				    SD_IMMEDIATE_RETRY_ISSUED);
15771 #ifdef __lock_lint
15772 				sd_print_incomplete_msg(un, bp, user_arg,
15773 				    SD_IMMEDIATE_RETRY_ISSUED);
15774 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
15775 				    SD_IMMEDIATE_RETRY_ISSUED);
15776 				sd_print_sense_failed_msg(un, bp, user_arg,
15777 				    SD_IMMEDIATE_RETRY_ISSUED);
15778 #endif
15779 			}
15780 
15781 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15782 			    "sd_retry_command: issuing immediate retry\n");
15783 
15784 			/*
15785 			 * Call sd_start_cmds() to transport the command to
15786 			 * the target.
15787 			 */
15788 			sd_start_cmds(un, bp);
15789 
15790 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15791 			    "sd_retry_command exit\n");
15792 			return;
15793 		}
15794 	}
15795 
15796 	/*
15797 	 * Set up to retry the command after a delay.
15798 	 * First call the user-provided function (if any)
15799 	 */
15800 	if (user_funcp != NULL) {
15801 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
15802 	}
15803 
15804 	sd_set_retry_bp(un, bp, retry_delay, statp);
15805 
15806 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15807 	return;
15808 
15809 fail_command:
15810 
15811 	if (user_funcp != NULL) {
15812 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
15813 	}
15814 
15815 fail_command_no_log:
15816 
15817 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15818 	    "sd_retry_command: returning failed command\n");
15819 
15820 	sd_return_failed_command(un, bp, failure_code);
15821 
15822 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
15823 }
15824 
15825 
15826 /*
15827  *    Function: sd_set_retry_bp
15828  *
15829  * Description: Set up the given bp for retry.
15830  *
15831  *   Arguments: un - ptr to associated softstate
15832  *		bp - ptr to buf(9S) for the command
15833  *		retry_delay - time interval before issuing retry (may be 0)
15834  *		statp - optional pointer to kstat function
15835  *
15836  *     Context: May be called under interrupt context
15837  */
15838 
15839 static void
15840 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
15841     void (*statp)(kstat_io_t *))
15842 {
15843 	ASSERT(un != NULL);
15844 	ASSERT(mutex_owned(SD_MUTEX(un)));
15845 	ASSERT(bp != NULL);
15846 
15847 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
15848 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
15849 
15850 	/*
15851 	 * Indicate that the command is being retried. This will not allow any
15852 	 * other commands on the wait queue to be transported to the target
15853 	 * until this command has been completed (success or failure). The
15854 	 * "retry command" is not transported to the target until the given
15855 	 * time delay expires, unless the user specified a 0 retry_delay.
15856 	 *
15857 	 * Note: the timeout(9F) callback routine is what actually calls
15858 	 * sd_start_cmds() to transport the command, with the exception of a
15859 	 * zero retry_delay. The only current implementor of a zero retry delay
15860 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
15861 	 */
15862 	if (un->un_retry_bp == NULL) {
15863 		ASSERT(un->un_retry_statp == NULL);
15864 		un->un_retry_bp = bp;
15865 
15866 		/*
15867 		 * If the user has not specified a delay the command should
15868 		 * be queued and no timeout should be scheduled.
15869 		 */
15870 		if (retry_delay == 0) {
15871 			/*
15872 			 * Save the kstat pointer that will be used in the
15873 			 * call to SD_UPDATE_KSTATS() below, so that
15874 			 * sd_start_cmds() can correctly decrement the waitq
15875 			 * count when it is time to transport this command.
15876 			 */
15877 			un->un_retry_statp = statp;
15878 			goto done;
15879 		}
15880 	}
15881 
15882 	if (un->un_retry_bp == bp) {
15883 		/*
15884 		 * Save the kstat pointer that will be used in the call to
15885 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
15886 		 * correctly decrement the waitq count when it is time to
15887 		 * transport this command.
15888 		 */
15889 		un->un_retry_statp = statp;
15890 
15891 		/*
15892 		 * Schedule a timeout if:
15893 		 *   1) The user has specified a delay.
15894 		 *   2) There is not a START_STOP_UNIT callback pending.
15895 		 *
15896 		 * If no delay has been specified, then it is up to the caller
15897 		 * to ensure that IO processing continues without stalling.
15898 		 * Effectively, this means that the caller will issue the
15899 		 * required call to sd_start_cmds(). The START_STOP_UNIT
15900 		 * callback does this after the START STOP UNIT command has
15901 		 * completed. In either of these cases we should not schedule
15902 		 * a timeout callback here.  Also don't schedule the timeout if
15903 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
15904 		 */
15905 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
15906 		    (un->un_direct_priority_timeid == NULL)) {
15907 			un->un_retry_timeid =
15908 			    timeout(sd_start_retry_command, un, retry_delay);
15909 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15910 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
15911 			    " bp:0x%p un_retry_timeid:0x%p\n",
15912 			    un, bp, un->un_retry_timeid);
15913 		}
15914 	} else {
15915 		/*
15916 		 * We only get in here if there is already another command
15917 		 * waiting to be retried.  In this case, we just put the
15918 		 * given command onto the wait queue, so it can be transported
15919 		 * after the current retry command has completed.
15920 		 *
15921 		 * Also we have to make sure that if the command at the head
15922 		 * of the wait queue is the un_failfast_bp, that we do not
15923 		 * put ahead of it any other commands that are to be retried.
15924 		 */
15925 		if ((un->un_failfast_bp != NULL) &&
15926 		    (un->un_failfast_bp == un->un_waitq_headp)) {
15927 			/*
15928 			 * Enqueue this command AFTER the first command on
15929 			 * the wait queue (which is also un_failfast_bp).
15930 			 */
15931 			bp->av_forw = un->un_waitq_headp->av_forw;
15932 			un->un_waitq_headp->av_forw = bp;
15933 			if (un->un_waitq_headp == un->un_waitq_tailp) {
15934 				un->un_waitq_tailp = bp;
15935 			}
15936 		} else {
15937 			/* Enqueue this command at the head of the waitq. */
15938 			bp->av_forw = un->un_waitq_headp;
15939 			un->un_waitq_headp = bp;
15940 			if (un->un_waitq_tailp == NULL) {
15941 				un->un_waitq_tailp = bp;
15942 			}
15943 		}
15944 
15945 		if (statp == NULL) {
15946 			statp = kstat_waitq_enter;
15947 		}
15948 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15949 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
15950 	}
15951 
15952 done:
15953 	if (statp != NULL) {
15954 		SD_UPDATE_KSTATS(un, statp, bp);
15955 	}
15956 
15957 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15958 	    "sd_set_retry_bp: exit un:0x%p\n", un);
15959 }
15960 
15961 
15962 /*
15963  *    Function: sd_start_retry_command
15964  *
15965  * Description: Start the command that has been waiting on the target's
15966  *		retry queue.  Called from timeout(9F) context after the
15967  *		retry delay interval has expired.
15968  *
15969  *   Arguments: arg - pointer to associated softstate for the device.
15970  *
15971  *     Context: timeout(9F) thread context.  May not sleep.
15972  */
15973 
15974 static void
15975 sd_start_retry_command(void *arg)
15976 {
15977 	struct sd_lun *un = arg;
15978 
15979 	ASSERT(un != NULL);
15980 	ASSERT(!mutex_owned(SD_MUTEX(un)));
15981 
15982 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15983 	    "sd_start_retry_command: entry\n");
15984 
15985 	mutex_enter(SD_MUTEX(un));
15986 
15987 	un->un_retry_timeid = NULL;
15988 
15989 	if (un->un_retry_bp != NULL) {
15990 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15991 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
15992 		    un, un->un_retry_bp);
15993 		sd_start_cmds(un, un->un_retry_bp);
15994 	}
15995 
15996 	mutex_exit(SD_MUTEX(un));
15997 
15998 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15999 	    "sd_start_retry_command: exit\n");
16000 }
16001 
16002 /*
16003  *    Function: sd_rmw_msg_print_handler
16004  *
16005  * Description: If RMW mode is enabled and warning message is triggered
16006  *              print I/O count during a fixed interval.
16007  *
16008  *   Arguments: arg - pointer to associated softstate for the device.
16009  *
16010  *     Context: timeout(9F) thread context. May not sleep.
16011  */
16012 static void
16013 sd_rmw_msg_print_handler(void *arg)
16014 {
16015 	struct sd_lun *un = arg;
16016 
16017 	ASSERT(un != NULL);
16018 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16019 
16020 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16021 	    "sd_rmw_msg_print_handler: entry\n");
16022 
16023 	mutex_enter(SD_MUTEX(un));
16024 
16025 	if (un->un_rmw_incre_count > 0) {
16026 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16027 		    "%"PRIu64" I/O requests are not aligned with %d disk "
16028 		    "sector size in %ld seconds. They are handled through "
16029 		    "Read Modify Write but the performance is very low!\n",
16030 		    un->un_rmw_incre_count, un->un_tgt_blocksize,
16031 		    drv_hztousec(SD_RMW_MSG_PRINT_TIMEOUT) / 1000000);
16032 		un->un_rmw_incre_count = 0;
16033 		un->un_rmw_msg_timeid = timeout(sd_rmw_msg_print_handler,
16034 		    un, SD_RMW_MSG_PRINT_TIMEOUT);
16035 	} else {
16036 		un->un_rmw_msg_timeid = NULL;
16037 	}
16038 
16039 	mutex_exit(SD_MUTEX(un));
16040 
16041 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16042 	    "sd_rmw_msg_print_handler: exit\n");
16043 }
16044 
16045 /*
16046  *    Function: sd_start_direct_priority_command
16047  *
16048  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
16049  *		received TRAN_BUSY when we called scsi_transport() to send it
16050  *		to the underlying HBA. This function is called from timeout(9F)
16051  *		context after the delay interval has expired.
16052  *
16053  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
16054  *
16055  *     Context: timeout(9F) thread context.  May not sleep.
16056  */
16057 
16058 static void
16059 sd_start_direct_priority_command(void *arg)
16060 {
16061 	struct buf	*priority_bp = arg;
16062 	struct sd_lun	*un;
16063 
16064 	ASSERT(priority_bp != NULL);
16065 	un = SD_GET_UN(priority_bp);
16066 	ASSERT(un != NULL);
16067 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16068 
16069 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16070 	    "sd_start_direct_priority_command: entry\n");
16071 
16072 	mutex_enter(SD_MUTEX(un));
16073 	un->un_direct_priority_timeid = NULL;
16074 	sd_start_cmds(un, priority_bp);
16075 	mutex_exit(SD_MUTEX(un));
16076 
16077 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16078 	    "sd_start_direct_priority_command: exit\n");
16079 }
16080 
16081 
16082 /*
16083  *    Function: sd_send_request_sense_command
16084  *
16085  * Description: Sends a REQUEST SENSE command to the target
16086  *
16087  *     Context: May be called from interrupt context.
16088  */
16089 
16090 static void
16091 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
16092     struct scsi_pkt *pktp)
16093 {
16094 	ASSERT(bp != NULL);
16095 	ASSERT(un != NULL);
16096 	ASSERT(mutex_owned(SD_MUTEX(un)));
16097 
16098 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
16099 	    "entry: buf:0x%p\n", bp);
16100 
16101 	/*
16102 	 * If we are syncing or dumping, then fail the command to avoid a
16103 	 * recursive callback into scsi_transport(). Also fail the command
16104 	 * if we are suspended (legacy behavior).
16105 	 */
16106 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
16107 	    (un->un_state == SD_STATE_DUMPING)) {
16108 		sd_return_failed_command(un, bp, EIO);
16109 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16110 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
16111 		return;
16112 	}
16113 
16114 	/*
16115 	 * Retry the failed command and don't issue the request sense if:
16116 	 *    1) the sense buf is busy
16117 	 *    2) we have 1 or more outstanding commands on the target
16118 	 *    (the sense data will be cleared or invalidated any way)
16119 	 *
16120 	 * Note: There could be an issue with not checking a retry limit here,
16121 	 * the problem is determining which retry limit to check.
16122 	 */
16123 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
16124 		/* Don't retry if the command is flagged as non-retryable */
16125 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
16126 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
16127 			    NULL, NULL, 0, un->un_busy_timeout,
16128 			    kstat_waitq_enter);
16129 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16130 			    "sd_send_request_sense_command: "
16131 			    "at full throttle, retrying exit\n");
16132 		} else {
16133 			sd_return_failed_command(un, bp, EIO);
16134 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16135 			    "sd_send_request_sense_command: "
16136 			    "at full throttle, non-retryable exit\n");
16137 		}
16138 		return;
16139 	}
16140 
16141 	sd_mark_rqs_busy(un, bp);
16142 	sd_start_cmds(un, un->un_rqs_bp);
16143 
16144 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16145 	    "sd_send_request_sense_command: exit\n");
16146 }
16147 
16148 
16149 /*
16150  *    Function: sd_mark_rqs_busy
16151  *
16152  * Description: Indicate that the request sense bp for this instance is
16153  *		in use.
16154  *
16155  *     Context: May be called under interrupt context
16156  */
16157 
16158 static void
16159 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
16160 {
16161 	struct sd_xbuf	*sense_xp;
16162 
16163 	ASSERT(un != NULL);
16164 	ASSERT(bp != NULL);
16165 	ASSERT(mutex_owned(SD_MUTEX(un)));
16166 	ASSERT(un->un_sense_isbusy == 0);
16167 
16168 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
16169 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
16170 
16171 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
16172 	ASSERT(sense_xp != NULL);
16173 
16174 	SD_INFO(SD_LOG_IO, un,
16175 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
16176 
16177 	ASSERT(sense_xp->xb_pktp != NULL);
16178 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
16179 	    == (FLAG_SENSING | FLAG_HEAD));
16180 
16181 	un->un_sense_isbusy = 1;
16182 	un->un_rqs_bp->b_resid = 0;
16183 	sense_xp->xb_pktp->pkt_resid  = 0;
16184 	sense_xp->xb_pktp->pkt_reason = 0;
16185 
16186 	/* So we can get back the bp at interrupt time! */
16187 	sense_xp->xb_sense_bp = bp;
16188 
16189 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
16190 
16191 	/*
16192 	 * Mark this buf as awaiting sense data. (This is already set in
16193 	 * the pkt_flags for the RQS packet.)
16194 	 */
16195 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
16196 
16197 	/* Request sense down same path */
16198 	if (scsi_pkt_allocated_correctly((SD_GET_XBUF(bp))->xb_pktp) &&
16199 	    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance)
16200 		sense_xp->xb_pktp->pkt_path_instance =
16201 		    ((SD_GET_XBUF(bp))->xb_pktp)->pkt_path_instance;
16202 
16203 	sense_xp->xb_retry_count = 0;
16204 	sense_xp->xb_victim_retry_count = 0;
16205 	sense_xp->xb_ua_retry_count = 0;
16206 	sense_xp->xb_nr_retry_count = 0;
16207 	sense_xp->xb_dma_resid  = 0;
16208 
16209 	/* Clean up the fields for auto-request sense */
16210 	sense_xp->xb_sense_status = 0;
16211 	sense_xp->xb_sense_state = 0;
16212 	sense_xp->xb_sense_resid = 0;
16213 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
16214 
16215 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
16216 }
16217 
16218 
16219 /*
16220  *    Function: sd_mark_rqs_idle
16221  *
16222  * Description: SD_MUTEX must be held continuously through this routine
16223  *		to prevent reuse of the rqs struct before the caller can
16224  *		complete it's processing.
16225  *
16226  * Return Code: Pointer to the RQS buf
16227  *
16228  *     Context: May be called under interrupt context
16229  */
16230 
16231 static struct buf *
16232 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
16233 {
16234 	struct buf *bp;
16235 	ASSERT(un != NULL);
16236 	ASSERT(sense_xp != NULL);
16237 	ASSERT(mutex_owned(SD_MUTEX(un)));
16238 	ASSERT(un->un_sense_isbusy != 0);
16239 
16240 	un->un_sense_isbusy = 0;
16241 	bp = sense_xp->xb_sense_bp;
16242 	sense_xp->xb_sense_bp = NULL;
16243 
16244 	/* This pkt is no longer interested in getting sense data */
16245 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
16246 
16247 	return (bp);
16248 }
16249 
16250 
16251 
16252 /*
16253  *    Function: sd_alloc_rqs
16254  *
16255  * Description: Set up the unit to receive auto request sense data
16256  *
16257  * Return Code: DDI_SUCCESS or DDI_FAILURE
16258  *
16259  *     Context: Called under attach(9E) context
16260  */
16261 
16262 static int
16263 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
16264 {
16265 	struct sd_xbuf *xp;
16266 
16267 	ASSERT(un != NULL);
16268 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16269 	ASSERT(un->un_rqs_bp == NULL);
16270 	ASSERT(un->un_rqs_pktp == NULL);
16271 
16272 	/*
16273 	 * First allocate the required buf and scsi_pkt structs, then set up
16274 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
16275 	 */
16276 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
16277 	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
16278 	if (un->un_rqs_bp == NULL) {
16279 		return (DDI_FAILURE);
16280 	}
16281 
16282 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
16283 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
16284 
16285 	if (un->un_rqs_pktp == NULL) {
16286 		sd_free_rqs(un);
16287 		return (DDI_FAILURE);
16288 	}
16289 
16290 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
16291 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
16292 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
16293 
16294 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
16295 
16296 	/* Set up the other needed members in the ARQ scsi_pkt. */
16297 	un->un_rqs_pktp->pkt_comp   = sdintr;
16298 	un->un_rqs_pktp->pkt_time   = sd_io_time;
16299 	un->un_rqs_pktp->pkt_flags |=
16300 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
16301 
16302 	/*
16303 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
16304 	 * provide any intpkt, destroypkt routines as we take care of
16305 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
16306 	 */
16307 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
16308 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
16309 	xp->xb_pktp = un->un_rqs_pktp;
16310 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
16311 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
16312 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
16313 
16314 	/*
16315 	 * Save the pointer to the request sense private bp so it can
16316 	 * be retrieved in sdintr.
16317 	 */
16318 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
16319 	ASSERT(un->un_rqs_bp->b_private == xp);
16320 
16321 	/*
16322 	 * See if the HBA supports auto-request sense for the specified
16323 	 * target/lun. If it does, then try to enable it (if not already
16324 	 * enabled).
16325 	 *
16326 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
16327 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
16328 	 * return success.  However, in both of these cases ARQ is always
16329 	 * enabled and scsi_ifgetcap will always return true. The best approach
16330 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
16331 	 *
16332 	 * The 3rd case is the HBA (adp) always return enabled on
16333 	 * scsi_ifgetgetcap even when it's not enable, the best approach
16334 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
16335 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
16336 	 */
16337 
16338 	if (un->un_f_is_fibre == TRUE) {
16339 		un->un_f_arq_enabled = TRUE;
16340 	} else {
16341 #if defined(__x86)
16342 		/*
16343 		 * Circumvent the Adaptec bug, remove this code when
16344 		 * the bug is fixed
16345 		 */
16346 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
16347 #endif
16348 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
16349 		case 0:
16350 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16351 			    "sd_alloc_rqs: HBA supports ARQ\n");
16352 			/*
16353 			 * ARQ is supported by this HBA but currently is not
16354 			 * enabled. Attempt to enable it and if successful then
16355 			 * mark this instance as ARQ enabled.
16356 			 */
16357 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
16358 			    == 1) {
16359 				/* Successfully enabled ARQ in the HBA */
16360 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16361 				    "sd_alloc_rqs: ARQ enabled\n");
16362 				un->un_f_arq_enabled = TRUE;
16363 			} else {
16364 				/* Could not enable ARQ in the HBA */
16365 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
16366 				    "sd_alloc_rqs: failed ARQ enable\n");
16367 				un->un_f_arq_enabled = FALSE;
16368 			}
16369 			break;
16370 		case 1:
16371 			/*
16372 			 * ARQ is supported by this HBA and is already enabled.
16373 			 * Just mark ARQ as enabled for this instance.
16374 			 */
16375 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16376 			    "sd_alloc_rqs: ARQ already enabled\n");
16377 			un->un_f_arq_enabled = TRUE;
16378 			break;
16379 		default:
16380 			/*
16381 			 * ARQ is not supported by this HBA; disable it for this
16382 			 * instance.
16383 			 */
16384 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
16385 			    "sd_alloc_rqs: HBA does not support ARQ\n");
16386 			un->un_f_arq_enabled = FALSE;
16387 			break;
16388 		}
16389 	}
16390 
16391 	return (DDI_SUCCESS);
16392 }
16393 
16394 
16395 /*
16396  *    Function: sd_free_rqs
16397  *
16398  * Description: Cleanup for the pre-instance RQS command.
16399  *
16400  *     Context: Kernel thread context
16401  */
16402 
16403 static void
16404 sd_free_rqs(struct sd_lun *un)
16405 {
16406 	ASSERT(un != NULL);
16407 
16408 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
16409 
16410 	/*
16411 	 * If consistent memory is bound to a scsi_pkt, the pkt
16412 	 * has to be destroyed *before* freeing the consistent memory.
16413 	 * Don't change the sequence of this operations.
16414 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
16415 	 * after it was freed in scsi_free_consistent_buf().
16416 	 */
16417 	if (un->un_rqs_pktp != NULL) {
16418 		scsi_destroy_pkt(un->un_rqs_pktp);
16419 		un->un_rqs_pktp = NULL;
16420 	}
16421 
16422 	if (un->un_rqs_bp != NULL) {
16423 		struct sd_xbuf *xp = SD_GET_XBUF(un->un_rqs_bp);
16424 		if (xp != NULL) {
16425 			kmem_free(xp, sizeof (struct sd_xbuf));
16426 		}
16427 		scsi_free_consistent_buf(un->un_rqs_bp);
16428 		un->un_rqs_bp = NULL;
16429 	}
16430 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
16431 }
16432 
16433 
16434 
16435 /*
16436  *    Function: sd_reduce_throttle
16437  *
16438  * Description: Reduces the maximum # of outstanding commands on a
16439  *		target to the current number of outstanding commands.
16440  *		Queues a tiemout(9F) callback to restore the limit
16441  *		after a specified interval has elapsed.
16442  *		Typically used when we get a TRAN_BUSY return code
16443  *		back from scsi_transport().
16444  *
16445  *   Arguments: un - ptr to the sd_lun softstate struct
16446  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
16447  *
16448  *     Context: May be called from interrupt context
16449  */
16450 
16451 static void
16452 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
16453 {
16454 	ASSERT(un != NULL);
16455 	ASSERT(mutex_owned(SD_MUTEX(un)));
16456 	ASSERT(un->un_ncmds_in_transport >= 0);
16457 
16458 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16459 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
16460 	    un, un->un_throttle, un->un_ncmds_in_transport);
16461 
16462 	if (un->un_throttle > 1) {
16463 		if (un->un_f_use_adaptive_throttle == TRUE) {
16464 			switch (throttle_type) {
16465 			case SD_THROTTLE_TRAN_BUSY:
16466 				if (un->un_busy_throttle == 0) {
16467 					un->un_busy_throttle = un->un_throttle;
16468 				}
16469 				break;
16470 			case SD_THROTTLE_QFULL:
16471 				un->un_busy_throttle = 0;
16472 				break;
16473 			default:
16474 				ASSERT(FALSE);
16475 			}
16476 
16477 			if (un->un_ncmds_in_transport > 0) {
16478 				un->un_throttle = un->un_ncmds_in_transport;
16479 			}
16480 
16481 		} else {
16482 			if (un->un_ncmds_in_transport == 0) {
16483 				un->un_throttle = 1;
16484 			} else {
16485 				un->un_throttle = un->un_ncmds_in_transport;
16486 			}
16487 		}
16488 	}
16489 
16490 	/* Reschedule the timeout if none is currently active */
16491 	if (un->un_reset_throttle_timeid == NULL) {
16492 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
16493 		    un, SD_THROTTLE_RESET_INTERVAL);
16494 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16495 		    "sd_reduce_throttle: timeout scheduled!\n");
16496 	}
16497 
16498 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
16499 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16500 }
16501 
16502 
16503 
16504 /*
16505  *    Function: sd_restore_throttle
16506  *
16507  * Description: Callback function for timeout(9F).  Resets the current
16508  *		value of un->un_throttle to its default.
16509  *
16510  *   Arguments: arg - pointer to associated softstate for the device.
16511  *
16512  *     Context: May be called from interrupt context
16513  */
16514 
16515 static void
16516 sd_restore_throttle(void *arg)
16517 {
16518 	struct sd_lun	*un = arg;
16519 
16520 	ASSERT(un != NULL);
16521 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16522 
16523 	mutex_enter(SD_MUTEX(un));
16524 
16525 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16526 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
16527 
16528 	un->un_reset_throttle_timeid = NULL;
16529 
16530 	if (un->un_f_use_adaptive_throttle == TRUE) {
16531 		/*
16532 		 * If un_busy_throttle is nonzero, then it contains the
16533 		 * value that un_throttle was when we got a TRAN_BUSY back
16534 		 * from scsi_transport(). We want to revert back to this
16535 		 * value.
16536 		 *
16537 		 * In the QFULL case, the throttle limit will incrementally
16538 		 * increase until it reaches max throttle.
16539 		 */
16540 		if (un->un_busy_throttle > 0) {
16541 			un->un_throttle = un->un_busy_throttle;
16542 			un->un_busy_throttle = 0;
16543 		} else {
16544 			/*
16545 			 * increase throttle by 10% open gate slowly, schedule
16546 			 * another restore if saved throttle has not been
16547 			 * reached
16548 			 */
16549 			short throttle;
16550 			if (sd_qfull_throttle_enable) {
16551 				throttle = un->un_throttle +
16552 				    max((un->un_throttle / 10), 1);
16553 				un->un_throttle =
16554 				    (throttle < un->un_saved_throttle) ?
16555 				    throttle : un->un_saved_throttle;
16556 				if (un->un_throttle < un->un_saved_throttle) {
16557 					un->un_reset_throttle_timeid =
16558 					    timeout(sd_restore_throttle,
16559 					    un,
16560 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
16561 				}
16562 			}
16563 		}
16564 
16565 		/*
16566 		 * If un_throttle has fallen below the low-water mark, we
16567 		 * restore the maximum value here (and allow it to ratchet
16568 		 * down again if necessary).
16569 		 */
16570 		if (un->un_throttle < un->un_min_throttle) {
16571 			un->un_throttle = un->un_saved_throttle;
16572 		}
16573 	} else {
16574 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
16575 		    "restoring limit from 0x%x to 0x%x\n",
16576 		    un->un_throttle, un->un_saved_throttle);
16577 		un->un_throttle = un->un_saved_throttle;
16578 	}
16579 
16580 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16581 	    "sd_restore_throttle: calling sd_start_cmds!\n");
16582 
16583 	sd_start_cmds(un, NULL);
16584 
16585 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
16586 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
16587 	    un, un->un_throttle);
16588 
16589 	mutex_exit(SD_MUTEX(un));
16590 
16591 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
16592 }
16593 
16594 /*
16595  *    Function: sdrunout
16596  *
16597  * Description: Callback routine for scsi_init_pkt when a resource allocation
16598  *		fails.
16599  *
16600  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
16601  *		soft state instance.
16602  *
16603  * Return Code: The scsi_init_pkt routine allows for the callback function to
16604  *		return a 0 indicating the callback should be rescheduled or a 1
16605  *		indicating not to reschedule. This routine always returns 1
16606  *		because the driver always provides a callback function to
16607  *		scsi_init_pkt. This results in a callback always being scheduled
16608  *		(via the scsi_init_pkt callback implementation) if a resource
16609  *		failure occurs.
16610  *
16611  *     Context: This callback function may not block or call routines that block
16612  *
16613  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
16614  *		request persisting at the head of the list which cannot be
16615  *		satisfied even after multiple retries. In the future the driver
16616  *		may implement some time of maximum runout count before failing
16617  *		an I/O.
16618  */
16619 
16620 static int
16621 sdrunout(caddr_t arg)
16622 {
16623 	struct sd_lun	*un = (struct sd_lun *)arg;
16624 
16625 	ASSERT(un != NULL);
16626 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16627 
16628 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
16629 
16630 	mutex_enter(SD_MUTEX(un));
16631 	sd_start_cmds(un, NULL);
16632 	mutex_exit(SD_MUTEX(un));
16633 	/*
16634 	 * This callback routine always returns 1 (i.e. do not reschedule)
16635 	 * because we always specify sdrunout as the callback handler for
16636 	 * scsi_init_pkt inside the call to sd_start_cmds.
16637 	 */
16638 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
16639 	return (1);
16640 }
16641 
16642 
16643 /*
16644  *    Function: sdintr
16645  *
16646  * Description: Completion callback routine for scsi_pkt(9S) structs
16647  *		sent to the HBA driver via scsi_transport(9F).
16648  *
16649  *     Context: Interrupt context
16650  */
16651 
16652 static void
16653 sdintr(struct scsi_pkt *pktp)
16654 {
16655 	struct buf	*bp;
16656 	struct sd_xbuf	*xp;
16657 	struct sd_lun	*un;
16658 	size_t		actual_len;
16659 	sd_ssc_t	*sscp;
16660 
16661 	ASSERT(pktp != NULL);
16662 	bp = (struct buf *)pktp->pkt_private;
16663 	ASSERT(bp != NULL);
16664 	xp = SD_GET_XBUF(bp);
16665 	ASSERT(xp != NULL);
16666 	ASSERT(xp->xb_pktp != NULL);
16667 	un = SD_GET_UN(bp);
16668 	ASSERT(un != NULL);
16669 	ASSERT(!mutex_owned(SD_MUTEX(un)));
16670 
16671 #ifdef SD_FAULT_INJECTION
16672 
16673 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
16674 	/* SD FaultInjection */
16675 	sd_faultinjection(pktp);
16676 
16677 #endif /* SD_FAULT_INJECTION */
16678 
16679 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
16680 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
16681 
16682 	mutex_enter(SD_MUTEX(un));
16683 
16684 	ASSERT(un->un_fm_private != NULL);
16685 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
16686 	ASSERT(sscp != NULL);
16687 
16688 	/* Reduce the count of the #commands currently in transport */
16689 	un->un_ncmds_in_transport--;
16690 	ASSERT(un->un_ncmds_in_transport >= 0);
16691 
16692 	/* Increment counter to indicate that the callback routine is active */
16693 	un->un_in_callback++;
16694 
16695 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
16696 
16697 #ifdef	SDDEBUG
16698 	if (bp == un->un_retry_bp) {
16699 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
16700 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
16701 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
16702 	}
16703 #endif
16704 
16705 	/*
16706 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
16707 	 * state if needed.
16708 	 */
16709 	if (pktp->pkt_reason == CMD_DEV_GONE) {
16710 		/* Prevent multiple console messages for the same failure. */
16711 		if (un->un_last_pkt_reason != CMD_DEV_GONE) {
16712 			un->un_last_pkt_reason = CMD_DEV_GONE;
16713 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16714 			    "Command failed to complete...Device is gone\n");
16715 		}
16716 		if (un->un_mediastate != DKIO_DEV_GONE) {
16717 			un->un_mediastate = DKIO_DEV_GONE;
16718 			cv_broadcast(&un->un_state_cv);
16719 		}
16720 		/*
16721 		 * If the command happens to be the REQUEST SENSE command,
16722 		 * free up the rqs buf and fail the original command.
16723 		 */
16724 		if (bp == un->un_rqs_bp) {
16725 			bp = sd_mark_rqs_idle(un, xp);
16726 		}
16727 		sd_return_failed_command(un, bp, EIO);
16728 		goto exit;
16729 	}
16730 
16731 	if (pktp->pkt_state & STATE_XARQ_DONE) {
16732 		SD_TRACE(SD_LOG_COMMON, un,
16733 		    "sdintr: extra sense data received. pkt=%p\n", pktp);
16734 	}
16735 
16736 	/*
16737 	 * First see if the pkt has auto-request sense data with it....
16738 	 * Look at the packet state first so we don't take a performance
16739 	 * hit looking at the arq enabled flag unless absolutely necessary.
16740 	 */
16741 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
16742 	    (un->un_f_arq_enabled == TRUE)) {
16743 		/*
16744 		 * The HBA did an auto request sense for this command so check
16745 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16746 		 * driver command that should not be retried.
16747 		 */
16748 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16749 			/*
16750 			 * Save the relevant sense info into the xp for the
16751 			 * original cmd.
16752 			 */
16753 			struct scsi_arq_status *asp;
16754 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
16755 			xp->xb_sense_status =
16756 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
16757 			xp->xb_sense_state  = asp->sts_rqpkt_state;
16758 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
16759 			if (pktp->pkt_state & STATE_XARQ_DONE) {
16760 				actual_len = MAX_SENSE_LENGTH -
16761 				    xp->xb_sense_resid;
16762 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16763 				    MAX_SENSE_LENGTH);
16764 			} else {
16765 				if (xp->xb_sense_resid > SENSE_LENGTH) {
16766 					actual_len = MAX_SENSE_LENGTH -
16767 					    xp->xb_sense_resid;
16768 				} else {
16769 					actual_len = SENSE_LENGTH -
16770 					    xp->xb_sense_resid;
16771 				}
16772 				if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16773 					if ((((struct uscsi_cmd *)
16774 					    (xp->xb_pktinfo))->uscsi_rqlen) >
16775 					    actual_len) {
16776 						xp->xb_sense_resid =
16777 						    (((struct uscsi_cmd *)
16778 						    (xp->xb_pktinfo))->
16779 						    uscsi_rqlen) - actual_len;
16780 					} else {
16781 						xp->xb_sense_resid = 0;
16782 					}
16783 				}
16784 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
16785 				    SENSE_LENGTH);
16786 			}
16787 
16788 			/* fail the command */
16789 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16790 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
16791 			sd_return_failed_command(un, bp, EIO);
16792 			goto exit;
16793 		}
16794 
16795 #if (defined(__x86))	/* DMAFREE for x86 only */
16796 		/*
16797 		 * We want to either retry or fail this command, so free
16798 		 * the DMA resources here.  If we retry the command then
16799 		 * the DMA resources will be reallocated in sd_start_cmds().
16800 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
16801 		 * causes the *entire* transfer to start over again from the
16802 		 * beginning of the request, even for PARTIAL chunks that
16803 		 * have already transferred successfully.
16804 		 */
16805 		if ((un->un_f_is_fibre == TRUE) &&
16806 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16807 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16808 			scsi_dmafree(pktp);
16809 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16810 		}
16811 #endif
16812 
16813 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16814 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
16815 
16816 		sd_handle_auto_request_sense(un, bp, xp, pktp);
16817 		goto exit;
16818 	}
16819 
16820 	/* Next see if this is the REQUEST SENSE pkt for the instance */
16821 	if (pktp->pkt_flags & FLAG_SENSING)  {
16822 		/* This pktp is from the unit's REQUEST_SENSE command */
16823 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16824 		    "sdintr: sd_handle_request_sense\n");
16825 		sd_handle_request_sense(un, bp, xp, pktp);
16826 		goto exit;
16827 	}
16828 
16829 	/*
16830 	 * Check to see if the command successfully completed as requested;
16831 	 * this is the most common case (and also the hot performance path).
16832 	 *
16833 	 * Requirements for successful completion are:
16834 	 * pkt_reason is CMD_CMPLT and packet status is status good.
16835 	 * In addition:
16836 	 * - A residual of zero indicates successful completion no matter what
16837 	 *   the command is.
16838 	 * - If the residual is not zero and the command is not a read or
16839 	 *   write, then it's still defined as successful completion. In other
16840 	 *   words, if the command is a read or write the residual must be
16841 	 *   zero for successful completion.
16842 	 * - If the residual is not zero and the command is a read or
16843 	 *   write, and it's a USCSICMD, then it's still defined as
16844 	 *   successful completion.
16845 	 */
16846 	if ((pktp->pkt_reason == CMD_CMPLT) &&
16847 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
16848 
16849 		/*
16850 		 * Return all USCSI commands on good status
16851 		 */
16852 		if (pktp->pkt_resid == 0) {
16853 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16854 			    "sdintr: returning command for resid == 0\n");
16855 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
16856 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
16857 			SD_UPDATE_B_RESID(bp, pktp);
16858 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16859 			    "sdintr: returning command for resid != 0\n");
16860 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
16861 			SD_UPDATE_B_RESID(bp, pktp);
16862 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16863 			    "sdintr: returning uscsi command\n");
16864 		} else {
16865 			goto not_successful;
16866 		}
16867 		sd_return_command(un, bp);
16868 
16869 		/*
16870 		 * Decrement counter to indicate that the callback routine
16871 		 * is done.
16872 		 */
16873 		un->un_in_callback--;
16874 		ASSERT(un->un_in_callback >= 0);
16875 		mutex_exit(SD_MUTEX(un));
16876 
16877 		return;
16878 	}
16879 
16880 not_successful:
16881 
16882 #if (defined(__x86))	/* DMAFREE for x86 only */
16883 	/*
16884 	 * The following is based upon knowledge of the underlying transport
16885 	 * and its use of DMA resources.  This code should be removed when
16886 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
16887 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
16888 	 * and sd_start_cmds().
16889 	 *
16890 	 * Free any DMA resources associated with this command if there
16891 	 * is a chance it could be retried or enqueued for later retry.
16892 	 * If we keep the DMA binding then mpxio cannot reissue the
16893 	 * command on another path whenever a path failure occurs.
16894 	 *
16895 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
16896 	 * causes the *entire* transfer to start over again from the
16897 	 * beginning of the request, even for PARTIAL chunks that
16898 	 * have already transferred successfully.
16899 	 *
16900 	 * This is only done for non-uscsi commands (and also skipped for the
16901 	 * driver's internal RQS command). Also just do this for Fibre Channel
16902 	 * devices as these are the only ones that support mpxio.
16903 	 */
16904 	if ((un->un_f_is_fibre == TRUE) &&
16905 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
16906 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
16907 		scsi_dmafree(pktp);
16908 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
16909 	}
16910 #endif
16911 
16912 	/*
16913 	 * The command did not successfully complete as requested so check
16914 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
16915 	 * driver command that should not be retried so just return. If
16916 	 * FLAG_DIAGNOSE is not set the error will be processed below.
16917 	 */
16918 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
16919 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16920 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
16921 		/*
16922 		 * Issue a request sense if a check condition caused the error
16923 		 * (we handle the auto request sense case above), otherwise
16924 		 * just fail the command.
16925 		 */
16926 		if ((pktp->pkt_reason == CMD_CMPLT) &&
16927 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
16928 			sd_send_request_sense_command(un, bp, pktp);
16929 		} else {
16930 			sd_return_failed_command(un, bp, EIO);
16931 		}
16932 		goto exit;
16933 	}
16934 
16935 	/*
16936 	 * The command did not successfully complete as requested so process
16937 	 * the error, retry, and/or attempt recovery.
16938 	 */
16939 	switch (pktp->pkt_reason) {
16940 	case CMD_CMPLT:
16941 		switch (SD_GET_PKT_STATUS(pktp)) {
16942 		case STATUS_GOOD:
16943 			/*
16944 			 * The command completed successfully with a non-zero
16945 			 * residual
16946 			 */
16947 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16948 			    "sdintr: STATUS_GOOD \n");
16949 			sd_pkt_status_good(un, bp, xp, pktp);
16950 			break;
16951 
16952 		case STATUS_CHECK:
16953 		case STATUS_TERMINATED:
16954 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16955 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
16956 			sd_pkt_status_check_condition(un, bp, xp, pktp);
16957 			break;
16958 
16959 		case STATUS_BUSY:
16960 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16961 			    "sdintr: STATUS_BUSY\n");
16962 			sd_pkt_status_busy(un, bp, xp, pktp);
16963 			break;
16964 
16965 		case STATUS_RESERVATION_CONFLICT:
16966 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16967 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
16968 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
16969 			break;
16970 
16971 		case STATUS_QFULL:
16972 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16973 			    "sdintr: STATUS_QFULL\n");
16974 			sd_pkt_status_qfull(un, bp, xp, pktp);
16975 			break;
16976 
16977 		case STATUS_MET:
16978 		case STATUS_INTERMEDIATE:
16979 		case STATUS_SCSI2:
16980 		case STATUS_INTERMEDIATE_MET:
16981 		case STATUS_ACA_ACTIVE:
16982 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16983 			    "Unexpected SCSI status received: 0x%x\n",
16984 			    SD_GET_PKT_STATUS(pktp));
16985 			/*
16986 			 * Mark the ssc_flags when detected invalid status
16987 			 * code for non-USCSI command.
16988 			 */
16989 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
16990 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
16991 				    0, "stat-code");
16992 			}
16993 			sd_return_failed_command(un, bp, EIO);
16994 			break;
16995 
16996 		default:
16997 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16998 			    "Invalid SCSI status received: 0x%x\n",
16999 			    SD_GET_PKT_STATUS(pktp));
17000 			if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17001 				sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_STATUS,
17002 				    0, "stat-code");
17003 			}
17004 			sd_return_failed_command(un, bp, EIO);
17005 			break;
17006 
17007 		}
17008 		break;
17009 
17010 	case CMD_INCOMPLETE:
17011 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17012 		    "sdintr:  CMD_INCOMPLETE\n");
17013 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
17014 		break;
17015 	case CMD_TRAN_ERR:
17016 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17017 		    "sdintr: CMD_TRAN_ERR\n");
17018 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
17019 		break;
17020 	case CMD_RESET:
17021 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17022 		    "sdintr: CMD_RESET \n");
17023 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
17024 		break;
17025 	case CMD_ABORTED:
17026 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17027 		    "sdintr: CMD_ABORTED \n");
17028 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
17029 		break;
17030 	case CMD_TIMEOUT:
17031 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17032 		    "sdintr: CMD_TIMEOUT\n");
17033 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
17034 		break;
17035 	case CMD_UNX_BUS_FREE:
17036 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17037 		    "sdintr: CMD_UNX_BUS_FREE \n");
17038 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
17039 		break;
17040 	case CMD_TAG_REJECT:
17041 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17042 		    "sdintr: CMD_TAG_REJECT\n");
17043 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
17044 		break;
17045 	default:
17046 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17047 		    "sdintr: default\n");
17048 		/*
17049 		 * Mark the ssc_flags for detecting invliad pkt_reason.
17050 		 */
17051 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17052 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_PKT_REASON,
17053 			    0, "pkt-reason");
17054 		}
17055 		sd_pkt_reason_default(un, bp, xp, pktp);
17056 		break;
17057 	}
17058 
17059 exit:
17060 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
17061 
17062 	/* Decrement counter to indicate that the callback routine is done. */
17063 	un->un_in_callback--;
17064 	ASSERT(un->un_in_callback >= 0);
17065 
17066 	/*
17067 	 * At this point, the pkt has been dispatched, ie, it is either
17068 	 * being re-tried or has been returned to its caller and should
17069 	 * not be referenced.
17070 	 */
17071 
17072 	mutex_exit(SD_MUTEX(un));
17073 }
17074 
17075 
17076 /*
17077  *    Function: sd_print_incomplete_msg
17078  *
17079  * Description: Prints the error message for a CMD_INCOMPLETE error.
17080  *
17081  *   Arguments: un - ptr to associated softstate for the device.
17082  *		bp - ptr to the buf(9S) for the command.
17083  *		arg - message string ptr
17084  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
17085  *			or SD_NO_RETRY_ISSUED.
17086  *
17087  *     Context: May be called under interrupt context
17088  */
17089 
17090 static void
17091 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17092 {
17093 	struct scsi_pkt	*pktp;
17094 	char	*msgp;
17095 	char	*cmdp = arg;
17096 
17097 	ASSERT(un != NULL);
17098 	ASSERT(mutex_owned(SD_MUTEX(un)));
17099 	ASSERT(bp != NULL);
17100 	ASSERT(arg != NULL);
17101 	pktp = SD_GET_PKTP(bp);
17102 	ASSERT(pktp != NULL);
17103 
17104 	switch (code) {
17105 	case SD_DELAYED_RETRY_ISSUED:
17106 	case SD_IMMEDIATE_RETRY_ISSUED:
17107 		msgp = "retrying";
17108 		break;
17109 	case SD_NO_RETRY_ISSUED:
17110 	default:
17111 		msgp = "giving up";
17112 		break;
17113 	}
17114 
17115 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17116 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17117 		    "incomplete %s- %s\n", cmdp, msgp);
17118 	}
17119 }
17120 
17121 
17122 
17123 /*
17124  *    Function: sd_pkt_status_good
17125  *
17126  * Description: Processing for a STATUS_GOOD code in pkt_status.
17127  *
17128  *     Context: May be called under interrupt context
17129  */
17130 
17131 static void
17132 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
17133     struct sd_xbuf *xp, struct scsi_pkt *pktp)
17134 {
17135 	char	*cmdp;
17136 
17137 	ASSERT(un != NULL);
17138 	ASSERT(mutex_owned(SD_MUTEX(un)));
17139 	ASSERT(bp != NULL);
17140 	ASSERT(xp != NULL);
17141 	ASSERT(pktp != NULL);
17142 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
17143 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
17144 	ASSERT(pktp->pkt_resid != 0);
17145 
17146 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
17147 
17148 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17149 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
17150 	case SCMD_READ:
17151 		cmdp = "read";
17152 		break;
17153 	case SCMD_WRITE:
17154 		cmdp = "write";
17155 		break;
17156 	default:
17157 		SD_UPDATE_B_RESID(bp, pktp);
17158 		sd_return_command(un, bp);
17159 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17160 		return;
17161 	}
17162 
17163 	/*
17164 	 * See if we can retry the read/write, preferrably immediately.
17165 	 * If retries are exhaused, then sd_retry_command() will update
17166 	 * the b_resid count.
17167 	 */
17168 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
17169 	    cmdp, EIO, (clock_t)0, NULL);
17170 
17171 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
17172 }
17173 
17174 
17175 
17176 
17177 
17178 /*
17179  *    Function: sd_handle_request_sense
17180  *
17181  * Description: Processing for non-auto Request Sense command.
17182  *
17183  *   Arguments: un - ptr to associated softstate
17184  *		sense_bp - ptr to buf(9S) for the RQS command
17185  *		sense_xp - ptr to the sd_xbuf for the RQS command
17186  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
17187  *
17188  *     Context: May be called under interrupt context
17189  */
17190 
17191 static void
17192 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
17193     struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
17194 {
17195 	struct buf	*cmd_bp;	/* buf for the original command */
17196 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
17197 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
17198 	size_t		actual_len;	/* actual sense data length */
17199 
17200 	ASSERT(un != NULL);
17201 	ASSERT(mutex_owned(SD_MUTEX(un)));
17202 	ASSERT(sense_bp != NULL);
17203 	ASSERT(sense_xp != NULL);
17204 	ASSERT(sense_pktp != NULL);
17205 
17206 	/*
17207 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
17208 	 * RQS command and not the original command.
17209 	 */
17210 	ASSERT(sense_pktp == un->un_rqs_pktp);
17211 	ASSERT(sense_bp   == un->un_rqs_bp);
17212 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
17213 	    (FLAG_SENSING | FLAG_HEAD));
17214 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
17215 	    FLAG_SENSING) == FLAG_SENSING);
17216 
17217 	/* These are the bp, xp, and pktp for the original command */
17218 	cmd_bp = sense_xp->xb_sense_bp;
17219 	cmd_xp = SD_GET_XBUF(cmd_bp);
17220 	cmd_pktp = SD_GET_PKTP(cmd_bp);
17221 
17222 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
17223 		/*
17224 		 * The REQUEST SENSE command failed.  Release the REQUEST
17225 		 * SENSE command for re-use, get back the bp for the original
17226 		 * command, and attempt to re-try the original command if
17227 		 * FLAG_DIAGNOSE is not set in the original packet.
17228 		 */
17229 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17230 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17231 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
17232 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
17233 			    NULL, NULL, EIO, (clock_t)0, NULL);
17234 			return;
17235 		}
17236 	}
17237 
17238 	/*
17239 	 * Save the relevant sense info into the xp for the original cmd.
17240 	 *
17241 	 * Note: if the request sense failed the state info will be zero
17242 	 * as set in sd_mark_rqs_busy()
17243 	 */
17244 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
17245 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
17246 	actual_len = MAX_SENSE_LENGTH - sense_pktp->pkt_resid;
17247 	if ((cmd_xp->xb_pkt_flags & SD_XB_USCSICMD) &&
17248 	    (((struct uscsi_cmd *)cmd_xp->xb_pktinfo)->uscsi_rqlen >
17249 	    SENSE_LENGTH)) {
17250 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17251 		    MAX_SENSE_LENGTH);
17252 		cmd_xp->xb_sense_resid = sense_pktp->pkt_resid;
17253 	} else {
17254 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
17255 		    SENSE_LENGTH);
17256 		if (actual_len < SENSE_LENGTH) {
17257 			cmd_xp->xb_sense_resid = SENSE_LENGTH - actual_len;
17258 		} else {
17259 			cmd_xp->xb_sense_resid = 0;
17260 		}
17261 	}
17262 
17263 	/*
17264 	 *  Free up the RQS command....
17265 	 *  NOTE:
17266 	 *	Must do this BEFORE calling sd_validate_sense_data!
17267 	 *	sd_validate_sense_data may return the original command in
17268 	 *	which case the pkt will be freed and the flags can no
17269 	 *	longer be touched.
17270 	 *	SD_MUTEX is held through this process until the command
17271 	 *	is dispatched based upon the sense data, so there are
17272 	 *	no race conditions.
17273 	 */
17274 	(void) sd_mark_rqs_idle(un, sense_xp);
17275 
17276 	/*
17277 	 * For a retryable command see if we have valid sense data, if so then
17278 	 * turn it over to sd_decode_sense() to figure out the right course of
17279 	 * action. Just fail a non-retryable command.
17280 	 */
17281 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
17282 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp, actual_len) ==
17283 		    SD_SENSE_DATA_IS_VALID) {
17284 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
17285 		}
17286 	} else {
17287 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
17288 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17289 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
17290 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
17291 		sd_return_failed_command(un, cmd_bp, EIO);
17292 	}
17293 }
17294 
17295 
17296 
17297 
17298 /*
17299  *    Function: sd_handle_auto_request_sense
17300  *
17301  * Description: Processing for auto-request sense information.
17302  *
17303  *   Arguments: un - ptr to associated softstate
17304  *		bp - ptr to buf(9S) for the command
17305  *		xp - ptr to the sd_xbuf for the command
17306  *		pktp - ptr to the scsi_pkt(9S) for the command
17307  *
17308  *     Context: May be called under interrupt context
17309  */
17310 
17311 static void
17312 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
17313     struct sd_xbuf *xp, struct scsi_pkt *pktp)
17314 {
17315 	struct scsi_arq_status *asp;
17316 	size_t actual_len;
17317 
17318 	ASSERT(un != NULL);
17319 	ASSERT(mutex_owned(SD_MUTEX(un)));
17320 	ASSERT(bp != NULL);
17321 	ASSERT(xp != NULL);
17322 	ASSERT(pktp != NULL);
17323 	ASSERT(pktp != un->un_rqs_pktp);
17324 	ASSERT(bp   != un->un_rqs_bp);
17325 
17326 	/*
17327 	 * For auto-request sense, we get a scsi_arq_status back from
17328 	 * the HBA, with the sense data in the sts_sensedata member.
17329 	 * The pkt_scbp of the packet points to this scsi_arq_status.
17330 	 */
17331 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
17332 
17333 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
17334 		/*
17335 		 * The auto REQUEST SENSE failed; see if we can re-try
17336 		 * the original command.
17337 		 */
17338 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17339 		    "auto request sense failed (reason=%s)\n",
17340 		    scsi_rname(asp->sts_rqpkt_reason));
17341 
17342 		sd_reset_target(un, pktp);
17343 
17344 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17345 		    NULL, NULL, EIO, (clock_t)0, NULL);
17346 		return;
17347 	}
17348 
17349 	/* Save the relevant sense info into the xp for the original cmd. */
17350 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
17351 	xp->xb_sense_state  = asp->sts_rqpkt_state;
17352 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
17353 	if (xp->xb_sense_state & STATE_XARQ_DONE) {
17354 		actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17355 		bcopy(&asp->sts_sensedata, xp->xb_sense_data,
17356 		    MAX_SENSE_LENGTH);
17357 	} else {
17358 		if (xp->xb_sense_resid > SENSE_LENGTH) {
17359 			actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
17360 		} else {
17361 			actual_len = SENSE_LENGTH - xp->xb_sense_resid;
17362 		}
17363 		if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
17364 			if ((((struct uscsi_cmd *)
17365 			    (xp->xb_pktinfo))->uscsi_rqlen) > actual_len) {
17366 				xp->xb_sense_resid = (((struct uscsi_cmd *)
17367 				    (xp->xb_pktinfo))->uscsi_rqlen) -
17368 				    actual_len;
17369 			} else {
17370 				xp->xb_sense_resid = 0;
17371 			}
17372 		}
17373 		bcopy(&asp->sts_sensedata, xp->xb_sense_data, SENSE_LENGTH);
17374 	}
17375 
17376 	/*
17377 	 * See if we have valid sense data, if so then turn it over to
17378 	 * sd_decode_sense() to figure out the right course of action.
17379 	 */
17380 	if (sd_validate_sense_data(un, bp, xp, actual_len) ==
17381 	    SD_SENSE_DATA_IS_VALID) {
17382 		sd_decode_sense(un, bp, xp, pktp);
17383 	}
17384 }
17385 
17386 
17387 /*
17388  *    Function: sd_print_sense_failed_msg
17389  *
17390  * Description: Print log message when RQS has failed.
17391  *
17392  *   Arguments: un - ptr to associated softstate
17393  *		bp - ptr to buf(9S) for the command
17394  *		arg - generic message string ptr
17395  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17396  *			or SD_NO_RETRY_ISSUED
17397  *
17398  *     Context: May be called from interrupt context
17399  */
17400 
17401 static void
17402 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
17403     int code)
17404 {
17405 	char	*msgp = arg;
17406 
17407 	ASSERT(un != NULL);
17408 	ASSERT(mutex_owned(SD_MUTEX(un)));
17409 	ASSERT(bp != NULL);
17410 
17411 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
17412 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
17413 	}
17414 }
17415 
17416 
17417 /*
17418  *    Function: sd_validate_sense_data
17419  *
17420  * Description: Check the given sense data for validity.
17421  *		If the sense data is not valid, the command will
17422  *		be either failed or retried!
17423  *
17424  * Return Code: SD_SENSE_DATA_IS_INVALID
17425  *		SD_SENSE_DATA_IS_VALID
17426  *
17427  *     Context: May be called from interrupt context
17428  */
17429 
17430 static int
17431 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17432     size_t actual_len)
17433 {
17434 	struct scsi_extended_sense *esp;
17435 	struct	scsi_pkt *pktp;
17436 	char	*msgp = NULL;
17437 	sd_ssc_t *sscp;
17438 
17439 	ASSERT(un != NULL);
17440 	ASSERT(mutex_owned(SD_MUTEX(un)));
17441 	ASSERT(bp != NULL);
17442 	ASSERT(bp != un->un_rqs_bp);
17443 	ASSERT(xp != NULL);
17444 	ASSERT(un->un_fm_private != NULL);
17445 
17446 	pktp = SD_GET_PKTP(bp);
17447 	ASSERT(pktp != NULL);
17448 
17449 	sscp = &((struct sd_fm_internal *)(un->un_fm_private))->fm_ssc;
17450 	ASSERT(sscp != NULL);
17451 
17452 	/*
17453 	 * Check the status of the RQS command (auto or manual).
17454 	 */
17455 	switch (xp->xb_sense_status & STATUS_MASK) {
17456 	case STATUS_GOOD:
17457 		break;
17458 
17459 	case STATUS_RESERVATION_CONFLICT:
17460 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
17461 		return (SD_SENSE_DATA_IS_INVALID);
17462 
17463 	case STATUS_BUSY:
17464 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17465 		    "Busy Status on REQUEST SENSE\n");
17466 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
17467 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17468 		return (SD_SENSE_DATA_IS_INVALID);
17469 
17470 	case STATUS_QFULL:
17471 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17472 		    "QFULL Status on REQUEST SENSE\n");
17473 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
17474 		    NULL, EIO, un->un_busy_timeout / 500, kstat_waitq_enter);
17475 		return (SD_SENSE_DATA_IS_INVALID);
17476 
17477 	case STATUS_CHECK:
17478 	case STATUS_TERMINATED:
17479 		msgp = "Check Condition on REQUEST SENSE\n";
17480 		goto sense_failed;
17481 
17482 	default:
17483 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
17484 		goto sense_failed;
17485 	}
17486 
17487 	/*
17488 	 * See if we got the minimum required amount of sense data.
17489 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
17490 	 * or less.
17491 	 */
17492 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
17493 	    (actual_len == 0)) {
17494 		msgp = "Request Sense couldn't get sense data\n";
17495 		goto sense_failed;
17496 	}
17497 
17498 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
17499 		msgp = "Not enough sense information\n";
17500 		/* Mark the ssc_flags for detecting invalid sense data */
17501 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17502 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17503 			    "sense-data");
17504 		}
17505 		goto sense_failed;
17506 	}
17507 
17508 	/*
17509 	 * We require the extended sense data
17510 	 */
17511 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
17512 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
17513 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
17514 			static char tmp[8];
17515 			static char buf[148];
17516 			char *p = (char *)(xp->xb_sense_data);
17517 			int i;
17518 
17519 			mutex_enter(&sd_sense_mutex);
17520 			(void) strcpy(buf, "undecodable sense information:");
17521 			for (i = 0; i < actual_len; i++) {
17522 				(void) sprintf(tmp, " 0x%x", *(p++) & 0xff);
17523 				(void) strcpy(&buf[strlen(buf)], tmp);
17524 			}
17525 			i = strlen(buf);
17526 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
17527 
17528 			if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
17529 				scsi_log(SD_DEVINFO(un), sd_label,
17530 				    CE_WARN, buf);
17531 			}
17532 			mutex_exit(&sd_sense_mutex);
17533 		}
17534 
17535 		/* Mark the ssc_flags for detecting invalid sense data */
17536 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17537 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17538 			    "sense-data");
17539 		}
17540 
17541 		/* Note: Legacy behavior, fail the command with no retry */
17542 		sd_return_failed_command(un, bp, EIO);
17543 		return (SD_SENSE_DATA_IS_INVALID);
17544 	}
17545 
17546 	/*
17547 	 * Check that es_code is valid (es_class concatenated with es_code
17548 	 * make up the "response code" field.  es_class will always be 7, so
17549 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
17550 	 * format.
17551 	 */
17552 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
17553 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
17554 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
17555 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
17556 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
17557 		/* Mark the ssc_flags for detecting invalid sense data */
17558 		if (!(xp->xb_pkt_flags & SD_XB_USCSICMD)) {
17559 			sd_ssc_set_info(sscp, SSC_FLAGS_INVALID_SENSE, 0,
17560 			    "sense-data");
17561 		}
17562 		goto sense_failed;
17563 	}
17564 
17565 	return (SD_SENSE_DATA_IS_VALID);
17566 
17567 sense_failed:
17568 	/*
17569 	 * If the request sense failed (for whatever reason), attempt
17570 	 * to retry the original command.
17571 	 */
17572 #if defined(__x86)
17573 	/*
17574 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
17575 	 * sddef.h for Sparc platform, and x86 uses 1 binary
17576 	 * for both SCSI/FC.
17577 	 * The SD_RETRY_DELAY value need to be adjusted here
17578 	 * when SD_RETRY_DELAY change in sddef.h
17579 	 */
17580 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17581 	    sd_print_sense_failed_msg, msgp, EIO,
17582 	    un->un_f_is_fibre ? drv_usectohz(100000) : (clock_t)0, NULL);
17583 #else
17584 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
17585 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
17586 #endif
17587 
17588 	return (SD_SENSE_DATA_IS_INVALID);
17589 }
17590 
17591 /*
17592  *    Function: sd_decode_sense
17593  *
17594  * Description: Take recovery action(s) when SCSI Sense Data is received.
17595  *
17596  *     Context: Interrupt context.
17597  */
17598 
17599 static void
17600 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17601     struct scsi_pkt *pktp)
17602 {
17603 	uint8_t sense_key;
17604 
17605 	ASSERT(un != NULL);
17606 	ASSERT(mutex_owned(SD_MUTEX(un)));
17607 	ASSERT(bp != NULL);
17608 	ASSERT(bp != un->un_rqs_bp);
17609 	ASSERT(xp != NULL);
17610 	ASSERT(pktp != NULL);
17611 
17612 	sense_key = scsi_sense_key(xp->xb_sense_data);
17613 
17614 	switch (sense_key) {
17615 	case KEY_NO_SENSE:
17616 		sd_sense_key_no_sense(un, bp, xp, pktp);
17617 		break;
17618 	case KEY_RECOVERABLE_ERROR:
17619 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
17620 		    bp, xp, pktp);
17621 		break;
17622 	case KEY_NOT_READY:
17623 		sd_sense_key_not_ready(un, xp->xb_sense_data,
17624 		    bp, xp, pktp);
17625 		break;
17626 	case KEY_MEDIUM_ERROR:
17627 	case KEY_HARDWARE_ERROR:
17628 		sd_sense_key_medium_or_hardware_error(un,
17629 		    xp->xb_sense_data, bp, xp, pktp);
17630 		break;
17631 	case KEY_ILLEGAL_REQUEST:
17632 		sd_sense_key_illegal_request(un, bp, xp, pktp);
17633 		break;
17634 	case KEY_UNIT_ATTENTION:
17635 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
17636 		    bp, xp, pktp);
17637 		break;
17638 	case KEY_WRITE_PROTECT:
17639 	case KEY_VOLUME_OVERFLOW:
17640 	case KEY_MISCOMPARE:
17641 		sd_sense_key_fail_command(un, bp, xp, pktp);
17642 		break;
17643 	case KEY_BLANK_CHECK:
17644 		sd_sense_key_blank_check(un, bp, xp, pktp);
17645 		break;
17646 	case KEY_ABORTED_COMMAND:
17647 		sd_sense_key_aborted_command(un, bp, xp, pktp);
17648 		break;
17649 	case KEY_VENDOR_UNIQUE:
17650 	case KEY_COPY_ABORTED:
17651 	case KEY_EQUAL:
17652 	case KEY_RESERVED:
17653 	default:
17654 		sd_sense_key_default(un, xp->xb_sense_data,
17655 		    bp, xp, pktp);
17656 		break;
17657 	}
17658 }
17659 
17660 
17661 /*
17662  *    Function: sd_dump_memory
17663  *
17664  * Description: Debug logging routine to print the contents of a user provided
17665  *		buffer. The output of the buffer is broken up into 256 byte
17666  *		segments due to a size constraint of the scsi_log.
17667  *		implementation.
17668  *
17669  *   Arguments: un - ptr to softstate
17670  *		comp - component mask
17671  *		title - "title" string to preceed data when printed
17672  *		data - ptr to data block to be printed
17673  *		len - size of data block to be printed
17674  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
17675  *
17676  *     Context: May be called from interrupt context
17677  */
17678 
17679 #define	SD_DUMP_MEMORY_BUF_SIZE	256
17680 
17681 static char *sd_dump_format_string[] = {
17682 		" 0x%02x",
17683 		" %c"
17684 };
17685 
17686 static void
17687 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
17688     int len, int fmt)
17689 {
17690 	int	i, j;
17691 	int	avail_count;
17692 	int	start_offset;
17693 	int	end_offset;
17694 	size_t	entry_len;
17695 	char	*bufp;
17696 	char	*local_buf;
17697 	char	*format_string;
17698 
17699 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
17700 
17701 	/*
17702 	 * In the debug version of the driver, this function is called from a
17703 	 * number of places which are NOPs in the release driver.
17704 	 * The debug driver therefore has additional methods of filtering
17705 	 * debug output.
17706 	 */
17707 #ifdef SDDEBUG
17708 	/*
17709 	 * In the debug version of the driver we can reduce the amount of debug
17710 	 * messages by setting sd_error_level to something other than
17711 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
17712 	 * sd_component_mask.
17713 	 */
17714 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
17715 	    (sd_error_level != SCSI_ERR_ALL)) {
17716 		return;
17717 	}
17718 	if (((sd_component_mask & comp) == 0) ||
17719 	    (sd_error_level != SCSI_ERR_ALL)) {
17720 		return;
17721 	}
17722 #else
17723 	if (sd_error_level != SCSI_ERR_ALL) {
17724 		return;
17725 	}
17726 #endif
17727 
17728 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
17729 	bufp = local_buf;
17730 	/*
17731 	 * Available length is the length of local_buf[], minus the
17732 	 * length of the title string, minus one for the ":", minus
17733 	 * one for the newline, minus one for the NULL terminator.
17734 	 * This gives the #bytes available for holding the printed
17735 	 * values from the given data buffer.
17736 	 */
17737 	if (fmt == SD_LOG_HEX) {
17738 		format_string = sd_dump_format_string[0];
17739 	} else /* SD_LOG_CHAR */ {
17740 		format_string = sd_dump_format_string[1];
17741 	}
17742 	/*
17743 	 * Available count is the number of elements from the given
17744 	 * data buffer that we can fit into the available length.
17745 	 * This is based upon the size of the format string used.
17746 	 * Make one entry and find it's size.
17747 	 */
17748 	(void) sprintf(bufp, format_string, data[0]);
17749 	entry_len = strlen(bufp);
17750 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
17751 
17752 	j = 0;
17753 	while (j < len) {
17754 		bufp = local_buf;
17755 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
17756 		start_offset = j;
17757 
17758 		end_offset = start_offset + avail_count;
17759 
17760 		(void) sprintf(bufp, "%s:", title);
17761 		bufp += strlen(bufp);
17762 		for (i = start_offset; ((i < end_offset) && (j < len));
17763 		    i++, j++) {
17764 			(void) sprintf(bufp, format_string, data[i]);
17765 			bufp += entry_len;
17766 		}
17767 		(void) sprintf(bufp, "\n");
17768 
17769 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
17770 	}
17771 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
17772 }
17773 
17774 /*
17775  *    Function: sd_print_sense_msg
17776  *
17777  * Description: Log a message based upon the given sense data.
17778  *
17779  *   Arguments: un - ptr to associated softstate
17780  *		bp - ptr to buf(9S) for the command
17781  *		arg - ptr to associate sd_sense_info struct
17782  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
17783  *			or SD_NO_RETRY_ISSUED
17784  *
17785  *     Context: May be called from interrupt context
17786  */
17787 
17788 static void
17789 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
17790 {
17791 	struct sd_xbuf	*xp;
17792 	struct scsi_pkt	*pktp;
17793 	uint8_t *sensep;
17794 	daddr_t request_blkno;
17795 	diskaddr_t err_blkno;
17796 	int severity;
17797 	int pfa_flag;
17798 	extern struct scsi_key_strings scsi_cmds[];
17799 
17800 	ASSERT(un != NULL);
17801 	ASSERT(mutex_owned(SD_MUTEX(un)));
17802 	ASSERT(bp != NULL);
17803 	xp = SD_GET_XBUF(bp);
17804 	ASSERT(xp != NULL);
17805 	pktp = SD_GET_PKTP(bp);
17806 	ASSERT(pktp != NULL);
17807 	ASSERT(arg != NULL);
17808 
17809 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
17810 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
17811 
17812 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
17813 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
17814 		severity = SCSI_ERR_RETRYABLE;
17815 	}
17816 
17817 	/* Use absolute block number for the request block number */
17818 	request_blkno = xp->xb_blkno;
17819 
17820 	/*
17821 	 * Now try to get the error block number from the sense data
17822 	 */
17823 	sensep = xp->xb_sense_data;
17824 
17825 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
17826 	    (uint64_t *)&err_blkno)) {
17827 		/*
17828 		 * We retrieved the error block number from the information
17829 		 * portion of the sense data.
17830 		 *
17831 		 * For USCSI commands we are better off using the error
17832 		 * block no. as the requested block no. (This is the best
17833 		 * we can estimate.)
17834 		 */
17835 		if ((SD_IS_BUFIO(xp) == FALSE) &&
17836 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
17837 			request_blkno = err_blkno;
17838 		}
17839 	} else {
17840 		/*
17841 		 * Without the es_valid bit set (for fixed format) or an
17842 		 * information descriptor (for descriptor format) we cannot
17843 		 * be certain of the error blkno, so just use the
17844 		 * request_blkno.
17845 		 */
17846 		err_blkno = (diskaddr_t)request_blkno;
17847 	}
17848 
17849 	/*
17850 	 * The following will log the buffer contents for the release driver
17851 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
17852 	 * level is set to verbose.
17853 	 */
17854 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
17855 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
17856 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
17857 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
17858 
17859 	if (pfa_flag == FALSE) {
17860 		/* This is normally only set for USCSI */
17861 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
17862 			return;
17863 		}
17864 
17865 		if ((SD_IS_BUFIO(xp) == TRUE) &&
17866 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
17867 		    (severity < sd_error_level))) {
17868 			return;
17869 		}
17870 	}
17871 
17872 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP ||
17873 	    ((scsi_sense_key(sensep) == KEY_RECOVERABLE_ERROR) &&
17874 	    (pktp->pkt_resid == 0))) {
17875 		scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
17876 		    request_blkno, err_blkno, scsi_cmds,
17877 		    (struct scsi_extended_sense *)sensep,
17878 		    un->un_additional_codes, NULL);
17879 	}
17880 }
17881 
17882 /*
17883  *    Function: sd_sense_key_no_sense
17884  *
17885  * Description: Recovery action when sense data was not received.
17886  *
17887  *     Context: May be called from interrupt context
17888  */
17889 
17890 static void
17891 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17892     struct scsi_pkt *pktp)
17893 {
17894 	struct sd_sense_info	si;
17895 
17896 	ASSERT(un != NULL);
17897 	ASSERT(mutex_owned(SD_MUTEX(un)));
17898 	ASSERT(bp != NULL);
17899 	ASSERT(xp != NULL);
17900 	ASSERT(pktp != NULL);
17901 
17902 	si.ssi_severity = SCSI_ERR_FATAL;
17903 	si.ssi_pfa_flag = FALSE;
17904 
17905 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
17906 
17907 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17908 	    &si, EIO, (clock_t)0, NULL);
17909 }
17910 
17911 
17912 /*
17913  *    Function: sd_sense_key_recoverable_error
17914  *
17915  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
17916  *
17917  *     Context: May be called from interrupt context
17918  */
17919 
17920 static void
17921 sd_sense_key_recoverable_error(struct sd_lun *un, uint8_t *sense_datap,
17922     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
17923 {
17924 	struct sd_sense_info	si;
17925 	uint8_t asc = scsi_sense_asc(sense_datap);
17926 	uint8_t ascq = scsi_sense_ascq(sense_datap);
17927 
17928 	ASSERT(un != NULL);
17929 	ASSERT(mutex_owned(SD_MUTEX(un)));
17930 	ASSERT(bp != NULL);
17931 	ASSERT(xp != NULL);
17932 	ASSERT(pktp != NULL);
17933 
17934 	/*
17935 	 * 0x00, 0x1D: ATA PASSTHROUGH INFORMATION AVAILABLE
17936 	 */
17937 	if (asc == 0x00 && ascq == 0x1D) {
17938 		sd_return_command(un, bp);
17939 		return;
17940 	}
17941 
17942 	/*
17943 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
17944 	 */
17945 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
17946 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
17947 		si.ssi_severity = SCSI_ERR_INFO;
17948 		si.ssi_pfa_flag = TRUE;
17949 	} else {
17950 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
17951 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
17952 		si.ssi_severity = SCSI_ERR_RECOVERED;
17953 		si.ssi_pfa_flag = FALSE;
17954 	}
17955 
17956 	if (pktp->pkt_resid == 0) {
17957 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17958 		sd_return_command(un, bp);
17959 		return;
17960 	}
17961 
17962 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
17963 	    &si, EIO, (clock_t)0, NULL);
17964 }
17965 
17966 
17967 
17968 
17969 /*
17970  *    Function: sd_sense_key_not_ready
17971  *
17972  * Description: Recovery actions for a SCSI "Not Ready" sense key.
17973  *
17974  *     Context: May be called from interrupt context
17975  */
17976 
17977 static void
17978 sd_sense_key_not_ready(struct sd_lun *un, uint8_t *sense_datap, struct buf *bp,
17979     struct sd_xbuf *xp, struct scsi_pkt *pktp)
17980 {
17981 	struct sd_sense_info	si;
17982 	uint8_t asc = scsi_sense_asc(sense_datap);
17983 	uint8_t ascq = scsi_sense_ascq(sense_datap);
17984 
17985 	ASSERT(un != NULL);
17986 	ASSERT(mutex_owned(SD_MUTEX(un)));
17987 	ASSERT(bp != NULL);
17988 	ASSERT(xp != NULL);
17989 	ASSERT(pktp != NULL);
17990 
17991 	si.ssi_severity = SCSI_ERR_FATAL;
17992 	si.ssi_pfa_flag = FALSE;
17993 
17994 	/*
17995 	 * Update error stats after first NOT READY error. Disks may have
17996 	 * been powered down and may need to be restarted.  For CDROMs,
17997 	 * report NOT READY errors only if media is present.
17998 	 */
17999 	if ((ISCD(un) && (asc == 0x3A)) ||
18000 	    (xp->xb_nr_retry_count > 0)) {
18001 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18002 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
18003 	}
18004 
18005 	/*
18006 	 * Just fail if the "not ready" retry limit has been reached.
18007 	 */
18008 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
18009 		/* Special check for error message printing for removables. */
18010 		if (un->un_f_has_removable_media && (asc == 0x04) &&
18011 		    (ascq >= 0x04)) {
18012 			si.ssi_severity = SCSI_ERR_ALL;
18013 		}
18014 		goto fail_command;
18015 	}
18016 
18017 	/*
18018 	 * Check the ASC and ASCQ in the sense data as needed, to determine
18019 	 * what to do.
18020 	 */
18021 	switch (asc) {
18022 	case 0x04:	/* LOGICAL UNIT NOT READY */
18023 		/*
18024 		 * disk drives that don't spin up result in a very long delay
18025 		 * in format without warning messages. We will log a message
18026 		 * if the error level is set to verbose.
18027 		 */
18028 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18029 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18030 			    "logical unit not ready, resetting disk\n");
18031 		}
18032 
18033 		/*
18034 		 * There are different requirements for CDROMs and disks for
18035 		 * the number of retries.  If a CD-ROM is giving this, it is
18036 		 * probably reading TOC and is in the process of getting
18037 		 * ready, so we should keep on trying for a long time to make
18038 		 * sure that all types of media are taken in account (for
18039 		 * some media the drive takes a long time to read TOC).  For
18040 		 * disks we do not want to retry this too many times as this
18041 		 * can cause a long hang in format when the drive refuses to
18042 		 * spin up (a very common failure).
18043 		 */
18044 		switch (ascq) {
18045 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
18046 			/*
18047 			 * Disk drives frequently refuse to spin up which
18048 			 * results in a very long hang in format without
18049 			 * warning messages.
18050 			 *
18051 			 * Note: This code preserves the legacy behavior of
18052 			 * comparing xb_nr_retry_count against zero for fibre
18053 			 * channel targets instead of comparing against the
18054 			 * un_reset_retry_count value.  The reason for this
18055 			 * discrepancy has been so utterly lost beneath the
18056 			 * Sands of Time that even Indiana Jones could not
18057 			 * find it.
18058 			 */
18059 			if (un->un_f_is_fibre == TRUE) {
18060 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18061 				    (xp->xb_nr_retry_count > 0)) &&
18062 				    (un->un_startstop_timeid == NULL)) {
18063 					scsi_log(SD_DEVINFO(un), sd_label,
18064 					    CE_WARN, "logical unit not ready, "
18065 					    "resetting disk\n");
18066 					sd_reset_target(un, pktp);
18067 				}
18068 			} else {
18069 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
18070 				    (xp->xb_nr_retry_count >
18071 				    un->un_reset_retry_count)) &&
18072 				    (un->un_startstop_timeid == NULL)) {
18073 					scsi_log(SD_DEVINFO(un), sd_label,
18074 					    CE_WARN, "logical unit not ready, "
18075 					    "resetting disk\n");
18076 					sd_reset_target(un, pktp);
18077 				}
18078 			}
18079 			break;
18080 
18081 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
18082 			/*
18083 			 * If the target is in the process of becoming
18084 			 * ready, just proceed with the retry. This can
18085 			 * happen with CD-ROMs that take a long time to
18086 			 * read TOC after a power cycle or reset.
18087 			 */
18088 			goto do_retry;
18089 
18090 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
18091 			break;
18092 
18093 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
18094 			/*
18095 			 * Retries cannot help here so just fail right away.
18096 			 */
18097 			goto fail_command;
18098 
18099 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
18100 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
18101 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
18102 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
18103 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
18104 		default:    /* Possible future codes in SCSI spec? */
18105 			/*
18106 			 * For removable-media devices, do not retry if
18107 			 * ASCQ > 2 as these result mostly from USCSI commands
18108 			 * on MMC devices issued to check status of an
18109 			 * operation initiated in immediate mode.  Also for
18110 			 * ASCQ >= 4 do not print console messages as these
18111 			 * mainly represent a user-initiated operation
18112 			 * instead of a system failure.
18113 			 */
18114 			if (un->un_f_has_removable_media) {
18115 				si.ssi_severity = SCSI_ERR_ALL;
18116 				goto fail_command;
18117 			}
18118 			break;
18119 		}
18120 
18121 		/*
18122 		 * As part of our recovery attempt for the NOT READY
18123 		 * condition, we issue a START STOP UNIT command. However
18124 		 * we want to wait for a short delay before attempting this
18125 		 * as there may still be more commands coming back from the
18126 		 * target with the check condition. To do this we use
18127 		 * timeout(9F) to call sd_start_stop_unit_callback() after
18128 		 * the delay interval expires. (sd_start_stop_unit_callback()
18129 		 * dispatches sd_start_stop_unit_task(), which will issue
18130 		 * the actual START STOP UNIT command. The delay interval
18131 		 * is one-half of the delay that we will use to retry the
18132 		 * command that generated the NOT READY condition.
18133 		 *
18134 		 * Note that we could just dispatch sd_start_stop_unit_task()
18135 		 * from here and allow it to sleep for the delay interval,
18136 		 * but then we would be tying up the taskq thread
18137 		 * uncesessarily for the duration of the delay.
18138 		 *
18139 		 * Do not issue the START STOP UNIT if the current command
18140 		 * is already a START STOP UNIT.
18141 		 */
18142 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
18143 			break;
18144 		}
18145 
18146 		/*
18147 		 * Do not schedule the timeout if one is already pending.
18148 		 */
18149 		if (un->un_startstop_timeid != NULL) {
18150 			SD_INFO(SD_LOG_ERROR, un,
18151 			    "sd_sense_key_not_ready: restart already issued to"
18152 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
18153 			    ddi_get_instance(SD_DEVINFO(un)));
18154 			break;
18155 		}
18156 
18157 		/*
18158 		 * Schedule the START STOP UNIT command, then queue the command
18159 		 * for a retry.
18160 		 *
18161 		 * Note: A timeout is not scheduled for this retry because we
18162 		 * want the retry to be serial with the START_STOP_UNIT. The
18163 		 * retry will be started when the START_STOP_UNIT is completed
18164 		 * in sd_start_stop_unit_task.
18165 		 */
18166 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
18167 		    un, un->un_busy_timeout / 2);
18168 		xp->xb_nr_retry_count++;
18169 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
18170 		return;
18171 
18172 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
18173 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18174 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18175 			    "unit does not respond to selection\n");
18176 		}
18177 		break;
18178 
18179 	case 0x3A:	/* MEDIUM NOT PRESENT */
18180 		if (sd_error_level >= SCSI_ERR_FATAL) {
18181 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18182 			    "Caddy not inserted in drive\n");
18183 		}
18184 
18185 		sr_ejected(un);
18186 		un->un_mediastate = DKIO_EJECTED;
18187 		/* The state has changed, inform the media watch routines */
18188 		cv_broadcast(&un->un_state_cv);
18189 		/* Just fail if no media is present in the drive. */
18190 		goto fail_command;
18191 
18192 	default:
18193 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
18194 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
18195 			    "Unit not Ready. Additional sense code 0x%x\n",
18196 			    asc);
18197 		}
18198 		break;
18199 	}
18200 
18201 do_retry:
18202 
18203 	/*
18204 	 * Retry the command, as some targets may report NOT READY for
18205 	 * several seconds after being reset.
18206 	 */
18207 	xp->xb_nr_retry_count++;
18208 	si.ssi_severity = SCSI_ERR_RETRYABLE;
18209 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
18210 	    &si, EIO, un->un_busy_timeout, NULL);
18211 
18212 	return;
18213 
18214 fail_command:
18215 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18216 	sd_return_failed_command(un, bp, EIO);
18217 }
18218 
18219 
18220 
18221 /*
18222  *    Function: sd_sense_key_medium_or_hardware_error
18223  *
18224  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
18225  *		sense key.
18226  *
18227  *     Context: May be called from interrupt context
18228  */
18229 
18230 static void
18231 sd_sense_key_medium_or_hardware_error(struct sd_lun *un, uint8_t *sense_datap,
18232     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18233 {
18234 	struct sd_sense_info	si;
18235 	uint8_t sense_key = scsi_sense_key(sense_datap);
18236 
18237 	ASSERT(un != NULL);
18238 	ASSERT(mutex_owned(SD_MUTEX(un)));
18239 	ASSERT(bp != NULL);
18240 	ASSERT(xp != NULL);
18241 	ASSERT(pktp != NULL);
18242 
18243 	si.ssi_severity = SCSI_ERR_FATAL;
18244 	si.ssi_pfa_flag = FALSE;
18245 
18246 	if (sense_key == KEY_MEDIUM_ERROR) {
18247 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
18248 	}
18249 
18250 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18251 
18252 	if ((un->un_reset_retry_count != 0) &&
18253 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
18254 		mutex_exit(SD_MUTEX(un));
18255 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
18256 		if (un->un_f_allow_bus_device_reset == TRUE) {
18257 
18258 			int reset_retval = 0;
18259 			if (un->un_f_lun_reset_enabled == TRUE) {
18260 				SD_TRACE(SD_LOG_IO_CORE, un,
18261 				    "sd_sense_key_medium_or_hardware_"
18262 				    "error: issuing RESET_LUN\n");
18263 				reset_retval = scsi_reset(SD_ADDRESS(un),
18264 				    RESET_LUN);
18265 			}
18266 			if (reset_retval == 0) {
18267 				SD_TRACE(SD_LOG_IO_CORE, un,
18268 				    "sd_sense_key_medium_or_hardware_"
18269 				    "error: issuing RESET_TARGET\n");
18270 				(void) scsi_reset(SD_ADDRESS(un),
18271 				    RESET_TARGET);
18272 			}
18273 		}
18274 		mutex_enter(SD_MUTEX(un));
18275 	}
18276 
18277 	/*
18278 	 * This really ought to be a fatal error, but we will retry anyway
18279 	 * as some drives report this as a spurious error.
18280 	 */
18281 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18282 	    &si, EIO, (clock_t)0, NULL);
18283 }
18284 
18285 
18286 
18287 /*
18288  *    Function: sd_sense_key_illegal_request
18289  *
18290  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
18291  *
18292  *     Context: May be called from interrupt context
18293  */
18294 
18295 static void
18296 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
18297     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18298 {
18299 	struct sd_sense_info	si;
18300 
18301 	ASSERT(un != NULL);
18302 	ASSERT(mutex_owned(SD_MUTEX(un)));
18303 	ASSERT(bp != NULL);
18304 	ASSERT(xp != NULL);
18305 	ASSERT(pktp != NULL);
18306 
18307 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
18308 
18309 	si.ssi_severity = SCSI_ERR_INFO;
18310 	si.ssi_pfa_flag = FALSE;
18311 
18312 	/* Pointless to retry if the target thinks it's an illegal request */
18313 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18314 	sd_return_failed_command(un, bp, EIO);
18315 }
18316 
18317 
18318 
18319 
18320 /*
18321  *    Function: sd_sense_key_unit_attention
18322  *
18323  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
18324  *
18325  *     Context: May be called from interrupt context
18326  */
18327 
18328 static void
18329 sd_sense_key_unit_attention(struct sd_lun *un, uint8_t *sense_datap,
18330     struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
18331 {
18332 	/*
18333 	 * For UNIT ATTENTION we allow retries for one minute. Devices
18334 	 * like Sonoma can return UNIT ATTENTION close to a minute
18335 	 * under certain conditions.
18336 	 */
18337 	int	retry_check_flag = SD_RETRIES_UA;
18338 	boolean_t	kstat_updated = B_FALSE;
18339 	struct	sd_sense_info		si;
18340 	uint8_t asc = scsi_sense_asc(sense_datap);
18341 	uint8_t	ascq = scsi_sense_ascq(sense_datap);
18342 
18343 	ASSERT(un != NULL);
18344 	ASSERT(mutex_owned(SD_MUTEX(un)));
18345 	ASSERT(bp != NULL);
18346 	ASSERT(xp != NULL);
18347 	ASSERT(pktp != NULL);
18348 
18349 	si.ssi_severity = SCSI_ERR_INFO;
18350 	si.ssi_pfa_flag = FALSE;
18351 
18352 
18353 	switch (asc) {
18354 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
18355 		if (sd_report_pfa != 0) {
18356 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
18357 			si.ssi_pfa_flag = TRUE;
18358 			retry_check_flag = SD_RETRIES_STANDARD;
18359 			goto do_retry;
18360 		}
18361 
18362 		break;
18363 
18364 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
18365 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
18366 			un->un_resvd_status |=
18367 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
18368 		}
18369 #ifdef _LP64
18370 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
18371 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
18372 			    un, KM_NOSLEEP) == TASKQID_INVALID) {
18373 				/*
18374 				 * If we can't dispatch the task we'll just
18375 				 * live without descriptor sense.  We can
18376 				 * try again on the next "unit attention"
18377 				 */
18378 				SD_ERROR(SD_LOG_ERROR, un,
18379 				    "sd_sense_key_unit_attention: "
18380 				    "Could not dispatch "
18381 				    "sd_reenable_dsense_task\n");
18382 			}
18383 		}
18384 #endif /* _LP64 */
18385 		/* FALLTHRU */
18386 
18387 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
18388 		if (!un->un_f_has_removable_media) {
18389 			break;
18390 		}
18391 
18392 		/*
18393 		 * When we get a unit attention from a removable-media device,
18394 		 * it may be in a state that will take a long time to recover
18395 		 * (e.g., from a reset).  Since we are executing in interrupt
18396 		 * context here, we cannot wait around for the device to come
18397 		 * back. So hand this command off to sd_media_change_task()
18398 		 * for deferred processing under taskq thread context. (Note
18399 		 * that the command still may be failed if a problem is
18400 		 * encountered at a later time.)
18401 		 */
18402 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
18403 		    KM_NOSLEEP) == TASKQID_INVALID) {
18404 			/*
18405 			 * Cannot dispatch the request so fail the command.
18406 			 */
18407 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
18408 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18409 			si.ssi_severity = SCSI_ERR_FATAL;
18410 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18411 			sd_return_failed_command(un, bp, EIO);
18412 		}
18413 
18414 		/*
18415 		 * If failed to dispatch sd_media_change_task(), we already
18416 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
18417 		 * we should update kstat later if it encounters an error. So,
18418 		 * we update kstat_updated flag here.
18419 		 */
18420 		kstat_updated = B_TRUE;
18421 
18422 		/*
18423 		 * Either the command has been successfully dispatched to a
18424 		 * task Q for retrying, or the dispatch failed. In either case
18425 		 * do NOT retry again by calling sd_retry_command. This sets up
18426 		 * two retries of the same command and when one completes and
18427 		 * frees the resources the other will access freed memory,
18428 		 * a bad thing.
18429 		 */
18430 		return;
18431 
18432 	default:
18433 		break;
18434 	}
18435 
18436 	/*
18437 	 * ASC  ASCQ
18438 	 *  2A   09	Capacity data has changed
18439 	 *  2A   01	Mode parameters changed
18440 	 *  3F   0E	Reported luns data has changed
18441 	 * Arrays that support logical unit expansion should report
18442 	 * capacity changes(2Ah/09). Mode parameters changed and
18443 	 * reported luns data has changed are the approximation.
18444 	 */
18445 	if (((asc == 0x2a) && (ascq == 0x09)) ||
18446 	    ((asc == 0x2a) && (ascq == 0x01)) ||
18447 	    ((asc == 0x3f) && (ascq == 0x0e))) {
18448 		if (taskq_dispatch(sd_tq, sd_target_change_task, un,
18449 		    KM_NOSLEEP) == TASKQID_INVALID) {
18450 			SD_ERROR(SD_LOG_ERROR, un,
18451 			    "sd_sense_key_unit_attention: "
18452 			    "Could not dispatch sd_target_change_task\n");
18453 		}
18454 	}
18455 
18456 	/*
18457 	 * Update kstat if we haven't done that.
18458 	 */
18459 	if (!kstat_updated) {
18460 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
18461 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
18462 	}
18463 
18464 do_retry:
18465 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
18466 	    EIO, SD_UA_RETRY_DELAY, NULL);
18467 }
18468 
18469 
18470 
18471 /*
18472  *    Function: sd_sense_key_fail_command
18473  *
18474  * Description: Use to fail a command when we don't like the sense key that
18475  *		was returned.
18476  *
18477  *     Context: May be called from interrupt context
18478  */
18479 
18480 static void
18481 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18482     struct scsi_pkt *pktp)
18483 {
18484 	struct sd_sense_info	si;
18485 
18486 	ASSERT(un != NULL);
18487 	ASSERT(mutex_owned(SD_MUTEX(un)));
18488 	ASSERT(bp != NULL);
18489 	ASSERT(xp != NULL);
18490 	ASSERT(pktp != NULL);
18491 
18492 	si.ssi_severity = SCSI_ERR_FATAL;
18493 	si.ssi_pfa_flag = FALSE;
18494 
18495 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18496 	sd_return_failed_command(un, bp, EIO);
18497 }
18498 
18499 
18500 
18501 /*
18502  *    Function: sd_sense_key_blank_check
18503  *
18504  * Description: Recovery actions for a SCSI "Blank Check" sense key.
18505  *		Has no monetary connotation.
18506  *
18507  *     Context: May be called from interrupt context
18508  */
18509 
18510 static void
18511 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18512     struct scsi_pkt *pktp)
18513 {
18514 	struct sd_sense_info	si;
18515 
18516 	ASSERT(un != NULL);
18517 	ASSERT(mutex_owned(SD_MUTEX(un)));
18518 	ASSERT(bp != NULL);
18519 	ASSERT(xp != NULL);
18520 	ASSERT(pktp != NULL);
18521 
18522 	/*
18523 	 * Blank check is not fatal for removable devices, therefore
18524 	 * it does not require a console message.
18525 	 */
18526 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
18527 	    SCSI_ERR_FATAL;
18528 	si.ssi_pfa_flag = FALSE;
18529 
18530 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
18531 	sd_return_failed_command(un, bp, EIO);
18532 }
18533 
18534 
18535 
18536 
18537 /*
18538  *    Function: sd_sense_key_aborted_command
18539  *
18540  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
18541  *
18542  *     Context: May be called from interrupt context
18543  */
18544 
18545 static void
18546 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
18547     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18548 {
18549 	struct sd_sense_info	si;
18550 
18551 	ASSERT(un != NULL);
18552 	ASSERT(mutex_owned(SD_MUTEX(un)));
18553 	ASSERT(bp != NULL);
18554 	ASSERT(xp != NULL);
18555 	ASSERT(pktp != NULL);
18556 
18557 	si.ssi_severity = SCSI_ERR_FATAL;
18558 	si.ssi_pfa_flag = FALSE;
18559 
18560 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18561 
18562 	/*
18563 	 * This really ought to be a fatal error, but we will retry anyway
18564 	 * as some drives report this as a spurious error.
18565 	 */
18566 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18567 	    &si, EIO, drv_usectohz(100000), NULL);
18568 }
18569 
18570 
18571 
18572 /*
18573  *    Function: sd_sense_key_default
18574  *
18575  * Description: Default recovery action for several SCSI sense keys (basically
18576  *		attempts a retry).
18577  *
18578  *     Context: May be called from interrupt context
18579  */
18580 
18581 static void
18582 sd_sense_key_default(struct sd_lun *un, uint8_t *sense_datap, struct buf *bp,
18583     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18584 {
18585 	struct sd_sense_info	si;
18586 	uint8_t sense_key = scsi_sense_key(sense_datap);
18587 
18588 	ASSERT(un != NULL);
18589 	ASSERT(mutex_owned(SD_MUTEX(un)));
18590 	ASSERT(bp != NULL);
18591 	ASSERT(xp != NULL);
18592 	ASSERT(pktp != NULL);
18593 
18594 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18595 
18596 	/*
18597 	 * Undecoded sense key.	Attempt retries and hope that will fix
18598 	 * the problem.  Otherwise, we're dead.
18599 	 */
18600 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
18601 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18602 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
18603 	}
18604 
18605 	si.ssi_severity = SCSI_ERR_FATAL;
18606 	si.ssi_pfa_flag = FALSE;
18607 
18608 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
18609 	    &si, EIO, (clock_t)0, NULL);
18610 }
18611 
18612 
18613 
18614 /*
18615  *    Function: sd_print_retry_msg
18616  *
18617  * Description: Print a message indicating the retry action being taken.
18618  *
18619  *   Arguments: un - ptr to associated softstate
18620  *		bp - ptr to buf(9S) for the command
18621  *		arg - not used.
18622  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18623  *			or SD_NO_RETRY_ISSUED
18624  *
18625  *     Context: May be called from interrupt context
18626  */
18627 /* ARGSUSED */
18628 static void
18629 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
18630 {
18631 	struct sd_xbuf	*xp;
18632 	struct scsi_pkt *pktp;
18633 	char *reasonp;
18634 	char *msgp;
18635 
18636 	ASSERT(un != NULL);
18637 	ASSERT(mutex_owned(SD_MUTEX(un)));
18638 	ASSERT(bp != NULL);
18639 	pktp = SD_GET_PKTP(bp);
18640 	ASSERT(pktp != NULL);
18641 	xp = SD_GET_XBUF(bp);
18642 	ASSERT(xp != NULL);
18643 
18644 	ASSERT(!mutex_owned(&un->un_pm_mutex));
18645 	mutex_enter(&un->un_pm_mutex);
18646 	if ((un->un_state == SD_STATE_SUSPENDED) ||
18647 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
18648 	    (pktp->pkt_flags & FLAG_SILENT)) {
18649 		mutex_exit(&un->un_pm_mutex);
18650 		goto update_pkt_reason;
18651 	}
18652 	mutex_exit(&un->un_pm_mutex);
18653 
18654 	/*
18655 	 * Suppress messages if they are all the same pkt_reason; with
18656 	 * TQ, many (up to 256) are returned with the same pkt_reason.
18657 	 * If we are in panic, then suppress the retry messages.
18658 	 */
18659 	switch (flag) {
18660 	case SD_NO_RETRY_ISSUED:
18661 		msgp = "giving up";
18662 		break;
18663 	case SD_IMMEDIATE_RETRY_ISSUED:
18664 	case SD_DELAYED_RETRY_ISSUED:
18665 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
18666 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
18667 		    (sd_error_level != SCSI_ERR_ALL))) {
18668 			return;
18669 		}
18670 		msgp = "retrying command";
18671 		break;
18672 	default:
18673 		goto update_pkt_reason;
18674 	}
18675 
18676 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
18677 	    scsi_rname(pktp->pkt_reason));
18678 
18679 	if (SD_FM_LOG(un) == SD_FM_LOG_NSUP) {
18680 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18681 		    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
18682 	}
18683 
18684 update_pkt_reason:
18685 	/*
18686 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
18687 	 * This is to prevent multiple console messages for the same failure
18688 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
18689 	 * when the command is retried successfully because there still may be
18690 	 * more commands coming back with the same value of pktp->pkt_reason.
18691 	 */
18692 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
18693 		un->un_last_pkt_reason = pktp->pkt_reason;
18694 	}
18695 }
18696 
18697 
18698 /*
18699  *    Function: sd_print_cmd_incomplete_msg
18700  *
18701  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
18702  *
18703  *   Arguments: un - ptr to associated softstate
18704  *		bp - ptr to buf(9S) for the command
18705  *		arg - passed to sd_print_retry_msg()
18706  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
18707  *			or SD_NO_RETRY_ISSUED
18708  *
18709  *     Context: May be called from interrupt context
18710  */
18711 
18712 static void
18713 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
18714     int code)
18715 {
18716 	dev_info_t	*dip;
18717 
18718 	ASSERT(un != NULL);
18719 	ASSERT(mutex_owned(SD_MUTEX(un)));
18720 	ASSERT(bp != NULL);
18721 
18722 	switch (code) {
18723 	case SD_NO_RETRY_ISSUED:
18724 		/* Command was failed. Someone turned off this target? */
18725 		if (un->un_state != SD_STATE_OFFLINE) {
18726 			/*
18727 			 * Suppress message if we are detaching and
18728 			 * device has been disconnected
18729 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
18730 			 * private interface and not part of the DDI
18731 			 */
18732 			dip = un->un_sd->sd_dev;
18733 			if (!(DEVI_IS_DETACHING(dip) &&
18734 			    DEVI_IS_DEVICE_REMOVED(dip))) {
18735 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18736 				"disk not responding to selection\n");
18737 			}
18738 			New_state(un, SD_STATE_OFFLINE);
18739 		}
18740 		break;
18741 
18742 	case SD_DELAYED_RETRY_ISSUED:
18743 	case SD_IMMEDIATE_RETRY_ISSUED:
18744 	default:
18745 		/* Command was successfully queued for retry */
18746 		sd_print_retry_msg(un, bp, arg, code);
18747 		break;
18748 	}
18749 }
18750 
18751 
18752 /*
18753  *    Function: sd_pkt_reason_cmd_incomplete
18754  *
18755  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
18756  *
18757  *     Context: May be called from interrupt context
18758  */
18759 
18760 static void
18761 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
18762     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18763 {
18764 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
18765 
18766 	ASSERT(un != NULL);
18767 	ASSERT(mutex_owned(SD_MUTEX(un)));
18768 	ASSERT(bp != NULL);
18769 	ASSERT(xp != NULL);
18770 	ASSERT(pktp != NULL);
18771 
18772 	/* Do not do a reset if selection did not complete */
18773 	/* Note: Should this not just check the bit? */
18774 	if (pktp->pkt_state != STATE_GOT_BUS) {
18775 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18776 		sd_reset_target(un, pktp);
18777 	}
18778 
18779 	/*
18780 	 * If the target was not successfully selected, then set
18781 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
18782 	 * with the target, and further retries and/or commands are
18783 	 * likely to take a long time.
18784 	 */
18785 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
18786 		flag |= SD_RETRIES_FAILFAST;
18787 	}
18788 
18789 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18790 
18791 	sd_retry_command(un, bp, flag,
18792 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18793 }
18794 
18795 
18796 
18797 /*
18798  *    Function: sd_pkt_reason_cmd_tran_err
18799  *
18800  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
18801  *
18802  *     Context: May be called from interrupt context
18803  */
18804 
18805 static void
18806 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
18807     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18808 {
18809 	ASSERT(un != NULL);
18810 	ASSERT(mutex_owned(SD_MUTEX(un)));
18811 	ASSERT(bp != NULL);
18812 	ASSERT(xp != NULL);
18813 	ASSERT(pktp != NULL);
18814 
18815 	/*
18816 	 * Do not reset if we got a parity error, or if
18817 	 * selection did not complete.
18818 	 */
18819 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18820 	/* Note: Should this not just check the bit for pkt_state? */
18821 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
18822 	    (pktp->pkt_state != STATE_GOT_BUS)) {
18823 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
18824 		sd_reset_target(un, pktp);
18825 	}
18826 
18827 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18828 
18829 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18830 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18831 }
18832 
18833 
18834 
18835 /*
18836  *    Function: sd_pkt_reason_cmd_reset
18837  *
18838  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
18839  *
18840  *     Context: May be called from interrupt context
18841  */
18842 
18843 static void
18844 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18845     struct scsi_pkt *pktp)
18846 {
18847 	ASSERT(un != NULL);
18848 	ASSERT(mutex_owned(SD_MUTEX(un)));
18849 	ASSERT(bp != NULL);
18850 	ASSERT(xp != NULL);
18851 	ASSERT(pktp != NULL);
18852 
18853 	/* The target may still be running the command, so try to reset. */
18854 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18855 	sd_reset_target(un, pktp);
18856 
18857 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18858 
18859 	/*
18860 	 * If pkt_reason is CMD_RESET chances are that this pkt got
18861 	 * reset because another target on this bus caused it. The target
18862 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
18863 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
18864 	 */
18865 
18866 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
18867 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18868 }
18869 
18870 
18871 
18872 
18873 /*
18874  *    Function: sd_pkt_reason_cmd_aborted
18875  *
18876  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
18877  *
18878  *     Context: May be called from interrupt context
18879  */
18880 
18881 static void
18882 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18883     struct scsi_pkt *pktp)
18884 {
18885 	ASSERT(un != NULL);
18886 	ASSERT(mutex_owned(SD_MUTEX(un)));
18887 	ASSERT(bp != NULL);
18888 	ASSERT(xp != NULL);
18889 	ASSERT(pktp != NULL);
18890 
18891 	/* The target may still be running the command, so try to reset. */
18892 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18893 	sd_reset_target(un, pktp);
18894 
18895 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18896 
18897 	/*
18898 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
18899 	 * aborted because another target on this bus caused it. The target
18900 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
18901 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
18902 	 */
18903 
18904 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
18905 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18906 }
18907 
18908 
18909 
18910 /*
18911  *    Function: sd_pkt_reason_cmd_timeout
18912  *
18913  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
18914  *
18915  *     Context: May be called from interrupt context
18916  */
18917 
18918 static void
18919 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
18920     struct scsi_pkt *pktp)
18921 {
18922 	ASSERT(un != NULL);
18923 	ASSERT(mutex_owned(SD_MUTEX(un)));
18924 	ASSERT(bp != NULL);
18925 	ASSERT(xp != NULL);
18926 	ASSERT(pktp != NULL);
18927 
18928 
18929 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
18930 	sd_reset_target(un, pktp);
18931 
18932 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18933 
18934 	/*
18935 	 * A command timeout indicates that we could not establish
18936 	 * communication with the target, so set SD_RETRIES_FAILFAST
18937 	 * as further retries/commands are likely to take a long time.
18938 	 */
18939 	sd_retry_command(un, bp,
18940 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
18941 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18942 }
18943 
18944 
18945 
18946 /*
18947  *    Function: sd_pkt_reason_cmd_unx_bus_free
18948  *
18949  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
18950  *
18951  *     Context: May be called from interrupt context
18952  */
18953 
18954 static void
18955 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
18956     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18957 {
18958 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
18959 
18960 	ASSERT(un != NULL);
18961 	ASSERT(mutex_owned(SD_MUTEX(un)));
18962 	ASSERT(bp != NULL);
18963 	ASSERT(xp != NULL);
18964 	ASSERT(pktp != NULL);
18965 
18966 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18967 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
18968 
18969 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
18970 	    sd_print_retry_msg : NULL;
18971 
18972 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
18973 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
18974 }
18975 
18976 
18977 /*
18978  *    Function: sd_pkt_reason_cmd_tag_reject
18979  *
18980  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
18981  *
18982  *     Context: May be called from interrupt context
18983  */
18984 
18985 static void
18986 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
18987     struct sd_xbuf *xp, struct scsi_pkt *pktp)
18988 {
18989 	ASSERT(un != NULL);
18990 	ASSERT(mutex_owned(SD_MUTEX(un)));
18991 	ASSERT(bp != NULL);
18992 	ASSERT(xp != NULL);
18993 	ASSERT(pktp != NULL);
18994 
18995 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
18996 	pktp->pkt_flags = 0;
18997 	un->un_tagflags = 0;
18998 	if (un->un_f_opt_queueing == TRUE) {
18999 		un->un_throttle = min(un->un_throttle, 3);
19000 	} else {
19001 		un->un_throttle = 1;
19002 	}
19003 	mutex_exit(SD_MUTEX(un));
19004 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
19005 	mutex_enter(SD_MUTEX(un));
19006 
19007 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19008 
19009 	/* Legacy behavior not to check retry counts here. */
19010 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
19011 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19012 }
19013 
19014 
19015 /*
19016  *    Function: sd_pkt_reason_default
19017  *
19018  * Description: Default recovery actions for SCSA pkt_reason values that
19019  *		do not have more explicit recovery actions.
19020  *
19021  *     Context: May be called from interrupt context
19022  */
19023 
19024 static void
19025 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19026     struct scsi_pkt *pktp)
19027 {
19028 	ASSERT(un != NULL);
19029 	ASSERT(mutex_owned(SD_MUTEX(un)));
19030 	ASSERT(bp != NULL);
19031 	ASSERT(xp != NULL);
19032 	ASSERT(pktp != NULL);
19033 
19034 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
19035 	sd_reset_target(un, pktp);
19036 
19037 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
19038 
19039 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
19040 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
19041 }
19042 
19043 
19044 
19045 /*
19046  *    Function: sd_pkt_status_check_condition
19047  *
19048  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
19049  *
19050  *     Context: May be called from interrupt context
19051  */
19052 
19053 static void
19054 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
19055     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19056 {
19057 	ASSERT(un != NULL);
19058 	ASSERT(mutex_owned(SD_MUTEX(un)));
19059 	ASSERT(bp != NULL);
19060 	ASSERT(xp != NULL);
19061 	ASSERT(pktp != NULL);
19062 
19063 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
19064 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
19065 
19066 	/*
19067 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
19068 	 * command will be retried after the request sense). Otherwise, retry
19069 	 * the command. Note: we are issuing the request sense even though the
19070 	 * retry limit may have been reached for the failed command.
19071 	 */
19072 	if (un->un_f_arq_enabled == FALSE) {
19073 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19074 		    "no ARQ, sending request sense command\n");
19075 		sd_send_request_sense_command(un, bp, pktp);
19076 	} else {
19077 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
19078 		    "ARQ,retrying request sense command\n");
19079 #if defined(__x86)
19080 		/*
19081 		 * The SD_RETRY_DELAY value need to be adjusted here
19082 		 * when SD_RETRY_DELAY change in sddef.h
19083 		 */
19084 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19085 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
19086 		    NULL);
19087 #else
19088 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
19089 		    EIO, SD_RETRY_DELAY, NULL);
19090 #endif
19091 	}
19092 
19093 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
19094 }
19095 
19096 
19097 /*
19098  *    Function: sd_pkt_status_busy
19099  *
19100  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
19101  *
19102  *     Context: May be called from interrupt context
19103  */
19104 
19105 static void
19106 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19107     struct scsi_pkt *pktp)
19108 {
19109 	ASSERT(un != NULL);
19110 	ASSERT(mutex_owned(SD_MUTEX(un)));
19111 	ASSERT(bp != NULL);
19112 	ASSERT(xp != NULL);
19113 	ASSERT(pktp != NULL);
19114 
19115 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19116 	    "sd_pkt_status_busy: entry\n");
19117 
19118 	/* If retries are exhausted, just fail the command. */
19119 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
19120 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
19121 		    "device busy too long\n");
19122 		sd_return_failed_command(un, bp, EIO);
19123 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19124 		    "sd_pkt_status_busy: exit\n");
19125 		return;
19126 	}
19127 	xp->xb_retry_count++;
19128 
19129 	/*
19130 	 * Try to reset the target. However, we do not want to perform
19131 	 * more than one reset if the device continues to fail. The reset
19132 	 * will be performed when the retry count reaches the reset
19133 	 * threshold.  This threshold should be set such that at least
19134 	 * one retry is issued before the reset is performed.
19135 	 */
19136 	if (xp->xb_retry_count ==
19137 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
19138 		int rval = 0;
19139 		mutex_exit(SD_MUTEX(un));
19140 		if (un->un_f_allow_bus_device_reset == TRUE) {
19141 			/*
19142 			 * First try to reset the LUN; if we cannot then
19143 			 * try to reset the target.
19144 			 */
19145 			if (un->un_f_lun_reset_enabled == TRUE) {
19146 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19147 				    "sd_pkt_status_busy: RESET_LUN\n");
19148 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19149 			}
19150 			if (rval == 0) {
19151 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19152 				    "sd_pkt_status_busy: RESET_TARGET\n");
19153 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19154 			}
19155 		}
19156 		if (rval == 0) {
19157 			/*
19158 			 * If the RESET_LUN and/or RESET_TARGET failed,
19159 			 * try RESET_ALL
19160 			 */
19161 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19162 			    "sd_pkt_status_busy: RESET_ALL\n");
19163 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
19164 		}
19165 		mutex_enter(SD_MUTEX(un));
19166 		if (rval == 0) {
19167 			/*
19168 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
19169 			 * At this point we give up & fail the command.
19170 			 */
19171 			sd_return_failed_command(un, bp, EIO);
19172 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19173 			    "sd_pkt_status_busy: exit (failed cmd)\n");
19174 			return;
19175 		}
19176 	}
19177 
19178 	/*
19179 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
19180 	 * we have already checked the retry counts above.
19181 	 */
19182 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
19183 	    EIO, un->un_busy_timeout, NULL);
19184 
19185 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19186 	    "sd_pkt_status_busy: exit\n");
19187 }
19188 
19189 
19190 /*
19191  *    Function: sd_pkt_status_reservation_conflict
19192  *
19193  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
19194  *		command status.
19195  *
19196  *     Context: May be called from interrupt context
19197  */
19198 
19199 static void
19200 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
19201     struct sd_xbuf *xp, struct scsi_pkt *pktp)
19202 {
19203 	ASSERT(un != NULL);
19204 	ASSERT(mutex_owned(SD_MUTEX(un)));
19205 	ASSERT(bp != NULL);
19206 	ASSERT(xp != NULL);
19207 	ASSERT(pktp != NULL);
19208 
19209 	/*
19210 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
19211 	 * conflict could be due to various reasons like incorrect keys, not
19212 	 * registered or not reserved etc. So, we return EACCES to the caller.
19213 	 */
19214 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
19215 		int cmd = SD_GET_PKT_OPCODE(pktp);
19216 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
19217 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
19218 			sd_return_failed_command(un, bp, EACCES);
19219 			return;
19220 		}
19221 	}
19222 
19223 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
19224 
19225 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
19226 		if (sd_failfast_enable != 0) {
19227 			/* By definition, we must panic here.... */
19228 			sd_panic_for_res_conflict(un);
19229 			/*NOTREACHED*/
19230 		}
19231 		SD_ERROR(SD_LOG_IO, un,
19232 		    "sd_handle_resv_conflict: Disk Reserved\n");
19233 		sd_return_failed_command(un, bp, EACCES);
19234 		return;
19235 	}
19236 
19237 	/*
19238 	 * 1147670: retry only if sd_retry_on_reservation_conflict
19239 	 * property is set (default is 1). Retries will not succeed
19240 	 * on a disk reserved by another initiator. HA systems
19241 	 * may reset this via sd.conf to avoid these retries.
19242 	 *
19243 	 * Note: The legacy return code for this failure is EIO, however EACCES
19244 	 * seems more appropriate for a reservation conflict.
19245 	 */
19246 	if (sd_retry_on_reservation_conflict == 0) {
19247 		SD_ERROR(SD_LOG_IO, un,
19248 		    "sd_handle_resv_conflict: Device Reserved\n");
19249 		sd_return_failed_command(un, bp, EIO);
19250 		return;
19251 	}
19252 
19253 	/*
19254 	 * Retry the command if we can.
19255 	 *
19256 	 * Note: The legacy return code for this failure is EIO, however EACCES
19257 	 * seems more appropriate for a reservation conflict.
19258 	 */
19259 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
19260 	    (clock_t)2, NULL);
19261 }
19262 
19263 
19264 
19265 /*
19266  *    Function: sd_pkt_status_qfull
19267  *
19268  * Description: Handle a QUEUE FULL condition from the target.  This can
19269  *		occur if the HBA does not handle the queue full condition.
19270  *		(Basically this means third-party HBAs as Sun HBAs will
19271  *		handle the queue full condition.)  Note that if there are
19272  *		some commands already in the transport, then the queue full
19273  *		has occurred because the queue for this nexus is actually
19274  *		full. If there are no commands in the transport, then the
19275  *		queue full is resulting from some other initiator or lun
19276  *		consuming all the resources at the target.
19277  *
19278  *     Context: May be called from interrupt context
19279  */
19280 
19281 static void
19282 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
19283     struct scsi_pkt *pktp)
19284 {
19285 	ASSERT(un != NULL);
19286 	ASSERT(mutex_owned(SD_MUTEX(un)));
19287 	ASSERT(bp != NULL);
19288 	ASSERT(xp != NULL);
19289 	ASSERT(pktp != NULL);
19290 
19291 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19292 	    "sd_pkt_status_qfull: entry\n");
19293 
19294 	/*
19295 	 * Just lower the QFULL throttle and retry the command.  Note that
19296 	 * we do not limit the number of retries here.
19297 	 */
19298 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
19299 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
19300 	    SD_RESTART_TIMEOUT, NULL);
19301 
19302 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19303 	    "sd_pkt_status_qfull: exit\n");
19304 }
19305 
19306 
19307 /*
19308  *    Function: sd_reset_target
19309  *
19310  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
19311  *		RESET_TARGET, or RESET_ALL.
19312  *
19313  *     Context: May be called under interrupt context.
19314  */
19315 
19316 static void
19317 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
19318 {
19319 	int rval = 0;
19320 
19321 	ASSERT(un != NULL);
19322 	ASSERT(mutex_owned(SD_MUTEX(un)));
19323 	ASSERT(pktp != NULL);
19324 
19325 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
19326 
19327 	/*
19328 	 * No need to reset if the transport layer has already done so.
19329 	 */
19330 	if ((pktp->pkt_statistics &
19331 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
19332 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19333 		    "sd_reset_target: no reset\n");
19334 		return;
19335 	}
19336 
19337 	mutex_exit(SD_MUTEX(un));
19338 
19339 	if (un->un_f_allow_bus_device_reset == TRUE) {
19340 		if (un->un_f_lun_reset_enabled == TRUE) {
19341 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19342 			    "sd_reset_target: RESET_LUN\n");
19343 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
19344 		}
19345 		if (rval == 0) {
19346 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19347 			    "sd_reset_target: RESET_TARGET\n");
19348 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
19349 		}
19350 	}
19351 
19352 	if (rval == 0) {
19353 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
19354 		    "sd_reset_target: RESET_ALL\n");
19355 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
19356 	}
19357 
19358 	mutex_enter(SD_MUTEX(un));
19359 
19360 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
19361 }
19362 
19363 /*
19364  *    Function: sd_target_change_task
19365  *
19366  * Description: Handle dynamic target change
19367  *
19368  *     Context: Executes in a taskq() thread context
19369  */
19370 static void
19371 sd_target_change_task(void *arg)
19372 {
19373 	struct sd_lun		*un = arg;
19374 	uint64_t		capacity;
19375 	diskaddr_t		label_cap;
19376 	uint_t			lbasize;
19377 	sd_ssc_t		*ssc;
19378 
19379 	ASSERT(un != NULL);
19380 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19381 
19382 	if ((un->un_f_blockcount_is_valid == FALSE) ||
19383 	    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
19384 		return;
19385 	}
19386 
19387 	ssc = sd_ssc_init(un);
19388 
19389 	if (sd_send_scsi_READ_CAPACITY(ssc, &capacity,
19390 	    &lbasize, SD_PATH_DIRECT) != 0) {
19391 		SD_ERROR(SD_LOG_ERROR, un,
19392 		    "sd_target_change_task: fail to read capacity\n");
19393 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19394 		goto task_exit;
19395 	}
19396 
19397 	mutex_enter(SD_MUTEX(un));
19398 	if (capacity <= un->un_blockcount) {
19399 		mutex_exit(SD_MUTEX(un));
19400 		goto task_exit;
19401 	}
19402 
19403 	sd_update_block_info(un, lbasize, capacity);
19404 	mutex_exit(SD_MUTEX(un));
19405 
19406 	/*
19407 	 * If lun is EFI labeled and lun capacity is greater than the
19408 	 * capacity contained in the label, log a sys event.
19409 	 */
19410 	if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
19411 	    (void*)SD_PATH_DIRECT) == 0) {
19412 		mutex_enter(SD_MUTEX(un));
19413 		if (un->un_f_blockcount_is_valid &&
19414 		    un->un_blockcount > label_cap) {
19415 			mutex_exit(SD_MUTEX(un));
19416 			sd_log_lun_expansion_event(un, KM_SLEEP);
19417 		} else {
19418 			mutex_exit(SD_MUTEX(un));
19419 		}
19420 	}
19421 
19422 task_exit:
19423 	sd_ssc_fini(ssc);
19424 }
19425 
19426 
19427 /*
19428  *    Function: sd_log_dev_status_event
19429  *
19430  * Description: Log EC_dev_status sysevent
19431  *
19432  *     Context: Never called from interrupt context
19433  */
19434 static void
19435 sd_log_dev_status_event(struct sd_lun *un, char *esc, int km_flag)
19436 {
19437 	int err;
19438 	char			*path;
19439 	nvlist_t		*attr_list;
19440 	size_t			n;
19441 
19442 	/* Allocate and build sysevent attribute list */
19443 	err = nvlist_alloc(&attr_list, NV_UNIQUE_NAME_TYPE, km_flag);
19444 	if (err != 0) {
19445 		SD_ERROR(SD_LOG_ERROR, un,
19446 		    "sd_log_dev_status_event: fail to allocate space\n");
19447 		return;
19448 	}
19449 
19450 	path = kmem_alloc(MAXPATHLEN, km_flag);
19451 	if (path == NULL) {
19452 		nvlist_free(attr_list);
19453 		SD_ERROR(SD_LOG_ERROR, un,
19454 		    "sd_log_dev_status_event: fail to allocate space\n");
19455 		return;
19456 	}
19457 
19458 	n = snprintf(path, MAXPATHLEN, "/devices");
19459 	(void) ddi_pathname(SD_DEVINFO(un), path + n);
19460 	n = strlen(path);
19461 	n += snprintf(path + n, MAXPATHLEN - n, ":x");
19462 
19463 	/*
19464 	 * On receipt of this event, the ZFS sysevent module will scan
19465 	 * active zpools for child vdevs matching this physical path.
19466 	 * In order to catch both whole disk pools and those with an
19467 	 * EFI boot partition, generate separate sysevents for minor
19468 	 * node 'a' and 'b'.
19469 	 */
19470 	for (char c = 'a'; c < 'c'; c++) {
19471 		path[n - 1] = c;
19472 
19473 		err = nvlist_add_string(attr_list, DEV_PHYS_PATH, path);
19474 		if (err != 0) {
19475 			SD_ERROR(SD_LOG_ERROR, un,
19476 			    "sd_log_dev_status_event: fail to add attribute\n");
19477 			break;
19478 		}
19479 
19480 		err = ddi_log_sysevent(SD_DEVINFO(un), SUNW_VENDOR,
19481 		    EC_DEV_STATUS, esc, attr_list, NULL, km_flag);
19482 		if (err != DDI_SUCCESS) {
19483 			SD_ERROR(SD_LOG_ERROR, un,
19484 			    "sd_log_dev_status_event: fail to log sysevent\n");
19485 			break;
19486 		}
19487 	}
19488 
19489 	nvlist_free(attr_list);
19490 	kmem_free(path, MAXPATHLEN);
19491 }
19492 
19493 
19494 /*
19495  *    Function: sd_log_lun_expansion_event
19496  *
19497  * Description: Log lun expansion sys event
19498  *
19499  *     Context: Never called from interrupt context
19500  */
19501 static void
19502 sd_log_lun_expansion_event(struct sd_lun *un, int km_flag)
19503 {
19504 	sd_log_dev_status_event(un, ESC_DEV_DLE, km_flag);
19505 }
19506 
19507 
19508 /*
19509  *    Function: sd_log_eject_request_event
19510  *
19511  * Description: Log eject request sysevent
19512  *
19513  *     Context: Never called from interrupt context
19514  */
19515 static void
19516 sd_log_eject_request_event(struct sd_lun *un, int km_flag)
19517 {
19518 	sd_log_dev_status_event(un, ESC_DEV_EJECT_REQUEST, km_flag);
19519 }
19520 
19521 
19522 /*
19523  *    Function: sd_media_change_task
19524  *
19525  * Description: Recovery action for CDROM to become available.
19526  *
19527  *     Context: Executes in a taskq() thread context
19528  */
19529 
19530 static void
19531 sd_media_change_task(void *arg)
19532 {
19533 	struct	scsi_pkt	*pktp = arg;
19534 	struct	sd_lun		*un;
19535 	struct	buf		*bp;
19536 	struct	sd_xbuf		*xp;
19537 	int	err		= 0;
19538 	int	retry_count	= 0;
19539 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
19540 	struct	sd_sense_info	si;
19541 
19542 	ASSERT(pktp != NULL);
19543 	bp = (struct buf *)pktp->pkt_private;
19544 	ASSERT(bp != NULL);
19545 	xp = SD_GET_XBUF(bp);
19546 	ASSERT(xp != NULL);
19547 	un = SD_GET_UN(bp);
19548 	ASSERT(un != NULL);
19549 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19550 	ASSERT(un->un_f_monitor_media_state);
19551 
19552 	si.ssi_severity = SCSI_ERR_INFO;
19553 	si.ssi_pfa_flag = FALSE;
19554 
19555 	/*
19556 	 * When a reset is issued on a CDROM, it takes a long time to
19557 	 * recover. First few attempts to read capacity and other things
19558 	 * related to handling unit attention fail (with a ASC 0x4 and
19559 	 * ASCQ 0x1). In that case we want to do enough retries and we want
19560 	 * to limit the retries in other cases of genuine failures like
19561 	 * no media in drive.
19562 	 */
19563 	while (retry_count++ < retry_limit) {
19564 		if ((err = sd_handle_mchange(un)) == 0) {
19565 			break;
19566 		}
19567 		if (err == EAGAIN) {
19568 			retry_limit = SD_UNIT_ATTENTION_RETRY;
19569 		}
19570 		/* Sleep for 0.5 sec. & try again */
19571 		delay(drv_usectohz(500000));
19572 	}
19573 
19574 	/*
19575 	 * Dispatch (retry or fail) the original command here,
19576 	 * along with appropriate console messages....
19577 	 *
19578 	 * Must grab the mutex before calling sd_retry_command,
19579 	 * sd_print_sense_msg and sd_return_failed_command.
19580 	 */
19581 	mutex_enter(SD_MUTEX(un));
19582 	if (err != SD_CMD_SUCCESS) {
19583 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
19584 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
19585 		si.ssi_severity = SCSI_ERR_FATAL;
19586 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
19587 		sd_return_failed_command(un, bp, EIO);
19588 	} else {
19589 		sd_retry_command(un, bp, SD_RETRIES_UA, sd_print_sense_msg,
19590 		    &si, EIO, (clock_t)0, NULL);
19591 	}
19592 	mutex_exit(SD_MUTEX(un));
19593 }
19594 
19595 
19596 
19597 /*
19598  *    Function: sd_handle_mchange
19599  *
19600  * Description: Perform geometry validation & other recovery when CDROM
19601  *		has been removed from drive.
19602  *
19603  * Return Code: 0 for success
19604  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
19605  *		sd_send_scsi_READ_CAPACITY()
19606  *
19607  *     Context: Executes in a taskq() thread context
19608  */
19609 
19610 static int
19611 sd_handle_mchange(struct sd_lun *un)
19612 {
19613 	uint64_t	capacity;
19614 	uint32_t	lbasize;
19615 	int		rval;
19616 	sd_ssc_t	*ssc;
19617 
19618 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19619 	ASSERT(un->un_f_monitor_media_state);
19620 
19621 	ssc = sd_ssc_init(un);
19622 	rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
19623 	    SD_PATH_DIRECT_PRIORITY);
19624 
19625 	if (rval != 0)
19626 		goto failed;
19627 
19628 	mutex_enter(SD_MUTEX(un));
19629 	sd_update_block_info(un, lbasize, capacity);
19630 
19631 	if (un->un_errstats != NULL) {
19632 		struct	sd_errstats *stp =
19633 		    (struct sd_errstats *)un->un_errstats->ks_data;
19634 		stp->sd_capacity.value.ui64 = (uint64_t)
19635 		    ((uint64_t)un->un_blockcount *
19636 		    (uint64_t)un->un_tgt_blocksize);
19637 	}
19638 
19639 	/*
19640 	 * Check if the media in the device is writable or not
19641 	 */
19642 	if (ISCD(un)) {
19643 		sd_check_for_writable_cd(ssc, SD_PATH_DIRECT_PRIORITY);
19644 	}
19645 
19646 	/*
19647 	 * Note: Maybe let the strategy/partitioning chain worry about getting
19648 	 * valid geometry.
19649 	 */
19650 	mutex_exit(SD_MUTEX(un));
19651 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
19652 
19653 
19654 	if (cmlb_validate(un->un_cmlbhandle, 0,
19655 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
19656 		sd_ssc_fini(ssc);
19657 		return (EIO);
19658 	} else {
19659 		if (un->un_f_pkstats_enabled) {
19660 			sd_set_pstats(un);
19661 			SD_TRACE(SD_LOG_IO_PARTITION, un,
19662 			    "sd_handle_mchange: un:0x%p pstats created and "
19663 			    "set\n", un);
19664 		}
19665 	}
19666 
19667 	/*
19668 	 * Try to lock the door
19669 	 */
19670 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
19671 	    SD_PATH_DIRECT_PRIORITY);
19672 failed:
19673 	if (rval != 0)
19674 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19675 	sd_ssc_fini(ssc);
19676 	return (rval);
19677 }
19678 
19679 
19680 /*
19681  *    Function: sd_send_scsi_DOORLOCK
19682  *
19683  * Description: Issue the scsi DOOR LOCK command
19684  *
19685  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
19686  *                      structure for this target.
19687  *		flag  - SD_REMOVAL_ALLOW
19688  *			SD_REMOVAL_PREVENT
19689  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19690  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19691  *			to use the USCSI "direct" chain and bypass the normal
19692  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19693  *			command is issued as part of an error recovery action.
19694  *
19695  * Return Code: 0   - Success
19696  *		errno return code from sd_ssc_send()
19697  *
19698  *     Context: Can sleep.
19699  */
19700 
19701 static int
19702 sd_send_scsi_DOORLOCK(sd_ssc_t *ssc, int flag, int path_flag)
19703 {
19704 	struct scsi_extended_sense	sense_buf;
19705 	union scsi_cdb		cdb;
19706 	struct uscsi_cmd	ucmd_buf;
19707 	int			status;
19708 	struct sd_lun		*un;
19709 
19710 	ASSERT(ssc != NULL);
19711 	un = ssc->ssc_un;
19712 	ASSERT(un != NULL);
19713 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19714 
19715 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
19716 
19717 	/* already determined doorlock is not supported, fake success */
19718 	if (un->un_f_doorlock_supported == FALSE) {
19719 		return (0);
19720 	}
19721 
19722 	/*
19723 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
19724 	 * ignore the command so we can complete the eject
19725 	 * operation.
19726 	 */
19727 	if (flag == SD_REMOVAL_PREVENT) {
19728 		mutex_enter(SD_MUTEX(un));
19729 		if (un->un_f_ejecting == TRUE) {
19730 			mutex_exit(SD_MUTEX(un));
19731 			return (EAGAIN);
19732 		}
19733 		mutex_exit(SD_MUTEX(un));
19734 	}
19735 
19736 	bzero(&cdb, sizeof (cdb));
19737 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19738 
19739 	cdb.scc_cmd = SCMD_DOORLOCK;
19740 	cdb.cdb_opaque[4] = (uchar_t)flag;
19741 
19742 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19743 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
19744 	ucmd_buf.uscsi_bufaddr	= NULL;
19745 	ucmd_buf.uscsi_buflen	= 0;
19746 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19747 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19748 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
19749 	ucmd_buf.uscsi_timeout	= 15;
19750 
19751 	SD_TRACE(SD_LOG_IO, un,
19752 	    "sd_send_scsi_DOORLOCK: returning sd_ssc_send\n");
19753 
19754 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19755 	    UIO_SYSSPACE, path_flag);
19756 
19757 	if (status == 0)
19758 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19759 
19760 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
19761 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19762 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
19763 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19764 
19765 		/* fake success and skip subsequent doorlock commands */
19766 		un->un_f_doorlock_supported = FALSE;
19767 		return (0);
19768 	}
19769 
19770 	return (status);
19771 }
19772 
19773 /*
19774  *    Function: sd_send_scsi_READ_CAPACITY
19775  *
19776  * Description: This routine uses the scsi READ CAPACITY command to determine
19777  *		the device capacity in number of blocks and the device native
19778  *		block size. If this function returns a failure, then the
19779  *		values in *capp and *lbap are undefined.  If the capacity
19780  *		returned is 0xffffffff then the lun is too large for a
19781  *		normal READ CAPACITY command and the results of a
19782  *		READ CAPACITY 16 will be used instead.
19783  *
19784  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
19785  *		capp - ptr to unsigned 64-bit variable to receive the
19786  *			capacity value from the command.
19787  *		lbap - ptr to unsigned 32-bit varaible to receive the
19788  *			block size value from the command
19789  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19790  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19791  *			to use the USCSI "direct" chain and bypass the normal
19792  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
19793  *			command is issued as part of an error recovery action.
19794  *
19795  * Return Code: 0   - Success
19796  *		EIO - IO error
19797  *		EACCES - Reservation conflict detected
19798  *		EAGAIN - Device is becoming ready
19799  *		errno return code from sd_ssc_send()
19800  *
19801  *     Context: Can sleep.  Blocks until command completes.
19802  */
19803 
19804 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
19805 
19806 static int
19807 sd_send_scsi_READ_CAPACITY(sd_ssc_t *ssc, uint64_t *capp, uint32_t *lbap,
19808     int path_flag)
19809 {
19810 	struct	scsi_extended_sense	sense_buf;
19811 	struct	uscsi_cmd	ucmd_buf;
19812 	union	scsi_cdb	cdb;
19813 	uint32_t		*capacity_buf;
19814 	uint64_t		capacity;
19815 	uint32_t		lbasize;
19816 	uint32_t		pbsize;
19817 	int			status;
19818 	struct sd_lun		*un;
19819 
19820 	ASSERT(ssc != NULL);
19821 
19822 	un = ssc->ssc_un;
19823 	ASSERT(un != NULL);
19824 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19825 	ASSERT(capp != NULL);
19826 	ASSERT(lbap != NULL);
19827 
19828 	SD_TRACE(SD_LOG_IO, un,
19829 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
19830 
19831 	/*
19832 	 * First send a READ_CAPACITY command to the target.
19833 	 * (This command is mandatory under SCSI-2.)
19834 	 *
19835 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
19836 	 * Medium Indicator bit is cleared.  The address field must be
19837 	 * zero if the PMI bit is zero.
19838 	 */
19839 	bzero(&cdb, sizeof (cdb));
19840 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19841 
19842 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
19843 
19844 	cdb.scc_cmd = SCMD_READ_CAPACITY;
19845 
19846 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19847 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19848 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
19849 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
19850 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19851 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
19852 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19853 	ucmd_buf.uscsi_timeout	= 60;
19854 
19855 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
19856 	    UIO_SYSSPACE, path_flag);
19857 
19858 	switch (status) {
19859 	case 0:
19860 		/* Return failure if we did not get valid capacity data. */
19861 		if (ucmd_buf.uscsi_resid != 0) {
19862 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
19863 			    "sd_send_scsi_READ_CAPACITY received invalid "
19864 			    "capacity data");
19865 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19866 			return (EIO);
19867 		}
19868 		/*
19869 		 * Read capacity and block size from the READ CAPACITY 10 data.
19870 		 * This data may be adjusted later due to device specific
19871 		 * issues.
19872 		 *
19873 		 * According to the SCSI spec, the READ CAPACITY 10
19874 		 * command returns the following:
19875 		 *
19876 		 *  bytes 0-3: Maximum logical block address available.
19877 		 *		(MSB in byte:0 & LSB in byte:3)
19878 		 *
19879 		 *  bytes 4-7: Block length in bytes
19880 		 *		(MSB in byte:4 & LSB in byte:7)
19881 		 *
19882 		 */
19883 		capacity = BE_32(capacity_buf[0]);
19884 		lbasize = BE_32(capacity_buf[1]);
19885 
19886 		/*
19887 		 * Done with capacity_buf
19888 		 */
19889 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19890 
19891 		/*
19892 		 * if the reported capacity is set to all 0xf's, then
19893 		 * this disk is too large and requires SBC-2 commands.
19894 		 * Reissue the request using READ CAPACITY 16.
19895 		 */
19896 		if (capacity == 0xffffffff) {
19897 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
19898 			status = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity,
19899 			    &lbasize, &pbsize, path_flag);
19900 			if (status != 0) {
19901 				return (status);
19902 			} else {
19903 				goto rc16_done;
19904 			}
19905 		}
19906 		break;	/* Success! */
19907 	case EIO:
19908 		switch (ucmd_buf.uscsi_status) {
19909 		case STATUS_RESERVATION_CONFLICT:
19910 			status = EACCES;
19911 			break;
19912 		case STATUS_CHECK:
19913 			/*
19914 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
19915 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
19916 			 */
19917 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19918 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
19919 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
19920 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19921 				return (EAGAIN);
19922 			}
19923 			break;
19924 		default:
19925 			break;
19926 		}
19927 		/* FALLTHRU */
19928 	default:
19929 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
19930 		return (status);
19931 	}
19932 
19933 	/*
19934 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
19935 	 * (2352 and 0 are common) so for these devices always force the value
19936 	 * to 2048 as required by the ATAPI specs.
19937 	 */
19938 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
19939 		lbasize = 2048;
19940 	}
19941 
19942 	/*
19943 	 * Get the maximum LBA value from the READ CAPACITY data.
19944 	 * Here we assume that the Partial Medium Indicator (PMI) bit
19945 	 * was cleared when issuing the command. This means that the LBA
19946 	 * returned from the device is the LBA of the last logical block
19947 	 * on the logical unit.  The actual logical block count will be
19948 	 * this value plus one.
19949 	 */
19950 	capacity += 1;
19951 
19952 	/*
19953 	 * Currently, for removable media, the capacity is saved in terms
19954 	 * of un->un_sys_blocksize, so scale the capacity value to reflect this.
19955 	 */
19956 	if (un->un_f_has_removable_media)
19957 		capacity *= (lbasize / un->un_sys_blocksize);
19958 
19959 rc16_done:
19960 
19961 	/*
19962 	 * Copy the values from the READ CAPACITY command into the space
19963 	 * provided by the caller.
19964 	 */
19965 	*capp = capacity;
19966 	*lbap = lbasize;
19967 
19968 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
19969 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
19970 
19971 	/*
19972 	 * Both the lbasize and capacity from the device must be nonzero,
19973 	 * otherwise we assume that the values are not valid and return
19974 	 * failure to the caller. (4203735)
19975 	 */
19976 	if ((capacity == 0) || (lbasize == 0)) {
19977 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
19978 		    "sd_send_scsi_READ_CAPACITY received invalid value "
19979 		    "capacity %llu lbasize %d", capacity, lbasize);
19980 		return (EIO);
19981 	}
19982 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
19983 	return (0);
19984 }
19985 
19986 /*
19987  *    Function: sd_send_scsi_READ_CAPACITY_16
19988  *
19989  * Description: This routine uses the scsi READ CAPACITY 16 command to
19990  *		determine the device capacity in number of blocks and the
19991  *		device native block size.  If this function returns a failure,
19992  *		then the values in *capp and *lbap are undefined.
19993  *		This routine should be called by sd_send_scsi_READ_CAPACITY
19994  *              which will apply any device specific adjustments to capacity
19995  *              and lbasize. One exception is it is also called by
19996  *              sd_get_media_info_ext. In that function, there is no need to
19997  *              adjust the capacity and lbasize.
19998  *
19999  *   Arguments: ssc   - ssc contains ptr to soft state struct for the target
20000  *		capp - ptr to unsigned 64-bit variable to receive the
20001  *			capacity value from the command.
20002  *		lbap - ptr to unsigned 32-bit varaible to receive the
20003  *			block size value from the command
20004  *              psp  - ptr to unsigned 32-bit variable to receive the
20005  *                      physical block size value from the command
20006  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20007  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20008  *			to use the USCSI "direct" chain and bypass the normal
20009  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
20010  *			this command is issued as part of an error recovery
20011  *			action.
20012  *
20013  * Return Code: 0   - Success
20014  *		EIO - IO error
20015  *		EACCES - Reservation conflict detected
20016  *		EAGAIN - Device is becoming ready
20017  *		errno return code from sd_ssc_send()
20018  *
20019  *     Context: Can sleep.  Blocks until command completes.
20020  */
20021 
20022 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
20023 
20024 static int
20025 sd_send_scsi_READ_CAPACITY_16(sd_ssc_t *ssc, uint64_t *capp, uint32_t *lbap,
20026     uint32_t *psp, int path_flag)
20027 {
20028 	struct	scsi_extended_sense	sense_buf;
20029 	struct	uscsi_cmd	ucmd_buf;
20030 	union	scsi_cdb	cdb;
20031 	uint64_t		*capacity16_buf;
20032 	uint64_t		capacity;
20033 	uint32_t		lbasize;
20034 	uint32_t		pbsize;
20035 	uint32_t		lbpb_exp;
20036 	int			status;
20037 	struct sd_lun		*un;
20038 
20039 	ASSERT(ssc != NULL);
20040 
20041 	un = ssc->ssc_un;
20042 	ASSERT(un != NULL);
20043 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20044 	ASSERT(capp != NULL);
20045 	ASSERT(lbap != NULL);
20046 
20047 	SD_TRACE(SD_LOG_IO, un,
20048 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
20049 
20050 	/*
20051 	 * First send a READ_CAPACITY_16 command to the target.
20052 	 *
20053 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
20054 	 * Medium Indicator bit is cleared.  The address field must be
20055 	 * zero if the PMI bit is zero.
20056 	 */
20057 	bzero(&cdb, sizeof (cdb));
20058 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20059 
20060 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
20061 
20062 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20063 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
20064 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
20065 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
20066 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20067 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
20068 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20069 	ucmd_buf.uscsi_timeout	= 60;
20070 
20071 	/*
20072 	 * Read Capacity (16) is a Service Action In command.  One
20073 	 * command byte (0x9E) is overloaded for multiple operations,
20074 	 * with the second CDB byte specifying the desired operation
20075 	 */
20076 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
20077 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
20078 
20079 	/*
20080 	 * Fill in allocation length field
20081 	 */
20082 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
20083 
20084 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20085 	    UIO_SYSSPACE, path_flag);
20086 
20087 	switch (status) {
20088 	case 0:
20089 		/* Return failure if we did not get valid capacity data. */
20090 		if (ucmd_buf.uscsi_resid > 20) {
20091 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20092 			    "sd_send_scsi_READ_CAPACITY_16 received invalid "
20093 			    "capacity data");
20094 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20095 			return (EIO);
20096 		}
20097 
20098 		/*
20099 		 * Read capacity and block size from the READ CAPACITY 16 data.
20100 		 * This data may be adjusted later due to device specific
20101 		 * issues.
20102 		 *
20103 		 * According to the SCSI spec, the READ CAPACITY 16
20104 		 * command returns the following:
20105 		 *
20106 		 *  bytes 0-7: Maximum logical block address available.
20107 		 *		(MSB in byte:0 & LSB in byte:7)
20108 		 *
20109 		 *  bytes 8-11: Block length in bytes
20110 		 *		(MSB in byte:8 & LSB in byte:11)
20111 		 *
20112 		 *  byte 13: LOGICAL BLOCKS PER PHYSICAL BLOCK EXPONENT
20113 		 *
20114 		 *  byte 14:
20115 		 *	bit 7: Thin-Provisioning Enabled
20116 		 *	bit 6: Thin-Provisioning Read Zeros
20117 		 */
20118 		capacity = BE_64(capacity16_buf[0]);
20119 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
20120 		lbpb_exp = (BE_64(capacity16_buf[1]) >> 16) & 0x0f;
20121 
20122 		un->un_thin_flags = 0;
20123 		if (((uint8_t *)capacity16_buf)[14] & (1 << 7))
20124 			un->un_thin_flags |= SD_THIN_PROV_ENABLED;
20125 		if (((uint8_t *)capacity16_buf)[14] & (1 << 6))
20126 			un->un_thin_flags |= SD_THIN_PROV_READ_ZEROS;
20127 
20128 		pbsize = lbasize << lbpb_exp;
20129 
20130 		/*
20131 		 * Done with capacity16_buf
20132 		 */
20133 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20134 
20135 		/*
20136 		 * if the reported capacity is set to all 0xf's, then
20137 		 * this disk is too large.  This could only happen with
20138 		 * a device that supports LBAs larger than 64 bits which
20139 		 * are not defined by any current T10 standards.
20140 		 */
20141 		if (capacity == 0xffffffffffffffff) {
20142 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20143 			    "disk is too large");
20144 			return (EIO);
20145 		}
20146 		break;	/* Success! */
20147 	case EIO:
20148 		switch (ucmd_buf.uscsi_status) {
20149 		case STATUS_RESERVATION_CONFLICT:
20150 			status = EACCES;
20151 			break;
20152 		case STATUS_CHECK:
20153 			/*
20154 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
20155 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
20156 			 */
20157 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20158 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
20159 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
20160 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20161 				return (EAGAIN);
20162 			}
20163 			break;
20164 		default:
20165 			break;
20166 		}
20167 		/* FALLTHRU */
20168 	default:
20169 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
20170 		return (status);
20171 	}
20172 
20173 	/*
20174 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
20175 	 * (2352 and 0 are common) so for these devices always force the value
20176 	 * to 2048 as required by the ATAPI specs.
20177 	 */
20178 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
20179 		lbasize = 2048;
20180 	}
20181 
20182 	/*
20183 	 * Get the maximum LBA value from the READ CAPACITY 16 data.
20184 	 * Here we assume that the Partial Medium Indicator (PMI) bit
20185 	 * was cleared when issuing the command. This means that the LBA
20186 	 * returned from the device is the LBA of the last logical block
20187 	 * on the logical unit.  The actual logical block count will be
20188 	 * this value plus one.
20189 	 */
20190 	capacity += 1;
20191 
20192 	/*
20193 	 * Currently, for removable media, the capacity is saved in terms
20194 	 * of un->un_sys_blocksize, so scale the capacity value to reflect this.
20195 	 */
20196 	if (un->un_f_has_removable_media)
20197 		capacity *= (lbasize / un->un_sys_blocksize);
20198 
20199 	*capp = capacity;
20200 	*lbap = lbasize;
20201 	*psp = pbsize;
20202 
20203 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
20204 	    "capacity:0x%llx  lbasize:0x%x, pbsize: 0x%x\n",
20205 	    capacity, lbasize, pbsize);
20206 
20207 	if ((capacity == 0) || (lbasize == 0) || (pbsize == 0)) {
20208 		sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
20209 		    "sd_send_scsi_READ_CAPACITY_16 received invalid value "
20210 		    "capacity %llu lbasize %d pbsize %d", capacity, lbasize);
20211 		return (EIO);
20212 	}
20213 
20214 	sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20215 	return (0);
20216 }
20217 
20218 
20219 /*
20220  *    Function: sd_send_scsi_START_STOP_UNIT
20221  *
20222  * Description: Issue a scsi START STOP UNIT command to the target.
20223  *
20224  *   Arguments: ssc    - ssc contatins pointer to driver soft state (unit)
20225  *                       structure for this target.
20226  *      pc_flag - SD_POWER_CONDITION
20227  *                SD_START_STOP
20228  *		flag  - SD_TARGET_START
20229  *			SD_TARGET_STOP
20230  *			SD_TARGET_EJECT
20231  *			SD_TARGET_CLOSE
20232  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
20233  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
20234  *			to use the USCSI "direct" chain and bypass the normal
20235  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
20236  *			command is issued as part of an error recovery action.
20237  *
20238  * Return Code: 0   - Success
20239  *		EIO - IO error
20240  *		EACCES - Reservation conflict detected
20241  *		ENXIO  - Not Ready, medium not present
20242  *		errno return code from sd_ssc_send()
20243  *
20244  *     Context: Can sleep.
20245  */
20246 
20247 static int
20248 sd_send_scsi_START_STOP_UNIT(sd_ssc_t *ssc, int pc_flag, int flag,
20249     int path_flag)
20250 {
20251 	struct	scsi_extended_sense	sense_buf;
20252 	union scsi_cdb		cdb;
20253 	struct uscsi_cmd	ucmd_buf;
20254 	int			status;
20255 	struct sd_lun		*un;
20256 
20257 	ASSERT(ssc != NULL);
20258 	un = ssc->ssc_un;
20259 	ASSERT(un != NULL);
20260 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20261 
20262 	SD_TRACE(SD_LOG_IO, un,
20263 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
20264 
20265 	if (un->un_f_check_start_stop &&
20266 	    (pc_flag == SD_START_STOP) &&
20267 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
20268 	    (un->un_f_start_stop_supported != TRUE)) {
20269 		return (0);
20270 	}
20271 
20272 	/*
20273 	 * If we are performing an eject operation and
20274 	 * we receive any command other than SD_TARGET_EJECT
20275 	 * we should immediately return.
20276 	 */
20277 	if (flag != SD_TARGET_EJECT) {
20278 		mutex_enter(SD_MUTEX(un));
20279 		if (un->un_f_ejecting == TRUE) {
20280 			mutex_exit(SD_MUTEX(un));
20281 			return (EAGAIN);
20282 		}
20283 		mutex_exit(SD_MUTEX(un));
20284 	}
20285 
20286 	bzero(&cdb, sizeof (cdb));
20287 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20288 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20289 
20290 	cdb.scc_cmd = SCMD_START_STOP;
20291 	cdb.cdb_opaque[4] = (pc_flag == SD_POWER_CONDITION) ?
20292 	    (uchar_t)(flag << 4) : (uchar_t)flag;
20293 
20294 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20295 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20296 	ucmd_buf.uscsi_bufaddr	= NULL;
20297 	ucmd_buf.uscsi_buflen	= 0;
20298 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20299 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20300 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20301 	ucmd_buf.uscsi_timeout	= 200;
20302 
20303 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20304 	    UIO_SYSSPACE, path_flag);
20305 
20306 	switch (status) {
20307 	case 0:
20308 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20309 		break;	/* Success! */
20310 	case EIO:
20311 		switch (ucmd_buf.uscsi_status) {
20312 		case STATUS_RESERVATION_CONFLICT:
20313 			status = EACCES;
20314 			break;
20315 		case STATUS_CHECK:
20316 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
20317 				switch (scsi_sense_key(
20318 				    (uint8_t *)&sense_buf)) {
20319 				case KEY_ILLEGAL_REQUEST:
20320 					status = ENOTSUP;
20321 					break;
20322 				case KEY_NOT_READY:
20323 					if (scsi_sense_asc(
20324 					    (uint8_t *)&sense_buf)
20325 					    == 0x3A) {
20326 						status = ENXIO;
20327 					}
20328 					break;
20329 				default:
20330 					break;
20331 				}
20332 			}
20333 			break;
20334 		default:
20335 			break;
20336 		}
20337 		break;
20338 	default:
20339 		break;
20340 	}
20341 
20342 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
20343 
20344 	return (status);
20345 }
20346 
20347 
20348 /*
20349  *    Function: sd_start_stop_unit_callback
20350  *
20351  * Description: timeout(9F) callback to begin recovery process for a
20352  *		device that has spun down.
20353  *
20354  *   Arguments: arg - pointer to associated softstate struct.
20355  *
20356  *     Context: Executes in a timeout(9F) thread context
20357  */
20358 
20359 static void
20360 sd_start_stop_unit_callback(void *arg)
20361 {
20362 	struct sd_lun	*un = arg;
20363 	ASSERT(un != NULL);
20364 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20365 
20366 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
20367 
20368 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
20369 }
20370 
20371 
20372 /*
20373  *    Function: sd_start_stop_unit_task
20374  *
20375  * Description: Recovery procedure when a drive is spun down.
20376  *
20377  *   Arguments: arg - pointer to associated softstate struct.
20378  *
20379  *     Context: Executes in a taskq() thread context
20380  */
20381 
20382 static void
20383 sd_start_stop_unit_task(void *arg)
20384 {
20385 	struct sd_lun	*un = arg;
20386 	sd_ssc_t	*ssc;
20387 	int		power_level;
20388 	int		rval;
20389 
20390 	ASSERT(un != NULL);
20391 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20392 
20393 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
20394 
20395 	/*
20396 	 * Some unformatted drives report not ready error, no need to
20397 	 * restart if format has been initiated.
20398 	 */
20399 	mutex_enter(SD_MUTEX(un));
20400 	if (un->un_f_format_in_progress == TRUE) {
20401 		mutex_exit(SD_MUTEX(un));
20402 		return;
20403 	}
20404 	mutex_exit(SD_MUTEX(un));
20405 
20406 	ssc = sd_ssc_init(un);
20407 	/*
20408 	 * When a START STOP command is issued from here, it is part of a
20409 	 * failure recovery operation and must be issued before any other
20410 	 * commands, including any pending retries. Thus it must be sent
20411 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
20412 	 * succeeds or not, we will start I/O after the attempt.
20413 	 * If power condition is supported and the current power level
20414 	 * is capable of performing I/O, we should set the power condition
20415 	 * to that level. Otherwise, set the power condition to ACTIVE.
20416 	 */
20417 	if (un->un_f_power_condition_supported) {
20418 		mutex_enter(SD_MUTEX(un));
20419 		ASSERT(SD_PM_IS_LEVEL_VALID(un, un->un_power_level));
20420 		power_level = sd_pwr_pc.ran_perf[un->un_power_level]
20421 		    > 0 ? un->un_power_level : SD_SPINDLE_ACTIVE;
20422 		mutex_exit(SD_MUTEX(un));
20423 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_POWER_CONDITION,
20424 		    sd_pl2pc[power_level], SD_PATH_DIRECT_PRIORITY);
20425 	} else {
20426 		rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
20427 		    SD_TARGET_START, SD_PATH_DIRECT_PRIORITY);
20428 	}
20429 
20430 	if (rval != 0)
20431 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
20432 	sd_ssc_fini(ssc);
20433 	/*
20434 	 * The above call blocks until the START_STOP_UNIT command completes.
20435 	 * Now that it has completed, we must re-try the original IO that
20436 	 * received the NOT READY condition in the first place. There are
20437 	 * three possible conditions here:
20438 	 *
20439 	 *  (1) The original IO is on un_retry_bp.
20440 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
20441 	 *	is NULL.
20442 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
20443 	 *	points to some other, unrelated bp.
20444 	 *
20445 	 * For each case, we must call sd_start_cmds() with un_retry_bp
20446 	 * as the argument. If un_retry_bp is NULL, this will initiate
20447 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
20448 	 * then this will process the bp on un_retry_bp. That may or may not
20449 	 * be the original IO, but that does not matter: the important thing
20450 	 * is to keep the IO processing going at this point.
20451 	 *
20452 	 * Note: This is a very specific error recovery sequence associated
20453 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
20454 	 * serialize the I/O with completion of the spin-up.
20455 	 */
20456 	mutex_enter(SD_MUTEX(un));
20457 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
20458 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
20459 	    un, un->un_retry_bp);
20460 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
20461 	sd_start_cmds(un, un->un_retry_bp);
20462 	mutex_exit(SD_MUTEX(un));
20463 
20464 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
20465 }
20466 
20467 
20468 /*
20469  *    Function: sd_send_scsi_INQUIRY
20470  *
20471  * Description: Issue the scsi INQUIRY command.
20472  *
20473  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20474  *                      structure for this target.
20475  *		bufaddr
20476  *		buflen
20477  *		evpd
20478  *		page_code
20479  *		page_length
20480  *
20481  * Return Code: 0   - Success
20482  *		errno return code from sd_ssc_send()
20483  *
20484  *     Context: Can sleep. Does not return until command is completed.
20485  */
20486 
20487 static int
20488 sd_send_scsi_INQUIRY(sd_ssc_t *ssc, uchar_t *bufaddr, size_t buflen,
20489     uchar_t evpd, uchar_t page_code, size_t *residp)
20490 {
20491 	union scsi_cdb		cdb;
20492 	struct uscsi_cmd	ucmd_buf;
20493 	int			status;
20494 	struct sd_lun		*un;
20495 
20496 	ASSERT(ssc != NULL);
20497 	un = ssc->ssc_un;
20498 	ASSERT(un != NULL);
20499 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20500 	ASSERT(bufaddr != NULL);
20501 
20502 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
20503 
20504 	bzero(&cdb, sizeof (cdb));
20505 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20506 	bzero(bufaddr, buflen);
20507 
20508 	cdb.scc_cmd = SCMD_INQUIRY;
20509 	cdb.cdb_opaque[1] = evpd;
20510 	cdb.cdb_opaque[2] = page_code;
20511 	FORMG0COUNT(&cdb, buflen);
20512 
20513 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20514 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20515 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
20516 	ucmd_buf.uscsi_buflen	= buflen;
20517 	ucmd_buf.uscsi_rqbuf	= NULL;
20518 	ucmd_buf.uscsi_rqlen	= 0;
20519 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
20520 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
20521 
20522 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20523 	    UIO_SYSSPACE, SD_PATH_DIRECT);
20524 
20525 	/*
20526 	 * Only handle status == 0, the upper-level caller
20527 	 * will put different assessment based on the context.
20528 	 */
20529 	if (status == 0)
20530 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20531 
20532 	if ((status == 0) && (residp != NULL)) {
20533 		*residp = ucmd_buf.uscsi_resid;
20534 	}
20535 
20536 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
20537 
20538 	return (status);
20539 }
20540 
20541 
20542 /*
20543  *    Function: sd_send_scsi_TEST_UNIT_READY
20544  *
20545  * Description: Issue the scsi TEST UNIT READY command.
20546  *		This routine can be told to set the flag USCSI_DIAGNOSE to
20547  *		prevent retrying failed commands. Use this when the intent
20548  *		is either to check for device readiness, to clear a Unit
20549  *		Attention, or to clear any outstanding sense data.
20550  *		However under specific conditions the expected behavior
20551  *		is for retries to bring a device ready, so use the flag
20552  *		with caution.
20553  *
20554  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20555  *                      structure for this target.
20556  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
20557  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
20558  *			0: dont check for media present, do retries on cmd.
20559  *
20560  * Return Code: 0   - Success
20561  *		EIO - IO error
20562  *		EACCES - Reservation conflict detected
20563  *		ENXIO  - Not Ready, medium not present
20564  *		errno return code from sd_ssc_send()
20565  *
20566  *     Context: Can sleep. Does not return until command is completed.
20567  */
20568 
20569 static int
20570 sd_send_scsi_TEST_UNIT_READY(sd_ssc_t *ssc, int flag)
20571 {
20572 	struct	scsi_extended_sense	sense_buf;
20573 	union scsi_cdb		cdb;
20574 	struct uscsi_cmd	ucmd_buf;
20575 	int			status;
20576 	struct sd_lun		*un;
20577 
20578 	ASSERT(ssc != NULL);
20579 	un = ssc->ssc_un;
20580 	ASSERT(un != NULL);
20581 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20582 
20583 	SD_TRACE(SD_LOG_IO, un,
20584 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
20585 
20586 	/*
20587 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
20588 	 * timeouts when they receive a TUR and the queue is not empty. Check
20589 	 * the configuration flag set during attach (indicating the drive has
20590 	 * this firmware bug) and un_ncmds_in_transport before issuing the
20591 	 * TUR. If there are
20592 	 * pending commands return success, this is a bit arbitrary but is ok
20593 	 * for non-removables (i.e. the eliteI disks) and non-clustering
20594 	 * configurations.
20595 	 */
20596 	if (un->un_f_cfg_tur_check == TRUE) {
20597 		mutex_enter(SD_MUTEX(un));
20598 		if (un->un_ncmds_in_transport != 0) {
20599 			mutex_exit(SD_MUTEX(un));
20600 			return (0);
20601 		}
20602 		mutex_exit(SD_MUTEX(un));
20603 	}
20604 
20605 	bzero(&cdb, sizeof (cdb));
20606 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20607 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20608 
20609 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
20610 
20611 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20612 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
20613 	ucmd_buf.uscsi_bufaddr	= NULL;
20614 	ucmd_buf.uscsi_buflen	= 0;
20615 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20616 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20617 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
20618 
20619 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
20620 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
20621 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
20622 	}
20623 	ucmd_buf.uscsi_timeout	= 60;
20624 
20625 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20626 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
20627 	    SD_PATH_STANDARD));
20628 
20629 	switch (status) {
20630 	case 0:
20631 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20632 		break;	/* Success! */
20633 	case EIO:
20634 		switch (ucmd_buf.uscsi_status) {
20635 		case STATUS_RESERVATION_CONFLICT:
20636 			status = EACCES;
20637 			break;
20638 		case STATUS_CHECK:
20639 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
20640 				break;
20641 			}
20642 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20643 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20644 			    KEY_NOT_READY) &&
20645 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
20646 				status = ENXIO;
20647 			}
20648 			break;
20649 		default:
20650 			break;
20651 		}
20652 		break;
20653 	default:
20654 		break;
20655 	}
20656 
20657 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
20658 
20659 	return (status);
20660 }
20661 
20662 /*
20663  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
20664  *
20665  * Description: Issue the scsi PERSISTENT RESERVE IN command.
20666  *
20667  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
20668  *                      structure for this target.
20669  *
20670  * Return Code: 0   - Success
20671  *		EACCES
20672  *		ENOTSUP
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_PERSISTENT_RESERVE_IN(sd_ssc_t *ssc, uchar_t usr_cmd,
20680     uint16_t data_len, uchar_t *data_bufp)
20681 {
20682 	struct scsi_extended_sense	sense_buf;
20683 	union scsi_cdb		cdb;
20684 	struct uscsi_cmd	ucmd_buf;
20685 	int			status;
20686 	int			no_caller_buf = FALSE;
20687 	struct sd_lun		*un;
20688 
20689 	ASSERT(ssc != NULL);
20690 	un = ssc->ssc_un;
20691 	ASSERT(un != NULL);
20692 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20693 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
20694 
20695 	SD_TRACE(SD_LOG_IO, un,
20696 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
20697 
20698 	bzero(&cdb, sizeof (cdb));
20699 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20700 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20701 	if (data_bufp == NULL) {
20702 		/* Allocate a default buf if the caller did not give one */
20703 		ASSERT(data_len == 0);
20704 		data_len  = MHIOC_RESV_KEY_SIZE;
20705 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
20706 		no_caller_buf = TRUE;
20707 	}
20708 
20709 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
20710 	cdb.cdb_opaque[1] = usr_cmd;
20711 	FORMG1COUNT(&cdb, data_len);
20712 
20713 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20714 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20715 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
20716 	ucmd_buf.uscsi_buflen	= data_len;
20717 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20718 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20719 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
20720 	ucmd_buf.uscsi_timeout	= 60;
20721 
20722 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20723 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20724 
20725 	switch (status) {
20726 	case 0:
20727 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20728 
20729 		break;	/* Success! */
20730 	case EIO:
20731 		switch (ucmd_buf.uscsi_status) {
20732 		case STATUS_RESERVATION_CONFLICT:
20733 			status = EACCES;
20734 			break;
20735 		case STATUS_CHECK:
20736 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20737 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20738 			    KEY_ILLEGAL_REQUEST)) {
20739 				status = ENOTSUP;
20740 			}
20741 			break;
20742 		default:
20743 			break;
20744 		}
20745 		break;
20746 	default:
20747 		break;
20748 	}
20749 
20750 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
20751 
20752 	if (no_caller_buf == TRUE) {
20753 		kmem_free(data_bufp, data_len);
20754 	}
20755 
20756 	return (status);
20757 }
20758 
20759 
20760 /*
20761  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
20762  *
20763  * Description: This routine is the driver entry point for handling CD-ROM
20764  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
20765  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
20766  *		device.
20767  *
20768  *   Arguments: ssc  -  ssc contains un - pointer to soft state struct
20769  *                      for the target.
20770  *		usr_cmd SCSI-3 reservation facility command (one of
20771  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
20772  *			SD_SCSI3_PREEMPTANDABORT, SD_SCSI3_CLEAR)
20773  *		usr_bufp - user provided pointer register, reserve descriptor or
20774  *			preempt and abort structure (mhioc_register_t,
20775  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
20776  *
20777  * Return Code: 0   - Success
20778  *		EACCES
20779  *		ENOTSUP
20780  *		errno return code from sd_ssc_send()
20781  *
20782  *     Context: Can sleep. Does not return until command is completed.
20783  */
20784 
20785 static int
20786 sd_send_scsi_PERSISTENT_RESERVE_OUT(sd_ssc_t *ssc, uchar_t usr_cmd,
20787     uchar_t *usr_bufp)
20788 {
20789 	struct scsi_extended_sense	sense_buf;
20790 	union scsi_cdb		cdb;
20791 	struct uscsi_cmd	ucmd_buf;
20792 	int			status;
20793 	uchar_t			data_len = sizeof (sd_prout_t);
20794 	sd_prout_t		*prp;
20795 	struct sd_lun		*un;
20796 
20797 	ASSERT(ssc != NULL);
20798 	un = ssc->ssc_un;
20799 	ASSERT(un != NULL);
20800 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20801 	ASSERT(data_len == 24);	/* required by scsi spec */
20802 
20803 	SD_TRACE(SD_LOG_IO, un,
20804 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
20805 
20806 	if (usr_bufp == NULL) {
20807 		return (EINVAL);
20808 	}
20809 
20810 	bzero(&cdb, sizeof (cdb));
20811 	bzero(&ucmd_buf, sizeof (ucmd_buf));
20812 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
20813 	prp = kmem_zalloc(data_len, KM_SLEEP);
20814 
20815 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
20816 	cdb.cdb_opaque[1] = usr_cmd;
20817 	FORMG1COUNT(&cdb, data_len);
20818 
20819 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
20820 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
20821 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
20822 	ucmd_buf.uscsi_buflen	= data_len;
20823 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
20824 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
20825 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
20826 	ucmd_buf.uscsi_timeout	= 60;
20827 
20828 	switch (usr_cmd) {
20829 	case SD_SCSI3_REGISTER: {
20830 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
20831 
20832 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20833 		bcopy(ptr->newkey.key, prp->service_key,
20834 		    MHIOC_RESV_KEY_SIZE);
20835 		prp->aptpl = ptr->aptpl;
20836 		break;
20837 	}
20838 	case SD_SCSI3_CLEAR: {
20839 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
20840 
20841 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20842 		break;
20843 	}
20844 	case SD_SCSI3_RESERVE:
20845 	case SD_SCSI3_RELEASE: {
20846 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
20847 
20848 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20849 		prp->scope_address = BE_32(ptr->scope_specific_addr);
20850 		cdb.cdb_opaque[2] = ptr->type;
20851 		break;
20852 	}
20853 	case SD_SCSI3_PREEMPTANDABORT: {
20854 		mhioc_preemptandabort_t *ptr =
20855 		    (mhioc_preemptandabort_t *)usr_bufp;
20856 
20857 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
20858 		bcopy(ptr->victim_key.key, prp->service_key,
20859 		    MHIOC_RESV_KEY_SIZE);
20860 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
20861 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
20862 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
20863 		break;
20864 	}
20865 	case SD_SCSI3_REGISTERANDIGNOREKEY:
20866 	{
20867 		mhioc_registerandignorekey_t *ptr;
20868 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
20869 		bcopy(ptr->newkey.key,
20870 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
20871 		prp->aptpl = ptr->aptpl;
20872 		break;
20873 	}
20874 	default:
20875 		ASSERT(FALSE);
20876 		break;
20877 	}
20878 
20879 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
20880 	    UIO_SYSSPACE, SD_PATH_STANDARD);
20881 
20882 	switch (status) {
20883 	case 0:
20884 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
20885 		break;	/* Success! */
20886 	case EIO:
20887 		switch (ucmd_buf.uscsi_status) {
20888 		case STATUS_RESERVATION_CONFLICT:
20889 			status = EACCES;
20890 			break;
20891 		case STATUS_CHECK:
20892 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
20893 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
20894 			    KEY_ILLEGAL_REQUEST)) {
20895 				status = ENOTSUP;
20896 			}
20897 			break;
20898 		default:
20899 			break;
20900 		}
20901 		break;
20902 	default:
20903 		break;
20904 	}
20905 
20906 	kmem_free(prp, data_len);
20907 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
20908 	return (status);
20909 }
20910 
20911 
20912 /*
20913  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
20914  *
20915  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
20916  *
20917  *   Arguments: un - pointer to the target's soft state struct
20918  *              dkc - pointer to the callback structure
20919  *
20920  * Return Code: 0 - success
20921  *		errno-type error code
20922  *
20923  *     Context: kernel thread context only.
20924  *
20925  *  _______________________________________________________________
20926  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
20927  * |FLUSH_VOLATILE|              | operation                       |
20928  * |______________|______________|_________________________________|
20929  * | 0            | NULL         | Synchronous flush on both       |
20930  * |              |              | volatile and non-volatile cache |
20931  * |______________|______________|_________________________________|
20932  * | 1            | NULL         | Synchronous flush on volatile   |
20933  * |              |              | cache; disk drivers may suppress|
20934  * |              |              | flush if disk table indicates   |
20935  * |              |              | non-volatile cache              |
20936  * |______________|______________|_________________________________|
20937  * | 0            | !NULL        | Asynchronous flush on both      |
20938  * |              |              | volatile and non-volatile cache;|
20939  * |______________|______________|_________________________________|
20940  * | 1            | !NULL        | Asynchronous flush on volatile  |
20941  * |              |              | cache; disk drivers may suppress|
20942  * |              |              | flush if disk table indicates   |
20943  * |              |              | non-volatile cache              |
20944  * |______________|______________|_________________________________|
20945  *
20946  */
20947 
20948 static int
20949 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
20950 {
20951 	struct sd_uscsi_info	*uip;
20952 	struct uscsi_cmd	*uscmd;
20953 	union scsi_cdb		*cdb;
20954 	struct buf		*bp;
20955 	int			rval = 0;
20956 	int			is_async;
20957 
20958 	SD_TRACE(SD_LOG_IO, un,
20959 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
20960 
20961 	ASSERT(un != NULL);
20962 	ASSERT(!mutex_owned(SD_MUTEX(un)));
20963 
20964 	if (dkc == NULL || dkc->dkc_callback == NULL) {
20965 		is_async = FALSE;
20966 	} else {
20967 		is_async = TRUE;
20968 	}
20969 
20970 	mutex_enter(SD_MUTEX(un));
20971 	/* check whether cache flush should be suppressed */
20972 	if (un->un_f_suppress_cache_flush == TRUE) {
20973 		mutex_exit(SD_MUTEX(un));
20974 		/*
20975 		 * suppress the cache flush if the device is told to do
20976 		 * so by sd.conf or disk table
20977 		 */
20978 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
20979 		    skip the cache flush since suppress_cache_flush is %d!\n",
20980 		    un->un_f_suppress_cache_flush);
20981 
20982 		if (is_async == TRUE) {
20983 			/* invoke callback for asynchronous flush */
20984 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
20985 		}
20986 		return (rval);
20987 	}
20988 	mutex_exit(SD_MUTEX(un));
20989 
20990 	/*
20991 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
20992 	 * set properly
20993 	 */
20994 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
20995 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
20996 
20997 	mutex_enter(SD_MUTEX(un));
20998 	if (dkc != NULL && un->un_f_sync_nv_supported &&
20999 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
21000 		/*
21001 		 * if the device supports SYNC_NV bit, turn on
21002 		 * the SYNC_NV bit to only flush volatile cache
21003 		 */
21004 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
21005 	}
21006 	mutex_exit(SD_MUTEX(un));
21007 
21008 	/*
21009 	 * First get some memory for the uscsi_cmd struct and cdb
21010 	 * and initialize for SYNCHRONIZE_CACHE cmd.
21011 	 */
21012 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
21013 	uscmd->uscsi_cdblen = CDB_GROUP1;
21014 	uscmd->uscsi_cdb = (caddr_t)cdb;
21015 	uscmd->uscsi_bufaddr = NULL;
21016 	uscmd->uscsi_buflen = 0;
21017 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
21018 	uscmd->uscsi_rqlen = SENSE_LENGTH;
21019 	uscmd->uscsi_rqresid = SENSE_LENGTH;
21020 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
21021 	uscmd->uscsi_timeout = sd_io_time;
21022 
21023 	/*
21024 	 * Allocate an sd_uscsi_info struct and fill it with the info
21025 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
21026 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
21027 	 * since we allocate the buf here in this function, we do not
21028 	 * need to preserve the prior contents of b_private.
21029 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
21030 	 */
21031 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
21032 	uip->ui_flags = SD_PATH_DIRECT;
21033 	uip->ui_cmdp  = uscmd;
21034 
21035 	bp = getrbuf(KM_SLEEP);
21036 	bp->b_private = uip;
21037 
21038 	/*
21039 	 * Setup buffer to carry uscsi request.
21040 	 */
21041 	bp->b_flags  = B_BUSY;
21042 	bp->b_bcount = 0;
21043 	bp->b_blkno  = 0;
21044 
21045 	if (is_async == TRUE) {
21046 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
21047 		uip->ui_dkc = *dkc;
21048 	}
21049 
21050 	bp->b_edev = SD_GET_DEV(un);
21051 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
21052 
21053 	/*
21054 	 * Unset un_f_sync_cache_required flag
21055 	 */
21056 	mutex_enter(SD_MUTEX(un));
21057 	un->un_f_sync_cache_required = FALSE;
21058 	mutex_exit(SD_MUTEX(un));
21059 
21060 	(void) sd_uscsi_strategy(bp);
21061 
21062 	/*
21063 	 * If synchronous request, wait for completion
21064 	 * If async just return and let b_iodone callback
21065 	 * cleanup.
21066 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
21067 	 * but it was also incremented in sd_uscsi_strategy(), so
21068 	 * we should be ok.
21069 	 */
21070 	if (is_async == FALSE) {
21071 		(void) biowait(bp);
21072 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
21073 	}
21074 
21075 	return (rval);
21076 }
21077 
21078 
21079 static int
21080 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
21081 {
21082 	struct sd_uscsi_info *uip;
21083 	struct uscsi_cmd *uscmd;
21084 	uint8_t *sense_buf;
21085 	struct sd_lun *un;
21086 	int status;
21087 	union scsi_cdb *cdb;
21088 
21089 	uip = (struct sd_uscsi_info *)(bp->b_private);
21090 	ASSERT(uip != NULL);
21091 
21092 	uscmd = uip->ui_cmdp;
21093 	ASSERT(uscmd != NULL);
21094 
21095 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
21096 	ASSERT(sense_buf != NULL);
21097 
21098 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
21099 	ASSERT(un != NULL);
21100 
21101 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
21102 
21103 	status = geterror(bp);
21104 	switch (status) {
21105 	case 0:
21106 		break;	/* Success! */
21107 	case EIO:
21108 		switch (uscmd->uscsi_status) {
21109 		case STATUS_RESERVATION_CONFLICT:
21110 			/* Ignore reservation conflict */
21111 			status = 0;
21112 			goto done;
21113 
21114 		case STATUS_CHECK:
21115 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
21116 			    (scsi_sense_key(sense_buf) ==
21117 			    KEY_ILLEGAL_REQUEST)) {
21118 				/* Ignore Illegal Request error */
21119 				if (cdb->cdb_un.tag&SD_SYNC_NV_BIT) {
21120 					mutex_enter(SD_MUTEX(un));
21121 					un->un_f_sync_nv_supported = FALSE;
21122 					mutex_exit(SD_MUTEX(un));
21123 					status = 0;
21124 					SD_TRACE(SD_LOG_IO, un,
21125 					    "un_f_sync_nv_supported \
21126 					    is set to false.\n");
21127 					goto done;
21128 				}
21129 
21130 				mutex_enter(SD_MUTEX(un));
21131 				un->un_f_sync_cache_supported = FALSE;
21132 				mutex_exit(SD_MUTEX(un));
21133 				SD_TRACE(SD_LOG_IO, un,
21134 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
21135 				    un_f_sync_cache_supported set to false \
21136 				    with asc = %x, ascq = %x\n",
21137 				    scsi_sense_asc(sense_buf),
21138 				    scsi_sense_ascq(sense_buf));
21139 				status = ENOTSUP;
21140 				goto done;
21141 			}
21142 			break;
21143 		default:
21144 			break;
21145 		}
21146 		/* FALLTHRU */
21147 	default:
21148 		/*
21149 		 * Turn on the un_f_sync_cache_required flag
21150 		 * since the SYNC CACHE command failed
21151 		 */
21152 		mutex_enter(SD_MUTEX(un));
21153 		un->un_f_sync_cache_required = TRUE;
21154 		mutex_exit(SD_MUTEX(un));
21155 
21156 		/*
21157 		 * Don't log an error message if this device
21158 		 * has removable media.
21159 		 */
21160 		if (!un->un_f_has_removable_media) {
21161 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
21162 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
21163 		}
21164 		break;
21165 	}
21166 
21167 done:
21168 	if (uip->ui_dkc.dkc_callback != NULL) {
21169 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
21170 	}
21171 
21172 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
21173 	freerbuf(bp);
21174 	kmem_free(uip, sizeof (struct sd_uscsi_info));
21175 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
21176 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
21177 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
21178 
21179 	return (status);
21180 }
21181 
21182 /*
21183  * Issues a single SCSI UNMAP command with a prepared UNMAP parameter list.
21184  * Returns zero on success, or the non-zero command error code on failure.
21185  */
21186 static int
21187 sd_send_scsi_UNMAP_issue_one(sd_ssc_t *ssc, unmap_param_hdr_t *uph,
21188     uint64_t num_descr, uint64_t bytes)
21189 {
21190 	struct sd_lun		*un = ssc->ssc_un;
21191 	struct scsi_extended_sense	sense_buf;
21192 	union scsi_cdb		cdb;
21193 	struct uscsi_cmd	ucmd_buf;
21194 	int			status;
21195 	const uint64_t		param_size = sizeof (unmap_param_hdr_t) +
21196 	    num_descr * sizeof (unmap_blk_descr_t);
21197 
21198 	ASSERT3U(param_size - 2, <=, UINT16_MAX);
21199 	uph->uph_data_len = BE_16(param_size - 2);
21200 	uph->uph_descr_data_len = BE_16(param_size - 8);
21201 
21202 	bzero(&cdb, sizeof (cdb));
21203 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21204 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21205 
21206 	cdb.scc_cmd = SCMD_UNMAP;
21207 	FORMG1COUNT(&cdb, param_size);
21208 
21209 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21210 	ucmd_buf.uscsi_cdblen	= (uchar_t)CDB_GROUP1;
21211 	ucmd_buf.uscsi_bufaddr	= (caddr_t)uph;
21212 	ucmd_buf.uscsi_buflen	= param_size;
21213 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21214 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21215 	ucmd_buf.uscsi_flags	= USCSI_WRITE | USCSI_RQENABLE | USCSI_SILENT;
21216 	ucmd_buf.uscsi_timeout	= un->un_cmd_timeout;
21217 
21218 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL, UIO_SYSSPACE,
21219 	    SD_PATH_STANDARD);
21220 
21221 	switch (status) {
21222 	case 0:
21223 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21224 
21225 		if (un->un_unmapstats) {
21226 			atomic_inc_64(&un->un_unmapstats->us_cmds.value.ui64);
21227 			atomic_add_64(&un->un_unmapstats->us_extents.value.ui64,
21228 			    num_descr);
21229 			atomic_add_64(&un->un_unmapstats->us_bytes.value.ui64,
21230 			    bytes);
21231 		}
21232 		break;	/* Success! */
21233 	case EIO:
21234 		if (un->un_unmapstats)
21235 			atomic_inc_64(&un->un_unmapstats->us_errs.value.ui64);
21236 		switch (ucmd_buf.uscsi_status) {
21237 		case STATUS_RESERVATION_CONFLICT:
21238 			status = EACCES;
21239 			break;
21240 		default:
21241 			break;
21242 		}
21243 		break;
21244 	default:
21245 		if (un->un_unmapstats)
21246 			atomic_inc_64(&un->un_unmapstats->us_errs.value.ui64);
21247 		break;
21248 	}
21249 
21250 	return (status);
21251 }
21252 
21253 /*
21254  * Returns a pointer to the i'th block descriptor inside an UNMAP param list.
21255  */
21256 static inline unmap_blk_descr_t *
21257 UNMAP_blk_descr_i(void *buf, size_t i)
21258 {
21259 	return ((unmap_blk_descr_t *)((uintptr_t)buf +
21260 	    sizeof (unmap_param_hdr_t) + (i * sizeof (unmap_blk_descr_t))));
21261 }
21262 
21263 /*
21264  * Takes the list of extents from sd_send_scsi_UNMAP, chops it up, prepares
21265  * UNMAP block descriptors and issues individual SCSI UNMAP commands. While
21266  * doing so we consult the block limits to determine at most how many
21267  * extents and LBAs we can UNMAP in one command.
21268  * If a command fails for whatever, reason, extent list processing is aborted
21269  * and the failed command's status is returned. Otherwise returns 0 on
21270  * success.
21271  */
21272 static int
21273 sd_send_scsi_UNMAP_issue(dev_t dev, sd_ssc_t *ssc, const dkioc_free_list_t *dfl)
21274 {
21275 	struct sd_lun		*un = ssc->ssc_un;
21276 	unmap_param_hdr_t	*uph;
21277 	sd_blk_limits_t		*lim = &un->un_blk_lim;
21278 	int			rval = 0;
21279 	int			partition;
21280 	/* partition offset & length in system blocks */
21281 	diskaddr_t		part_off_sysblks = 0, part_len_sysblks = 0;
21282 	uint64_t		part_off, part_len;
21283 	uint64_t		descr_cnt_lim, byte_cnt_lim;
21284 	uint64_t		descr_issued = 0, bytes_issued = 0;
21285 
21286 	uph = kmem_zalloc(SD_UNMAP_PARAM_LIST_MAXSZ, KM_SLEEP);
21287 
21288 	partition = SDPART(dev);
21289 	rval = cmlb_partinfo(un->un_cmlbhandle, partition, &part_len_sysblks,
21290 	    &part_off_sysblks, NULL, NULL, (void *)SD_PATH_DIRECT);
21291 	if (rval != 0)
21292 		goto out;
21293 	part_off = SD_SYSBLOCKS2BYTES(part_off_sysblks);
21294 	part_len = SD_SYSBLOCKS2BYTES(part_len_sysblks);
21295 
21296 	ASSERT(un->un_blk_lim.lim_max_unmap_lba_cnt != 0);
21297 	ASSERT(un->un_blk_lim.lim_max_unmap_descr_cnt != 0);
21298 	/* Spec says 0xffffffff are special values, so compute maximums. */
21299 	byte_cnt_lim = lim->lim_max_unmap_lba_cnt < UINT32_MAX ?
21300 	    (uint64_t)lim->lim_max_unmap_lba_cnt * un->un_tgt_blocksize :
21301 	    UINT64_MAX;
21302 	descr_cnt_lim = MIN(lim->lim_max_unmap_descr_cnt, SD_UNMAP_MAX_DESCR);
21303 
21304 	if (dfl->dfl_offset >= part_len) {
21305 		rval = SET_ERROR(EINVAL);
21306 		goto out;
21307 	}
21308 
21309 	for (size_t i = 0; i < dfl->dfl_num_exts; i++) {
21310 		const dkioc_free_list_ext_t *ext = &dfl->dfl_exts[i];
21311 		uint64_t ext_start = ext->dfle_start;
21312 		uint64_t ext_length = ext->dfle_length;
21313 
21314 		while (ext_length > 0) {
21315 			unmap_blk_descr_t *ubd;
21316 			/* Respect device limit on LBA count per command */
21317 			uint64_t len = MIN(MIN(ext_length, byte_cnt_lim -
21318 			    bytes_issued), SD_TGTBLOCKS2BYTES(un, UINT32_MAX));
21319 
21320 			/* check partition limits */
21321 			if (ext_start >= part_len ||
21322 			    ext_start + len < ext_start ||
21323 			    dfl->dfl_offset + ext_start + len <
21324 			    dfl->dfl_offset ||
21325 			    dfl->dfl_offset + ext_start + len > part_len) {
21326 				rval = SET_ERROR(EINVAL);
21327 				goto out;
21328 			}
21329 
21330 			ASSERT3U(descr_issued, <, descr_cnt_lim);
21331 			ASSERT3U(bytes_issued, <, byte_cnt_lim);
21332 			ubd = UNMAP_blk_descr_i(uph, descr_issued);
21333 
21334 			/* adjust in-partition addresses to be device-global */
21335 			ubd->ubd_lba = BE_64(SD_BYTES2TGTBLOCKS(un,
21336 			    dfl->dfl_offset + ext_start + part_off));
21337 			ubd->ubd_lba_cnt = BE_32(SD_BYTES2TGTBLOCKS(un, len));
21338 
21339 			descr_issued++;
21340 			bytes_issued += len;
21341 
21342 			/* Issue command when device limits reached */
21343 			if (descr_issued == descr_cnt_lim ||
21344 			    bytes_issued == byte_cnt_lim) {
21345 				rval = sd_send_scsi_UNMAP_issue_one(ssc, uph,
21346 				    descr_issued, bytes_issued);
21347 				if (rval != 0)
21348 					goto out;
21349 				descr_issued = 0;
21350 				bytes_issued = 0;
21351 			}
21352 
21353 			ext_start += len;
21354 			ext_length -= len;
21355 		}
21356 	}
21357 
21358 	if (descr_issued > 0) {
21359 		/* issue last command */
21360 		rval = sd_send_scsi_UNMAP_issue_one(ssc, uph, descr_issued,
21361 		    bytes_issued);
21362 	}
21363 
21364 out:
21365 	kmem_free(uph, SD_UNMAP_PARAM_LIST_MAXSZ);
21366 	return (rval);
21367 }
21368 
21369 /*
21370  * Issues one or several UNMAP commands based on a list of extents to be
21371  * unmapped. The internal multi-command processing is hidden, as the exact
21372  * number of commands and extents per command is limited by both SCSI
21373  * command syntax and device limits (as expressed in the SCSI Block Limits
21374  * VPD page and un_blk_lim in struct sd_lun).
21375  * Returns zero on success, or the error code of the first failed SCSI UNMAP
21376  * command.
21377  */
21378 static int
21379 sd_send_scsi_UNMAP(dev_t dev, sd_ssc_t *ssc, dkioc_free_list_t *dfl, int flag)
21380 {
21381 	struct sd_lun		*un = ssc->ssc_un;
21382 	int			rval = 0;
21383 
21384 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21385 	ASSERT(dfl != NULL);
21386 
21387 	/* Per spec, any of these conditions signals lack of UNMAP support. */
21388 	if (!(un->un_thin_flags & SD_THIN_PROV_ENABLED) ||
21389 	    un->un_blk_lim.lim_max_unmap_descr_cnt == 0 ||
21390 	    un->un_blk_lim.lim_max_unmap_lba_cnt == 0) {
21391 		return (SET_ERROR(ENOTSUP));
21392 	}
21393 
21394 	/* For userspace calls we must copy in. */
21395 	if (!(flag & FKIOCTL)) {
21396 		int err = dfl_copyin(dfl, &dfl, flag, KM_SLEEP);
21397 		if (err != 0)
21398 			return (err);
21399 	} else if (dfl->dfl_num_exts > DFL_COPYIN_MAX_EXTS) {
21400 		ASSERT3U(dfl->dfl_num_exts, <=, DFL_COPYIN_MAX_EXTS);
21401 		return (SET_ERROR(EINVAL));
21402 	}
21403 
21404 	rval = sd_send_scsi_UNMAP_issue(dev, ssc, dfl);
21405 
21406 	if (!(flag & FKIOCTL)) {
21407 		dfl_free(dfl);
21408 		dfl = NULL;
21409 	}
21410 
21411 	return (rval);
21412 }
21413 
21414 /*
21415  *    Function: sd_send_scsi_GET_CONFIGURATION
21416  *
21417  * Description: Issues the get configuration command to the device.
21418  *		Called from sd_check_for_writable_cd & sd_get_media_info
21419  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
21420  *   Arguments: ssc
21421  *		ucmdbuf
21422  *		rqbuf
21423  *		rqbuflen
21424  *		bufaddr
21425  *		buflen
21426  *		path_flag
21427  *
21428  * Return Code: 0   - Success
21429  *		errno return code from sd_ssc_send()
21430  *
21431  *     Context: Can sleep. Does not return until command is completed.
21432  *
21433  */
21434 
21435 static int
21436 sd_send_scsi_GET_CONFIGURATION(sd_ssc_t *ssc, struct uscsi_cmd *ucmdbuf,
21437     uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
21438     int path_flag)
21439 {
21440 	char	cdb[CDB_GROUP1];
21441 	int	status;
21442 	struct sd_lun	*un;
21443 
21444 	ASSERT(ssc != NULL);
21445 	un = ssc->ssc_un;
21446 	ASSERT(un != NULL);
21447 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21448 	ASSERT(bufaddr != NULL);
21449 	ASSERT(ucmdbuf != NULL);
21450 	ASSERT(rqbuf != NULL);
21451 
21452 	SD_TRACE(SD_LOG_IO, un,
21453 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
21454 
21455 	bzero(cdb, sizeof (cdb));
21456 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21457 	bzero(rqbuf, rqbuflen);
21458 	bzero(bufaddr, buflen);
21459 
21460 	/*
21461 	 * Set up cdb field for the get configuration command.
21462 	 */
21463 	cdb[0] = SCMD_GET_CONFIGURATION;
21464 	cdb[1] = 0x02;  /* Requested Type */
21465 	cdb[8] = SD_PROFILE_HEADER_LEN;
21466 	ucmdbuf->uscsi_cdb = cdb;
21467 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21468 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21469 	ucmdbuf->uscsi_buflen = buflen;
21470 	ucmdbuf->uscsi_timeout = sd_io_time;
21471 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21472 	ucmdbuf->uscsi_rqlen = rqbuflen;
21473 	ucmdbuf->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT | USCSI_READ;
21474 
21475 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21476 	    UIO_SYSSPACE, path_flag);
21477 
21478 	switch (status) {
21479 	case 0:
21480 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21481 		break;  /* Success! */
21482 	case EIO:
21483 		switch (ucmdbuf->uscsi_status) {
21484 		case STATUS_RESERVATION_CONFLICT:
21485 			status = EACCES;
21486 			break;
21487 		default:
21488 			break;
21489 		}
21490 		break;
21491 	default:
21492 		break;
21493 	}
21494 
21495 	if (status == 0) {
21496 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21497 		    "sd_send_scsi_GET_CONFIGURATION: data",
21498 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21499 	}
21500 
21501 	SD_TRACE(SD_LOG_IO, un,
21502 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
21503 
21504 	return (status);
21505 }
21506 
21507 /*
21508  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
21509  *
21510  * Description: Issues the get configuration command to the device to
21511  *              retrieve a specific feature. Called from
21512  *		sd_check_for_writable_cd & sd_set_mmc_caps.
21513  *   Arguments: ssc
21514  *              ucmdbuf
21515  *              rqbuf
21516  *              rqbuflen
21517  *              bufaddr
21518  *              buflen
21519  *		feature
21520  *
21521  * Return Code: 0   - Success
21522  *              errno return code from sd_ssc_send()
21523  *
21524  *     Context: Can sleep. Does not return until command is completed.
21525  *
21526  */
21527 static int
21528 sd_send_scsi_feature_GET_CONFIGURATION(sd_ssc_t *ssc, struct uscsi_cmd *ucmdbuf,
21529     uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
21530     char feature, int path_flag)
21531 {
21532 	char    cdb[CDB_GROUP1];
21533 	int	status;
21534 	struct sd_lun	*un;
21535 
21536 	ASSERT(ssc != NULL);
21537 	un = ssc->ssc_un;
21538 	ASSERT(un != NULL);
21539 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21540 	ASSERT(bufaddr != NULL);
21541 	ASSERT(ucmdbuf != NULL);
21542 	ASSERT(rqbuf != NULL);
21543 
21544 	SD_TRACE(SD_LOG_IO, un,
21545 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
21546 
21547 	bzero(cdb, sizeof (cdb));
21548 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
21549 	bzero(rqbuf, rqbuflen);
21550 	bzero(bufaddr, buflen);
21551 
21552 	/*
21553 	 * Set up cdb field for the get configuration command.
21554 	 */
21555 	cdb[0] = SCMD_GET_CONFIGURATION;
21556 	cdb[1] = 0x02;  /* Requested Type */
21557 	cdb[3] = feature;
21558 	cdb[8] = buflen;
21559 	ucmdbuf->uscsi_cdb = cdb;
21560 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
21561 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
21562 	ucmdbuf->uscsi_buflen = buflen;
21563 	ucmdbuf->uscsi_timeout = sd_io_time;
21564 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
21565 	ucmdbuf->uscsi_rqlen = rqbuflen;
21566 	ucmdbuf->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT | USCSI_READ;
21567 
21568 	status = sd_ssc_send(ssc, ucmdbuf, FKIOCTL,
21569 	    UIO_SYSSPACE, path_flag);
21570 
21571 	switch (status) {
21572 	case 0:
21573 
21574 		break;  /* Success! */
21575 	case EIO:
21576 		switch (ucmdbuf->uscsi_status) {
21577 		case STATUS_RESERVATION_CONFLICT:
21578 			status = EACCES;
21579 			break;
21580 		default:
21581 			break;
21582 		}
21583 		break;
21584 	default:
21585 		break;
21586 	}
21587 
21588 	if (status == 0) {
21589 		SD_DUMP_MEMORY(un, SD_LOG_IO,
21590 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
21591 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
21592 	}
21593 
21594 	SD_TRACE(SD_LOG_IO, un,
21595 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
21596 
21597 	return (status);
21598 }
21599 
21600 
21601 /*
21602  *    Function: sd_send_scsi_MODE_SENSE
21603  *
21604  * Description: Utility function for issuing a scsi MODE SENSE command.
21605  *		Note: This routine uses a consistent implementation for Group0,
21606  *		Group1, and Group2 commands across all platforms. ATAPI devices
21607  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21608  *
21609  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21610  *                      structure for this target.
21611  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
21612  *			  CDB_GROUP[1|2] (10 byte).
21613  *		bufaddr - buffer for page data retrieved from the target.
21614  *		buflen - size of page to be retrieved.
21615  *		page_code - page code of data to be retrieved from the target.
21616  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21617  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21618  *			to use the USCSI "direct" chain and bypass the normal
21619  *			command waitq.
21620  *
21621  * Return Code: 0   - Success
21622  *		errno return code from sd_ssc_send()
21623  *
21624  *     Context: Can sleep. Does not return until command is completed.
21625  */
21626 
21627 static int
21628 sd_send_scsi_MODE_SENSE(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
21629     size_t buflen,  uchar_t page_code, int path_flag)
21630 {
21631 	struct	scsi_extended_sense	sense_buf;
21632 	union scsi_cdb		cdb;
21633 	struct uscsi_cmd	ucmd_buf;
21634 	int			status;
21635 	int			headlen;
21636 	struct sd_lun		*un;
21637 
21638 	ASSERT(ssc != NULL);
21639 	un = ssc->ssc_un;
21640 	ASSERT(un != NULL);
21641 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21642 	ASSERT(bufaddr != NULL);
21643 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
21644 	    (cdbsize == CDB_GROUP2));
21645 
21646 	SD_TRACE(SD_LOG_IO, un,
21647 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
21648 
21649 	bzero(&cdb, sizeof (cdb));
21650 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21651 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21652 	bzero(bufaddr, buflen);
21653 
21654 	if (cdbsize == CDB_GROUP0) {
21655 		cdb.scc_cmd = SCMD_MODE_SENSE;
21656 		cdb.cdb_opaque[2] = page_code;
21657 		FORMG0COUNT(&cdb, buflen);
21658 		headlen = MODE_HEADER_LENGTH;
21659 	} else {
21660 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
21661 		cdb.cdb_opaque[2] = page_code;
21662 		FORMG1COUNT(&cdb, buflen);
21663 		headlen = MODE_HEADER_LENGTH_GRP2;
21664 	}
21665 
21666 	ASSERT(headlen <= buflen);
21667 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21668 
21669 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21670 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21671 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21672 	ucmd_buf.uscsi_buflen	= buflen;
21673 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21674 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21675 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
21676 	ucmd_buf.uscsi_timeout	= 60;
21677 
21678 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21679 	    UIO_SYSSPACE, path_flag);
21680 
21681 	switch (status) {
21682 	case 0:
21683 		/*
21684 		 * sr_check_wp() uses 0x3f page code and check the header of
21685 		 * mode page to determine if target device is write-protected.
21686 		 * But some USB devices return 0 bytes for 0x3f page code. For
21687 		 * this case, make sure that mode page header is returned at
21688 		 * least.
21689 		 */
21690 		if (buflen - ucmd_buf.uscsi_resid <  headlen) {
21691 			status = EIO;
21692 			sd_ssc_set_info(ssc, SSC_FLAGS_INVALID_DATA, -1,
21693 			    "mode page header is not returned");
21694 		}
21695 		break;	/* Success! */
21696 	case EIO:
21697 		switch (ucmd_buf.uscsi_status) {
21698 		case STATUS_RESERVATION_CONFLICT:
21699 			status = EACCES;
21700 			break;
21701 		default:
21702 			break;
21703 		}
21704 		break;
21705 	default:
21706 		break;
21707 	}
21708 
21709 	if (status == 0) {
21710 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
21711 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21712 	}
21713 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
21714 
21715 	return (status);
21716 }
21717 
21718 
21719 /*
21720  *    Function: sd_send_scsi_MODE_SELECT
21721  *
21722  * Description: Utility function for issuing a scsi MODE SELECT command.
21723  *		Note: This routine uses a consistent implementation for Group0,
21724  *		Group1, and Group2 commands across all platforms. ATAPI devices
21725  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
21726  *
21727  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21728  *                      structure for this target.
21729  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
21730  *			  CDB_GROUP[1|2] (10 byte).
21731  *		bufaddr - buffer for page data retrieved from the target.
21732  *		buflen - size of page to be retrieved.
21733  *		save_page - boolean to determin if SP bit should be set.
21734  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21735  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21736  *			to use the USCSI "direct" chain and bypass the normal
21737  *			command waitq.
21738  *
21739  * Return Code: 0   - Success
21740  *		errno return code from sd_ssc_send()
21741  *
21742  *     Context: Can sleep. Does not return until command is completed.
21743  */
21744 
21745 static int
21746 sd_send_scsi_MODE_SELECT(sd_ssc_t *ssc, int cdbsize, uchar_t *bufaddr,
21747     size_t buflen,  uchar_t save_page, int path_flag)
21748 {
21749 	struct	scsi_extended_sense	sense_buf;
21750 	union scsi_cdb		cdb;
21751 	struct uscsi_cmd	ucmd_buf;
21752 	int			status;
21753 	struct sd_lun		*un;
21754 
21755 	ASSERT(ssc != NULL);
21756 	un = ssc->ssc_un;
21757 	ASSERT(un != NULL);
21758 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21759 	ASSERT(bufaddr != NULL);
21760 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
21761 	    (cdbsize == CDB_GROUP2));
21762 
21763 	SD_TRACE(SD_LOG_IO, un,
21764 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
21765 
21766 	bzero(&cdb, sizeof (cdb));
21767 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21768 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21769 
21770 	/* Set the PF bit for many third party drives */
21771 	cdb.cdb_opaque[1] = 0x10;
21772 
21773 	/* Set the savepage(SP) bit if given */
21774 	if (save_page == SD_SAVE_PAGE) {
21775 		cdb.cdb_opaque[1] |= 0x01;
21776 	}
21777 
21778 	if (cdbsize == CDB_GROUP0) {
21779 		cdb.scc_cmd = SCMD_MODE_SELECT;
21780 		FORMG0COUNT(&cdb, buflen);
21781 	} else {
21782 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
21783 		FORMG1COUNT(&cdb, buflen);
21784 	}
21785 
21786 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21787 
21788 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21789 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21790 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
21791 	ucmd_buf.uscsi_buflen	= buflen;
21792 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21793 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21794 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
21795 	ucmd_buf.uscsi_timeout	= 60;
21796 
21797 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21798 	    UIO_SYSSPACE, path_flag);
21799 
21800 	switch (status) {
21801 	case 0:
21802 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21803 		break;	/* Success! */
21804 	case EIO:
21805 		switch (ucmd_buf.uscsi_status) {
21806 		case STATUS_RESERVATION_CONFLICT:
21807 			status = EACCES;
21808 			break;
21809 		default:
21810 			break;
21811 		}
21812 		break;
21813 	default:
21814 		break;
21815 	}
21816 
21817 	if (status == 0) {
21818 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
21819 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21820 	}
21821 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
21822 
21823 	return (status);
21824 }
21825 
21826 
21827 /*
21828  *    Function: sd_send_scsi_RDWR
21829  *
21830  * Description: Issue a scsi READ or WRITE command with the given parameters.
21831  *
21832  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21833  *                      structure for this target.
21834  *		cmd:	 SCMD_READ or SCMD_WRITE
21835  *		bufaddr: Address of caller's buffer to receive the RDWR data
21836  *		buflen:  Length of caller's buffer receive the RDWR data.
21837  *		start_block: Block number for the start of the RDWR operation.
21838  *			 (Assumes target-native block size.)
21839  *		residp:  Pointer to variable to receive the redisual of the
21840  *			 RDWR operation (may be NULL of no residual requested).
21841  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
21842  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
21843  *			to use the USCSI "direct" chain and bypass the normal
21844  *			command waitq.
21845  *
21846  * Return Code: 0   - Success
21847  *		errno return code from sd_ssc_send()
21848  *
21849  *     Context: Can sleep. Does not return until command is completed.
21850  */
21851 
21852 static int
21853 sd_send_scsi_RDWR(sd_ssc_t *ssc, uchar_t cmd, void *bufaddr,
21854     size_t buflen, daddr_t start_block, int path_flag)
21855 {
21856 	struct	scsi_extended_sense	sense_buf;
21857 	union scsi_cdb		cdb;
21858 	struct uscsi_cmd	ucmd_buf;
21859 	uint32_t		block_count;
21860 	int			status;
21861 	int			cdbsize;
21862 	uchar_t			flag;
21863 	struct sd_lun		*un;
21864 
21865 	ASSERT(ssc != NULL);
21866 	un = ssc->ssc_un;
21867 	ASSERT(un != NULL);
21868 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21869 	ASSERT(bufaddr != NULL);
21870 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
21871 
21872 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
21873 
21874 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
21875 		return (EINVAL);
21876 	}
21877 
21878 	mutex_enter(SD_MUTEX(un));
21879 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
21880 	mutex_exit(SD_MUTEX(un));
21881 
21882 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
21883 
21884 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
21885 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
21886 	    bufaddr, buflen, start_block, block_count);
21887 
21888 	bzero(&cdb, sizeof (cdb));
21889 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21890 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21891 
21892 	/* Compute CDB size to use */
21893 	if (start_block > 0xffffffff)
21894 		cdbsize = CDB_GROUP4;
21895 	else if ((start_block & 0xFFE00000) ||
21896 	    (un->un_f_cfg_is_atapi == TRUE))
21897 		cdbsize = CDB_GROUP1;
21898 	else
21899 		cdbsize = CDB_GROUP0;
21900 
21901 	switch (cdbsize) {
21902 	case CDB_GROUP0:	/* 6-byte CDBs */
21903 		cdb.scc_cmd = cmd;
21904 		FORMG0ADDR(&cdb, start_block);
21905 		FORMG0COUNT(&cdb, block_count);
21906 		break;
21907 	case CDB_GROUP1:	/* 10-byte CDBs */
21908 		cdb.scc_cmd = cmd | SCMD_GROUP1;
21909 		FORMG1ADDR(&cdb, start_block);
21910 		FORMG1COUNT(&cdb, block_count);
21911 		break;
21912 	case CDB_GROUP4:	/* 16-byte CDBs */
21913 		cdb.scc_cmd = cmd | SCMD_GROUP4;
21914 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
21915 		FORMG4COUNT(&cdb, block_count);
21916 		break;
21917 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
21918 	default:
21919 		/* All others reserved */
21920 		return (EINVAL);
21921 	}
21922 
21923 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
21924 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
21925 
21926 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
21927 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
21928 	ucmd_buf.uscsi_bufaddr	= bufaddr;
21929 	ucmd_buf.uscsi_buflen	= buflen;
21930 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
21931 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
21932 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
21933 	ucmd_buf.uscsi_timeout	= 60;
21934 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
21935 	    UIO_SYSSPACE, path_flag);
21936 
21937 	switch (status) {
21938 	case 0:
21939 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
21940 		break;	/* Success! */
21941 	case EIO:
21942 		switch (ucmd_buf.uscsi_status) {
21943 		case STATUS_RESERVATION_CONFLICT:
21944 			status = EACCES;
21945 			break;
21946 		default:
21947 			break;
21948 		}
21949 		break;
21950 	default:
21951 		break;
21952 	}
21953 
21954 	if (status == 0) {
21955 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
21956 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
21957 	}
21958 
21959 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
21960 
21961 	return (status);
21962 }
21963 
21964 
21965 /*
21966  *    Function: sd_send_scsi_LOG_SENSE
21967  *
21968  * Description: Issue a scsi LOG_SENSE command with the given parameters.
21969  *
21970  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
21971  *                      structure for this target.
21972  *
21973  * Return Code: 0   - Success
21974  *		errno return code from sd_ssc_send()
21975  *
21976  *     Context: Can sleep. Does not return until command is completed.
21977  */
21978 
21979 static int
21980 sd_send_scsi_LOG_SENSE(sd_ssc_t *ssc, uchar_t *bufaddr, uint16_t buflen,
21981     uchar_t page_code, uchar_t page_control, uint16_t param_ptr, int path_flag)
21982 {
21983 	struct scsi_extended_sense	sense_buf;
21984 	union scsi_cdb		cdb;
21985 	struct uscsi_cmd	ucmd_buf;
21986 	int			status;
21987 	struct sd_lun		*un;
21988 
21989 	ASSERT(ssc != NULL);
21990 	un = ssc->ssc_un;
21991 	ASSERT(un != NULL);
21992 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21993 
21994 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
21995 
21996 	bzero(&cdb, sizeof (cdb));
21997 	bzero(&ucmd_buf, sizeof (ucmd_buf));
21998 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
21999 
22000 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
22001 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
22002 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
22003 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
22004 	FORMG1COUNT(&cdb, buflen);
22005 
22006 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22007 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
22008 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
22009 	ucmd_buf.uscsi_buflen	= buflen;
22010 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
22011 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
22012 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
22013 	ucmd_buf.uscsi_timeout	= 60;
22014 
22015 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22016 	    UIO_SYSSPACE, path_flag);
22017 
22018 	switch (status) {
22019 	case 0:
22020 		break;
22021 	case EIO:
22022 		switch (ucmd_buf.uscsi_status) {
22023 		case STATUS_RESERVATION_CONFLICT:
22024 			status = EACCES;
22025 			break;
22026 		case STATUS_CHECK:
22027 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
22028 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
22029 			    KEY_ILLEGAL_REQUEST) &&
22030 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
22031 				/*
22032 				 * ASC 0x24: INVALID FIELD IN CDB
22033 				 */
22034 				switch (page_code) {
22035 				case START_STOP_CYCLE_PAGE:
22036 					/*
22037 					 * The start stop cycle counter is
22038 					 * implemented as page 0x31 in earlier
22039 					 * generation disks. In new generation
22040 					 * disks the start stop cycle counter is
22041 					 * implemented as page 0xE. To properly
22042 					 * handle this case if an attempt for
22043 					 * log page 0xE is made and fails we
22044 					 * will try again using page 0x31.
22045 					 *
22046 					 * Network storage BU committed to
22047 					 * maintain the page 0x31 for this
22048 					 * purpose and will not have any other
22049 					 * page implemented with page code 0x31
22050 					 * until all disks transition to the
22051 					 * standard page.
22052 					 */
22053 					mutex_enter(SD_MUTEX(un));
22054 					un->un_start_stop_cycle_page =
22055 					    START_STOP_CYCLE_VU_PAGE;
22056 					cdb.cdb_opaque[2] =
22057 					    (char)(page_control << 6) |
22058 					    un->un_start_stop_cycle_page;
22059 					mutex_exit(SD_MUTEX(un));
22060 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22061 					status = sd_ssc_send(
22062 					    ssc, &ucmd_buf, FKIOCTL,
22063 					    UIO_SYSSPACE, path_flag);
22064 
22065 					break;
22066 				case TEMPERATURE_PAGE:
22067 					status = ENOTTY;
22068 					break;
22069 				default:
22070 					break;
22071 				}
22072 			}
22073 			break;
22074 		default:
22075 			break;
22076 		}
22077 		break;
22078 	default:
22079 		break;
22080 	}
22081 
22082 	if (status == 0) {
22083 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22084 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
22085 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
22086 	}
22087 
22088 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
22089 
22090 	return (status);
22091 }
22092 
22093 
22094 /*
22095  *    Function: sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION
22096  *
22097  * Description: Issue the scsi GET EVENT STATUS NOTIFICATION command.
22098  *
22099  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
22100  *                      structure for this target.
22101  *		bufaddr
22102  *		buflen
22103  *		class_req
22104  *
22105  * Return Code: 0   - Success
22106  *		errno return code from sd_ssc_send()
22107  *
22108  *     Context: Can sleep. Does not return until command is completed.
22109  */
22110 
22111 static int
22112 sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION(sd_ssc_t *ssc, uchar_t *bufaddr,
22113     size_t buflen, uchar_t class_req)
22114 {
22115 	union scsi_cdb		cdb;
22116 	struct uscsi_cmd	ucmd_buf;
22117 	int			status;
22118 	struct sd_lun		*un;
22119 
22120 	ASSERT(ssc != NULL);
22121 	un = ssc->ssc_un;
22122 	ASSERT(un != NULL);
22123 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22124 	ASSERT(bufaddr != NULL);
22125 
22126 	SD_TRACE(SD_LOG_IO, un,
22127 	    "sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION: entry: un:0x%p\n", un);
22128 
22129 	bzero(&cdb, sizeof (cdb));
22130 	bzero(&ucmd_buf, sizeof (ucmd_buf));
22131 	bzero(bufaddr, buflen);
22132 
22133 	cdb.scc_cmd = SCMD_GET_EVENT_STATUS_NOTIFICATION;
22134 	cdb.cdb_opaque[1] = 1; /* polled */
22135 	cdb.cdb_opaque[4] = class_req;
22136 	FORMG1COUNT(&cdb, buflen);
22137 
22138 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
22139 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
22140 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
22141 	ucmd_buf.uscsi_buflen	= buflen;
22142 	ucmd_buf.uscsi_rqbuf	= NULL;
22143 	ucmd_buf.uscsi_rqlen	= 0;
22144 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
22145 	ucmd_buf.uscsi_timeout	= 60;
22146 
22147 	status = sd_ssc_send(ssc, &ucmd_buf, FKIOCTL,
22148 	    UIO_SYSSPACE, SD_PATH_DIRECT);
22149 
22150 	/*
22151 	 * Only handle status == 0, the upper-level caller
22152 	 * will put different assessment based on the context.
22153 	 */
22154 	if (status == 0) {
22155 		sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22156 
22157 		if (ucmd_buf.uscsi_resid != 0) {
22158 			status = EIO;
22159 		}
22160 	}
22161 
22162 	SD_TRACE(SD_LOG_IO, un,
22163 	    "sd_send_scsi_GET_EVENT_STATUS_NOTIFICATION: exit\n");
22164 
22165 	return (status);
22166 }
22167 
22168 
22169 static boolean_t
22170 sd_gesn_media_data_valid(uchar_t *data)
22171 {
22172 	uint16_t			len;
22173 
22174 	len = (data[1] << 8) | data[0];
22175 	return ((len >= 6) &&
22176 	    ((data[2] & SD_GESN_HEADER_NEA) == 0) &&
22177 	    ((data[2] & SD_GESN_HEADER_CLASS) == SD_GESN_MEDIA_CLASS) &&
22178 	    ((data[3] & (1 << SD_GESN_MEDIA_CLASS)) != 0));
22179 }
22180 
22181 
22182 /*
22183  *    Function: sdioctl
22184  *
22185  * Description: Driver's ioctl(9e) entry point function.
22186  *
22187  *   Arguments: dev     - device number
22188  *		cmd     - ioctl operation to be performed
22189  *		arg     - user argument, contains data to be set or reference
22190  *			  parameter for get
22191  *		flag    - bit flag, indicating open settings, 32/64 bit type
22192  *		cred_p  - user credential pointer
22193  *		rval_p  - calling process return value (OPT)
22194  *
22195  * Return Code: EINVAL
22196  *		ENOTTY
22197  *		ENXIO
22198  *		EIO
22199  *		EFAULT
22200  *		ENOTSUP
22201  *		EPERM
22202  *
22203  *     Context: Called from the device switch at normal priority.
22204  */
22205 
22206 static int
22207 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
22208 {
22209 	struct sd_lun	*un = NULL;
22210 	int		err = 0;
22211 	int		i = 0;
22212 	cred_t		*cr;
22213 	int		tmprval = EINVAL;
22214 	boolean_t	is_valid;
22215 	sd_ssc_t	*ssc;
22216 
22217 	/*
22218 	 * All device accesses go thru sdstrategy where we check on suspend
22219 	 * status
22220 	 */
22221 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22222 		return (ENXIO);
22223 	}
22224 
22225 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22226 
22227 	/* Initialize sd_ssc_t for internal uscsi commands */
22228 	ssc = sd_ssc_init(un);
22229 
22230 	is_valid = SD_IS_VALID_LABEL(un);
22231 
22232 	/*
22233 	 * Moved this wait from sd_uscsi_strategy to here for
22234 	 * reasons of deadlock prevention. Internal driver commands,
22235 	 * specifically those to change a devices power level, result
22236 	 * in a call to sd_uscsi_strategy.
22237 	 */
22238 	mutex_enter(SD_MUTEX(un));
22239 	while ((un->un_state == SD_STATE_SUSPENDED) ||
22240 	    (un->un_state == SD_STATE_PM_CHANGING)) {
22241 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
22242 	}
22243 	/*
22244 	 * Twiddling the counter here protects commands from now
22245 	 * through to the top of sd_uscsi_strategy. Without the
22246 	 * counter inc. a power down, for example, could get in
22247 	 * after the above check for state is made and before
22248 	 * execution gets to the top of sd_uscsi_strategy.
22249 	 * That would cause problems.
22250 	 */
22251 	un->un_ncmds_in_driver++;
22252 
22253 	if (!is_valid &&
22254 	    (flag & (FNDELAY | FNONBLOCK))) {
22255 		switch (cmd) {
22256 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
22257 		case DKIOCGVTOC:
22258 		case DKIOCGEXTVTOC:
22259 		case DKIOCGAPART:
22260 		case DKIOCPARTINFO:
22261 		case DKIOCEXTPARTINFO:
22262 		case DKIOCSGEOM:
22263 		case DKIOCSAPART:
22264 		case DKIOCGETEFI:
22265 		case DKIOCPARTITION:
22266 		case DKIOCSVTOC:
22267 		case DKIOCSEXTVTOC:
22268 		case DKIOCSETEFI:
22269 		case DKIOCGMBOOT:
22270 		case DKIOCSMBOOT:
22271 		case DKIOCG_PHYGEOM:
22272 		case DKIOCG_VIRTGEOM:
22273 #if defined(__x86)
22274 		case DKIOCSETEXTPART:
22275 #endif
22276 			/* let cmlb handle it */
22277 			goto skip_ready_valid;
22278 
22279 		case CDROMPAUSE:
22280 		case CDROMRESUME:
22281 		case CDROMPLAYMSF:
22282 		case CDROMPLAYTRKIND:
22283 		case CDROMREADTOCHDR:
22284 		case CDROMREADTOCENTRY:
22285 		case CDROMSTOP:
22286 		case CDROMSTART:
22287 		case CDROMVOLCTRL:
22288 		case CDROMSUBCHNL:
22289 		case CDROMREADMODE2:
22290 		case CDROMREADMODE1:
22291 		case CDROMREADOFFSET:
22292 		case CDROMSBLKMODE:
22293 		case CDROMGBLKMODE:
22294 		case CDROMGDRVSPEED:
22295 		case CDROMSDRVSPEED:
22296 		case CDROMCDDA:
22297 		case CDROMCDXA:
22298 		case CDROMSUBCODE:
22299 			if (!ISCD(un)) {
22300 				un->un_ncmds_in_driver--;
22301 				ASSERT(un->un_ncmds_in_driver >= 0);
22302 				mutex_exit(SD_MUTEX(un));
22303 				err = ENOTTY;
22304 				goto done_without_assess;
22305 			}
22306 			break;
22307 		case FDEJECT:
22308 		case DKIOCEJECT:
22309 		case CDROMEJECT:
22310 			if (!un->un_f_eject_media_supported) {
22311 				un->un_ncmds_in_driver--;
22312 				ASSERT(un->un_ncmds_in_driver >= 0);
22313 				mutex_exit(SD_MUTEX(un));
22314 				err = ENOTTY;
22315 				goto done_without_assess;
22316 			}
22317 			break;
22318 		case DKIOCFLUSHWRITECACHE:
22319 			mutex_exit(SD_MUTEX(un));
22320 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
22321 			if (err != 0) {
22322 				mutex_enter(SD_MUTEX(un));
22323 				un->un_ncmds_in_driver--;
22324 				ASSERT(un->un_ncmds_in_driver >= 0);
22325 				mutex_exit(SD_MUTEX(un));
22326 				err = EIO;
22327 				goto done_quick_assess;
22328 			}
22329 			mutex_enter(SD_MUTEX(un));
22330 			/* FALLTHROUGH */
22331 		case DKIOCREMOVABLE:
22332 		case DKIOCHOTPLUGGABLE:
22333 		case DKIOCINFO:
22334 		case DKIOCGMEDIAINFO:
22335 		case DKIOCGMEDIAINFOEXT:
22336 		case DKIOCSOLIDSTATE:
22337 		case DKIOC_CANFREE:
22338 		case MHIOCENFAILFAST:
22339 		case MHIOCSTATUS:
22340 		case MHIOCTKOWN:
22341 		case MHIOCRELEASE:
22342 		case MHIOCGRP_INKEYS:
22343 		case MHIOCGRP_INRESV:
22344 		case MHIOCGRP_REGISTER:
22345 		case MHIOCGRP_CLEAR:
22346 		case MHIOCGRP_RESERVE:
22347 		case MHIOCGRP_PREEMPTANDABORT:
22348 		case MHIOCGRP_REGISTERANDIGNOREKEY:
22349 		case CDROMCLOSETRAY:
22350 		case USCSICMD:
22351 		case USCSIMAXXFER:
22352 			goto skip_ready_valid;
22353 		default:
22354 			break;
22355 		}
22356 
22357 		mutex_exit(SD_MUTEX(un));
22358 		err = sd_ready_and_valid(ssc, SDPART(dev));
22359 		mutex_enter(SD_MUTEX(un));
22360 
22361 		if (err != SD_READY_VALID) {
22362 			switch (cmd) {
22363 			case DKIOCSTATE:
22364 			case CDROMGDRVSPEED:
22365 			case CDROMSDRVSPEED:
22366 			case FDEJECT:	/* for eject command */
22367 			case DKIOCEJECT:
22368 			case CDROMEJECT:
22369 			case DKIOCREMOVABLE:
22370 			case DKIOCHOTPLUGGABLE:
22371 				break;
22372 			default:
22373 				if (un->un_f_has_removable_media) {
22374 					err = ENXIO;
22375 				} else {
22376 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
22377 					if (err == SD_RESERVED_BY_OTHERS) {
22378 						err = EACCES;
22379 					} else {
22380 						err = EIO;
22381 					}
22382 				}
22383 				un->un_ncmds_in_driver--;
22384 				ASSERT(un->un_ncmds_in_driver >= 0);
22385 				mutex_exit(SD_MUTEX(un));
22386 
22387 				goto done_without_assess;
22388 			}
22389 		}
22390 	}
22391 
22392 skip_ready_valid:
22393 	mutex_exit(SD_MUTEX(un));
22394 
22395 	switch (cmd) {
22396 	case DKIOCINFO:
22397 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
22398 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
22399 		break;
22400 
22401 	case DKIOCGMEDIAINFO:
22402 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
22403 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
22404 		break;
22405 
22406 	case DKIOCGMEDIAINFOEXT:
22407 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFOEXT\n");
22408 		err = sd_get_media_info_ext(dev, (caddr_t)arg, flag);
22409 		break;
22410 
22411 	case DKIOCGGEOM:
22412 	case DKIOCGVTOC:
22413 	case DKIOCGEXTVTOC:
22414 	case DKIOCGAPART:
22415 	case DKIOCPARTINFO:
22416 	case DKIOCEXTPARTINFO:
22417 	case DKIOCSGEOM:
22418 	case DKIOCSAPART:
22419 	case DKIOCGETEFI:
22420 	case DKIOCPARTITION:
22421 	case DKIOCSVTOC:
22422 	case DKIOCSEXTVTOC:
22423 	case DKIOCSETEFI:
22424 	case DKIOCGMBOOT:
22425 	case DKIOCSMBOOT:
22426 	case DKIOCG_PHYGEOM:
22427 	case DKIOCG_VIRTGEOM:
22428 #if defined(__x86)
22429 	case DKIOCSETEXTPART:
22430 #endif
22431 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
22432 
22433 		/* TUR should spin up */
22434 
22435 		if (un->un_f_has_removable_media)
22436 			err = sd_send_scsi_TEST_UNIT_READY(ssc,
22437 			    SD_CHECK_FOR_MEDIA);
22438 
22439 		else
22440 			err = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
22441 
22442 		if (err != 0)
22443 			goto done_with_assess;
22444 
22445 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
22446 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
22447 
22448 		if ((err == 0) &&
22449 		    ((cmd == DKIOCSETEFI) ||
22450 		    ((un->un_f_pkstats_enabled) &&
22451 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC ||
22452 		    cmd == DKIOCSEXTVTOC)))) {
22453 
22454 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
22455 			    (void *)SD_PATH_DIRECT);
22456 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
22457 				sd_set_pstats(un);
22458 				SD_TRACE(SD_LOG_IO_PARTITION, un,
22459 				    "sd_ioctl: un:0x%p pstats created and "
22460 				    "set\n", un);
22461 			}
22462 		}
22463 
22464 		if ((cmd == DKIOCSVTOC || cmd == DKIOCSEXTVTOC) ||
22465 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
22466 
22467 			mutex_enter(SD_MUTEX(un));
22468 			if (un->un_f_devid_supported &&
22469 			    (un->un_f_opt_fab_devid == TRUE)) {
22470 				if (un->un_devid == NULL) {
22471 					sd_register_devid(ssc, SD_DEVINFO(un),
22472 					    SD_TARGET_IS_UNRESERVED);
22473 				} else {
22474 					/*
22475 					 * The device id for this disk
22476 					 * has been fabricated. The
22477 					 * device id must be preserved
22478 					 * by writing it back out to
22479 					 * disk.
22480 					 */
22481 					if (sd_write_deviceid(ssc) != 0) {
22482 						ddi_devid_free(un->un_devid);
22483 						un->un_devid = NULL;
22484 					}
22485 				}
22486 			}
22487 			mutex_exit(SD_MUTEX(un));
22488 		}
22489 
22490 		break;
22491 
22492 	case DKIOCLOCK:
22493 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
22494 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
22495 		    SD_PATH_STANDARD);
22496 		goto done_with_assess;
22497 
22498 	case DKIOCUNLOCK:
22499 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
22500 		err = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
22501 		    SD_PATH_STANDARD);
22502 		goto done_with_assess;
22503 
22504 	case DKIOCSTATE: {
22505 		enum dkio_state		state;
22506 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
22507 
22508 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
22509 			err = EFAULT;
22510 		} else {
22511 			err = sd_check_media(dev, state);
22512 			if (err == 0) {
22513 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
22514 				    sizeof (int), flag) != 0)
22515 					err = EFAULT;
22516 			}
22517 		}
22518 		break;
22519 	}
22520 
22521 	case DKIOCREMOVABLE:
22522 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
22523 		i = un->un_f_has_removable_media ? 1 : 0;
22524 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22525 			err = EFAULT;
22526 		} else {
22527 			err = 0;
22528 		}
22529 		break;
22530 
22531 	case DKIOCSOLIDSTATE:
22532 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSOLIDSTATE\n");
22533 		i = un->un_f_is_solid_state ? 1 : 0;
22534 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22535 			err = EFAULT;
22536 		} else {
22537 			err = 0;
22538 		}
22539 		break;
22540 
22541 	case DKIOCHOTPLUGGABLE:
22542 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
22543 		i = un->un_f_is_hotpluggable ? 1 : 0;
22544 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22545 			err = EFAULT;
22546 		} else {
22547 			err = 0;
22548 		}
22549 		break;
22550 
22551 	case DKIOCREADONLY:
22552 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREADONLY\n");
22553 		i = 0;
22554 		if ((ISCD(un) && !un->un_f_mmc_writable_media) ||
22555 		    (sr_check_wp(dev) != 0)) {
22556 			i = 1;
22557 		}
22558 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
22559 			err = EFAULT;
22560 		} else {
22561 			err = 0;
22562 		}
22563 		break;
22564 
22565 	case DKIOCGTEMPERATURE:
22566 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
22567 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
22568 		break;
22569 
22570 	case MHIOCENFAILFAST:
22571 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
22572 		if ((err = drv_priv(cred_p)) == 0) {
22573 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
22574 		}
22575 		break;
22576 
22577 	case MHIOCTKOWN:
22578 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
22579 		if ((err = drv_priv(cred_p)) == 0) {
22580 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
22581 		}
22582 		break;
22583 
22584 	case MHIOCRELEASE:
22585 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
22586 		if ((err = drv_priv(cred_p)) == 0) {
22587 			err = sd_mhdioc_release(dev);
22588 		}
22589 		break;
22590 
22591 	case MHIOCSTATUS:
22592 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
22593 		if ((err = drv_priv(cred_p)) == 0) {
22594 			switch (sd_send_scsi_TEST_UNIT_READY(ssc, 0)) {
22595 			case 0:
22596 				err = 0;
22597 				break;
22598 			case EACCES:
22599 				*rval_p = 1;
22600 				err = 0;
22601 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
22602 				break;
22603 			default:
22604 				err = EIO;
22605 				goto done_with_assess;
22606 			}
22607 		}
22608 		break;
22609 
22610 	case MHIOCQRESERVE:
22611 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
22612 		if ((err = drv_priv(cred_p)) == 0) {
22613 			err = sd_reserve_release(dev, SD_RESERVE);
22614 		}
22615 		break;
22616 
22617 	case MHIOCREREGISTERDEVID:
22618 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
22619 		if (drv_priv(cred_p) == EPERM) {
22620 			err = EPERM;
22621 		} else if (!un->un_f_devid_supported) {
22622 			err = ENOTTY;
22623 		} else {
22624 			err = sd_mhdioc_register_devid(dev);
22625 		}
22626 		break;
22627 
22628 	case MHIOCGRP_INKEYS:
22629 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
22630 		if (((err = drv_priv(cred_p)) != EPERM) &&
22631 		    arg != (intptr_t)NULL) {
22632 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22633 				err = ENOTSUP;
22634 			} else {
22635 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
22636 				    flag);
22637 			}
22638 		}
22639 		break;
22640 
22641 	case MHIOCGRP_INRESV:
22642 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
22643 		if (((err = drv_priv(cred_p)) != EPERM) &&
22644 		    arg != (intptr_t)NULL) {
22645 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22646 				err = ENOTSUP;
22647 			} else {
22648 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
22649 			}
22650 		}
22651 		break;
22652 
22653 	case MHIOCGRP_REGISTER:
22654 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
22655 		if ((err = drv_priv(cred_p)) != EPERM) {
22656 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22657 				err = ENOTSUP;
22658 			} else if (arg != (intptr_t)NULL) {
22659 				mhioc_register_t reg;
22660 				if (ddi_copyin((void *)arg, &reg,
22661 				    sizeof (mhioc_register_t), flag) != 0) {
22662 					err = EFAULT;
22663 				} else {
22664 					err =
22665 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22666 					    ssc, SD_SCSI3_REGISTER,
22667 					    (uchar_t *)&reg);
22668 					if (err != 0)
22669 						goto done_with_assess;
22670 				}
22671 			}
22672 		}
22673 		break;
22674 
22675 	case MHIOCGRP_CLEAR:
22676 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_CLEAR\n");
22677 		if ((err = drv_priv(cred_p)) != EPERM) {
22678 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22679 				err = ENOTSUP;
22680 			} else if (arg != (intptr_t)NULL) {
22681 				mhioc_register_t reg;
22682 				if (ddi_copyin((void *)arg, &reg,
22683 				    sizeof (mhioc_register_t), flag) != 0) {
22684 					err = EFAULT;
22685 				} else {
22686 					err =
22687 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22688 					    ssc, SD_SCSI3_CLEAR,
22689 					    (uchar_t *)&reg);
22690 					if (err != 0)
22691 						goto done_with_assess;
22692 				}
22693 			}
22694 		}
22695 		break;
22696 
22697 	case MHIOCGRP_RESERVE:
22698 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
22699 		if ((err = drv_priv(cred_p)) != EPERM) {
22700 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22701 				err = ENOTSUP;
22702 			} else if (arg != (intptr_t)NULL) {
22703 				mhioc_resv_desc_t resv_desc;
22704 				if (ddi_copyin((void *)arg, &resv_desc,
22705 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
22706 					err = EFAULT;
22707 				} else {
22708 					err =
22709 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22710 					    ssc, SD_SCSI3_RESERVE,
22711 					    (uchar_t *)&resv_desc);
22712 					if (err != 0)
22713 						goto done_with_assess;
22714 				}
22715 			}
22716 		}
22717 		break;
22718 
22719 	case MHIOCGRP_PREEMPTANDABORT:
22720 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
22721 		if ((err = drv_priv(cred_p)) != EPERM) {
22722 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22723 				err = ENOTSUP;
22724 			} else if (arg != (intptr_t)NULL) {
22725 				mhioc_preemptandabort_t preempt_abort;
22726 				if (ddi_copyin((void *)arg, &preempt_abort,
22727 				    sizeof (mhioc_preemptandabort_t),
22728 				    flag) != 0) {
22729 					err = EFAULT;
22730 				} else {
22731 					err =
22732 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22733 					    ssc, SD_SCSI3_PREEMPTANDABORT,
22734 					    (uchar_t *)&preempt_abort);
22735 					if (err != 0)
22736 						goto done_with_assess;
22737 				}
22738 			}
22739 		}
22740 		break;
22741 
22742 	case MHIOCGRP_REGISTERANDIGNOREKEY:
22743 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
22744 		if ((err = drv_priv(cred_p)) != EPERM) {
22745 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
22746 				err = ENOTSUP;
22747 			} else if (arg != (intptr_t)NULL) {
22748 				mhioc_registerandignorekey_t r_and_i;
22749 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
22750 				    sizeof (mhioc_registerandignorekey_t),
22751 				    flag) != 0) {
22752 					err = EFAULT;
22753 				} else {
22754 					err =
22755 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
22756 					    ssc, SD_SCSI3_REGISTERANDIGNOREKEY,
22757 					    (uchar_t *)&r_and_i);
22758 					if (err != 0)
22759 						goto done_with_assess;
22760 				}
22761 			}
22762 		}
22763 		break;
22764 
22765 	case USCSICMD:
22766 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
22767 		cr = ddi_get_cred();
22768 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
22769 			err = EPERM;
22770 		} else {
22771 			enum uio_seg	uioseg;
22772 
22773 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
22774 			    UIO_USERSPACE;
22775 			if (un->un_f_format_in_progress == TRUE) {
22776 				err = EAGAIN;
22777 				break;
22778 			}
22779 
22780 			err = sd_ssc_send(ssc,
22781 			    (struct uscsi_cmd *)arg,
22782 			    flag, uioseg, SD_PATH_STANDARD);
22783 			if (err != 0)
22784 				goto done_with_assess;
22785 			else
22786 				sd_ssc_assessment(ssc, SD_FMT_STANDARD);
22787 		}
22788 		break;
22789 
22790 	case USCSIMAXXFER:
22791 		SD_TRACE(SD_LOG_IOCTL, un, "USCSIMAXXFER\n");
22792 		cr = ddi_get_cred();
22793 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
22794 			err = EPERM;
22795 		} else {
22796 			const uscsi_xfer_t xfer = un->un_max_xfer_size;
22797 
22798 			if (ddi_copyout(&xfer, (void *)arg, sizeof (xfer),
22799 			    flag) != 0) {
22800 				err = EFAULT;
22801 			} else {
22802 				err = 0;
22803 			}
22804 		}
22805 		break;
22806 
22807 	case CDROMPAUSE:
22808 	case CDROMRESUME:
22809 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
22810 		if (!ISCD(un)) {
22811 			err = ENOTTY;
22812 		} else {
22813 			err = sr_pause_resume(dev, cmd);
22814 		}
22815 		break;
22816 
22817 	case CDROMPLAYMSF:
22818 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
22819 		if (!ISCD(un)) {
22820 			err = ENOTTY;
22821 		} else {
22822 			err = sr_play_msf(dev, (caddr_t)arg, flag);
22823 		}
22824 		break;
22825 
22826 	case CDROMPLAYTRKIND:
22827 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
22828 #if defined(__x86)
22829 		/*
22830 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
22831 		 */
22832 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
22833 #else
22834 		if (!ISCD(un)) {
22835 #endif
22836 			err = ENOTTY;
22837 		} else {
22838 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
22839 		}
22840 		break;
22841 
22842 	case CDROMREADTOCHDR:
22843 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
22844 		if (!ISCD(un)) {
22845 			err = ENOTTY;
22846 		} else {
22847 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
22848 		}
22849 		break;
22850 
22851 	case CDROMREADTOCENTRY:
22852 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
22853 		if (!ISCD(un)) {
22854 			err = ENOTTY;
22855 		} else {
22856 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
22857 		}
22858 		break;
22859 
22860 	case CDROMSTOP:
22861 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
22862 		if (!ISCD(un)) {
22863 			err = ENOTTY;
22864 		} else {
22865 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22866 			    SD_TARGET_STOP, SD_PATH_STANDARD);
22867 			goto done_with_assess;
22868 		}
22869 		break;
22870 
22871 	case CDROMSTART:
22872 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
22873 		if (!ISCD(un)) {
22874 			err = ENOTTY;
22875 		} else {
22876 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22877 			    SD_TARGET_START, SD_PATH_STANDARD);
22878 			goto done_with_assess;
22879 		}
22880 		break;
22881 
22882 	case CDROMCLOSETRAY:
22883 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
22884 		if (!ISCD(un)) {
22885 			err = ENOTTY;
22886 		} else {
22887 			err = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
22888 			    SD_TARGET_CLOSE, SD_PATH_STANDARD);
22889 			goto done_with_assess;
22890 		}
22891 		break;
22892 
22893 	case FDEJECT:	/* for eject command */
22894 	case DKIOCEJECT:
22895 	case CDROMEJECT:
22896 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
22897 		if (!un->un_f_eject_media_supported) {
22898 			err = ENOTTY;
22899 		} else {
22900 			err = sr_eject(dev);
22901 		}
22902 		break;
22903 
22904 	case CDROMVOLCTRL:
22905 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
22906 		if (!ISCD(un)) {
22907 			err = ENOTTY;
22908 		} else {
22909 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
22910 		}
22911 		break;
22912 
22913 	case CDROMSUBCHNL:
22914 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
22915 		if (!ISCD(un)) {
22916 			err = ENOTTY;
22917 		} else {
22918 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
22919 		}
22920 		break;
22921 
22922 	case CDROMREADMODE2:
22923 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
22924 		if (!ISCD(un)) {
22925 			err = ENOTTY;
22926 		} else if (un->un_f_cfg_is_atapi == TRUE) {
22927 			/*
22928 			 * If the drive supports READ CD, use that instead of
22929 			 * switching the LBA size via a MODE SELECT
22930 			 * Block Descriptor
22931 			 */
22932 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
22933 		} else {
22934 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
22935 		}
22936 		break;
22937 
22938 	case CDROMREADMODE1:
22939 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
22940 		if (!ISCD(un)) {
22941 			err = ENOTTY;
22942 		} else {
22943 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
22944 		}
22945 		break;
22946 
22947 	case CDROMREADOFFSET:
22948 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
22949 		if (!ISCD(un)) {
22950 			err = ENOTTY;
22951 		} else {
22952 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
22953 			    flag);
22954 		}
22955 		break;
22956 
22957 	case CDROMSBLKMODE:
22958 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
22959 		/*
22960 		 * There is no means of changing block size in case of atapi
22961 		 * drives, thus return ENOTTY if drive type is atapi
22962 		 */
22963 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
22964 			err = ENOTTY;
22965 		} else if (un->un_f_mmc_cap == TRUE) {
22966 
22967 			/*
22968 			 * MMC Devices do not support changing the
22969 			 * logical block size
22970 			 *
22971 			 * Note: EINVAL is being returned instead of ENOTTY to
22972 			 * maintain consistancy with the original mmc
22973 			 * driver update.
22974 			 */
22975 			err = EINVAL;
22976 		} else {
22977 			mutex_enter(SD_MUTEX(un));
22978 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
22979 			    (un->un_ncmds_in_transport > 0)) {
22980 				mutex_exit(SD_MUTEX(un));
22981 				err = EINVAL;
22982 			} else {
22983 				mutex_exit(SD_MUTEX(un));
22984 				err = sr_change_blkmode(dev, cmd, arg, flag);
22985 			}
22986 		}
22987 		break;
22988 
22989 	case CDROMGBLKMODE:
22990 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
22991 		if (!ISCD(un)) {
22992 			err = ENOTTY;
22993 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
22994 		    (un->un_f_blockcount_is_valid != FALSE)) {
22995 			/*
22996 			 * Drive is an ATAPI drive so return target block
22997 			 * size for ATAPI drives since we cannot change the
22998 			 * blocksize on ATAPI drives. Used primarily to detect
22999 			 * if an ATAPI cdrom is present.
23000 			 */
23001 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
23002 			    sizeof (int), flag) != 0) {
23003 				err = EFAULT;
23004 			} else {
23005 				err = 0;
23006 			}
23007 
23008 		} else {
23009 			/*
23010 			 * Drive supports changing block sizes via a Mode
23011 			 * Select.
23012 			 */
23013 			err = sr_change_blkmode(dev, cmd, arg, flag);
23014 		}
23015 		break;
23016 
23017 	case CDROMGDRVSPEED:
23018 	case CDROMSDRVSPEED:
23019 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
23020 		if (!ISCD(un)) {
23021 			err = ENOTTY;
23022 		} else if (un->un_f_mmc_cap == TRUE) {
23023 			/*
23024 			 * Note: In the future the driver implementation
23025 			 * for getting and
23026 			 * setting cd speed should entail:
23027 			 * 1) If non-mmc try the Toshiba mode page
23028 			 *    (sr_change_speed)
23029 			 * 2) If mmc but no support for Real Time Streaming try
23030 			 *    the SET CD SPEED (0xBB) command
23031 			 *   (sr_atapi_change_speed)
23032 			 * 3) If mmc and support for Real Time Streaming
23033 			 *    try the GET PERFORMANCE and SET STREAMING
23034 			 *    commands (not yet implemented, 4380808)
23035 			 */
23036 			/*
23037 			 * As per recent MMC spec, CD-ROM speed is variable
23038 			 * and changes with LBA. Since there is no such
23039 			 * things as drive speed now, fail this ioctl.
23040 			 *
23041 			 * Note: EINVAL is returned for consistancy of original
23042 			 * implementation which included support for getting
23043 			 * the drive speed of mmc devices but not setting
23044 			 * the drive speed. Thus EINVAL would be returned
23045 			 * if a set request was made for an mmc device.
23046 			 * We no longer support get or set speed for
23047 			 * mmc but need to remain consistent with regard
23048 			 * to the error code returned.
23049 			 */
23050 			err = EINVAL;
23051 		} else if (un->un_f_cfg_is_atapi == TRUE) {
23052 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
23053 		} else {
23054 			err = sr_change_speed(dev, cmd, arg, flag);
23055 		}
23056 		break;
23057 
23058 	case CDROMCDDA:
23059 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
23060 		if (!ISCD(un)) {
23061 			err = ENOTTY;
23062 		} else {
23063 			err = sr_read_cdda(dev, (void *)arg, flag);
23064 		}
23065 		break;
23066 
23067 	case CDROMCDXA:
23068 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
23069 		if (!ISCD(un)) {
23070 			err = ENOTTY;
23071 		} else {
23072 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
23073 		}
23074 		break;
23075 
23076 	case CDROMSUBCODE:
23077 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
23078 		if (!ISCD(un)) {
23079 			err = ENOTTY;
23080 		} else {
23081 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
23082 		}
23083 		break;
23084 
23085 
23086 #ifdef SDDEBUG
23087 /* RESET/ABORTS testing ioctls */
23088 	case DKIOCRESET: {
23089 		int	reset_level;
23090 
23091 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
23092 			err = EFAULT;
23093 		} else {
23094 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
23095 			    "reset_level = 0x%lx\n", reset_level);
23096 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
23097 				err = 0;
23098 			} else {
23099 				err = EIO;
23100 			}
23101 		}
23102 		break;
23103 	}
23104 
23105 	case DKIOCABORT:
23106 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
23107 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
23108 			err = 0;
23109 		} else {
23110 			err = EIO;
23111 		}
23112 		break;
23113 #endif
23114 
23115 #ifdef SD_FAULT_INJECTION
23116 /* SDIOC FaultInjection testing ioctls */
23117 	case SDIOCSTART:
23118 	case SDIOCSTOP:
23119 	case SDIOCINSERTPKT:
23120 	case SDIOCINSERTXB:
23121 	case SDIOCINSERTUN:
23122 	case SDIOCINSERTARQ:
23123 	case SDIOCPUSH:
23124 	case SDIOCRETRIEVE:
23125 	case SDIOCRUN:
23126 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
23127 		    "SDIOC detected cmd:0x%X:\n", cmd);
23128 		/* call error generator */
23129 		sd_faultinjection_ioctl(cmd, arg, un);
23130 		err = 0;
23131 		break;
23132 
23133 #endif /* SD_FAULT_INJECTION */
23134 
23135 	case DKIOCFLUSHWRITECACHE:
23136 		{
23137 			struct dk_callback *dkc = (struct dk_callback *)arg;
23138 
23139 			mutex_enter(SD_MUTEX(un));
23140 			if (!un->un_f_sync_cache_supported ||
23141 			    !un->un_f_write_cache_enabled) {
23142 				err = un->un_f_sync_cache_supported ?
23143 				    0 : ENOTSUP;
23144 				mutex_exit(SD_MUTEX(un));
23145 				if ((flag & FKIOCTL) && dkc != NULL &&
23146 				    dkc->dkc_callback != NULL) {
23147 					(*dkc->dkc_callback)(dkc->dkc_cookie,
23148 					    err);
23149 					/*
23150 					 * Did callback and reported error.
23151 					 * Since we did a callback, ioctl
23152 					 * should return 0.
23153 					 */
23154 					err = 0;
23155 				}
23156 				break;
23157 			}
23158 			mutex_exit(SD_MUTEX(un));
23159 
23160 			if ((flag & FKIOCTL) && dkc != NULL &&
23161 			    dkc->dkc_callback != NULL) {
23162 				/* async SYNC CACHE request */
23163 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
23164 			} else {
23165 				/* synchronous SYNC CACHE request */
23166 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
23167 			}
23168 		}
23169 		break;
23170 
23171 	case DKIOCFREE:
23172 		{
23173 			dkioc_free_list_t *dfl = (dkioc_free_list_t *)arg;
23174 
23175 			/* bad ioctls shouldn't panic */
23176 			if (dfl == NULL) {
23177 				/* check kernel callers strictly in debug */
23178 				ASSERT0(flag & FKIOCTL);
23179 				err = SET_ERROR(EINVAL);
23180 				break;
23181 			}
23182 			/* synchronous UNMAP request */
23183 			err = sd_send_scsi_UNMAP(dev, ssc, dfl, flag);
23184 		}
23185 		break;
23186 
23187 	case DKIOC_CANFREE:
23188 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC_CANFREE\n");
23189 		i = (un->un_thin_flags & SD_THIN_PROV_ENABLED) ? 1 : 0;
23190 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
23191 			err = EFAULT;
23192 		} else {
23193 			err = 0;
23194 		}
23195 		break;
23196 
23197 	case DKIOCGETWCE: {
23198 
23199 		int wce;
23200 
23201 		if ((err = sd_get_write_cache_enabled(ssc, &wce)) != 0) {
23202 			break;
23203 		}
23204 
23205 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
23206 			err = EFAULT;
23207 		}
23208 		break;
23209 	}
23210 
23211 	case DKIOCSETWCE: {
23212 
23213 		int wce, sync_supported;
23214 		int cur_wce = 0;
23215 
23216 		if (!un->un_f_cache_mode_changeable) {
23217 			err = EINVAL;
23218 			break;
23219 		}
23220 
23221 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
23222 			err = EFAULT;
23223 			break;
23224 		}
23225 
23226 		/*
23227 		 * Synchronize multiple threads trying to enable
23228 		 * or disable the cache via the un_f_wcc_cv
23229 		 * condition variable.
23230 		 */
23231 		mutex_enter(SD_MUTEX(un));
23232 
23233 		/*
23234 		 * Don't allow the cache to be enabled if the
23235 		 * config file has it disabled.
23236 		 */
23237 		if (un->un_f_opt_disable_cache && wce) {
23238 			mutex_exit(SD_MUTEX(un));
23239 			err = EINVAL;
23240 			break;
23241 		}
23242 
23243 		/*
23244 		 * Wait for write cache change in progress
23245 		 * bit to be clear before proceeding.
23246 		 */
23247 		while (un->un_f_wcc_inprog)
23248 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
23249 
23250 		un->un_f_wcc_inprog = 1;
23251 
23252 		mutex_exit(SD_MUTEX(un));
23253 
23254 		/*
23255 		 * Get the current write cache state
23256 		 */
23257 		if ((err = sd_get_write_cache_enabled(ssc, &cur_wce)) != 0) {
23258 			mutex_enter(SD_MUTEX(un));
23259 			un->un_f_wcc_inprog = 0;
23260 			cv_broadcast(&un->un_wcc_cv);
23261 			mutex_exit(SD_MUTEX(un));
23262 			break;
23263 		}
23264 
23265 		mutex_enter(SD_MUTEX(un));
23266 		un->un_f_write_cache_enabled = (cur_wce != 0);
23267 
23268 		if (un->un_f_write_cache_enabled && wce == 0) {
23269 			/*
23270 			 * Disable the write cache.  Don't clear
23271 			 * un_f_write_cache_enabled until after
23272 			 * the mode select and flush are complete.
23273 			 */
23274 			sync_supported = un->un_f_sync_cache_supported;
23275 
23276 			/*
23277 			 * If cache flush is suppressed, we assume that the
23278 			 * controller firmware will take care of managing the
23279 			 * write cache for us: no need to explicitly
23280 			 * disable it.
23281 			 */
23282 			if (!un->un_f_suppress_cache_flush) {
23283 				mutex_exit(SD_MUTEX(un));
23284 				if ((err = sd_cache_control(ssc,
23285 				    SD_CACHE_NOCHANGE,
23286 				    SD_CACHE_DISABLE)) == 0 &&
23287 				    sync_supported) {
23288 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
23289 					    NULL);
23290 				}
23291 			} else {
23292 				mutex_exit(SD_MUTEX(un));
23293 			}
23294 
23295 			mutex_enter(SD_MUTEX(un));
23296 			if (err == 0) {
23297 				un->un_f_write_cache_enabled = 0;
23298 			}
23299 
23300 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
23301 			/*
23302 			 * Set un_f_write_cache_enabled first, so there is
23303 			 * no window where the cache is enabled, but the
23304 			 * bit says it isn't.
23305 			 */
23306 			un->un_f_write_cache_enabled = 1;
23307 
23308 			/*
23309 			 * If cache flush is suppressed, we assume that the
23310 			 * controller firmware will take care of managing the
23311 			 * write cache for us: no need to explicitly
23312 			 * enable it.
23313 			 */
23314 			if (!un->un_f_suppress_cache_flush) {
23315 				mutex_exit(SD_MUTEX(un));
23316 				err = sd_cache_control(ssc, SD_CACHE_NOCHANGE,
23317 				    SD_CACHE_ENABLE);
23318 			} else {
23319 				mutex_exit(SD_MUTEX(un));
23320 			}
23321 
23322 			mutex_enter(SD_MUTEX(un));
23323 
23324 			if (err) {
23325 				un->un_f_write_cache_enabled = 0;
23326 			}
23327 		}
23328 
23329 		un->un_f_wcc_inprog = 0;
23330 		cv_broadcast(&un->un_wcc_cv);
23331 		mutex_exit(SD_MUTEX(un));
23332 		break;
23333 	}
23334 
23335 	default:
23336 		err = ENOTTY;
23337 		break;
23338 	}
23339 	mutex_enter(SD_MUTEX(un));
23340 	un->un_ncmds_in_driver--;
23341 	ASSERT(un->un_ncmds_in_driver >= 0);
23342 	mutex_exit(SD_MUTEX(un));
23343 
23344 
23345 done_without_assess:
23346 	sd_ssc_fini(ssc);
23347 
23348 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
23349 	return (err);
23350 
23351 done_with_assess:
23352 	mutex_enter(SD_MUTEX(un));
23353 	un->un_ncmds_in_driver--;
23354 	ASSERT(un->un_ncmds_in_driver >= 0);
23355 	mutex_exit(SD_MUTEX(un));
23356 
23357 done_quick_assess:
23358 	if (err != 0)
23359 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23360 	/* Uninitialize sd_ssc_t pointer */
23361 	sd_ssc_fini(ssc);
23362 
23363 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
23364 	return (err);
23365 }
23366 
23367 
23368 /*
23369  *    Function: sd_dkio_ctrl_info
23370  *
23371  * Description: This routine is the driver entry point for handling controller
23372  *		information ioctl requests (DKIOCINFO).
23373  *
23374  *   Arguments: dev  - the device number
23375  *		arg  - pointer to user provided dk_cinfo structure
23376  *		       specifying the controller type and attributes.
23377  *		flag - this argument is a pass through to ddi_copyxxx()
23378  *		       directly from the mode argument of ioctl().
23379  *
23380  * Return Code: 0
23381  *		EFAULT
23382  *		ENXIO
23383  */
23384 
23385 static int
23386 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
23387 {
23388 	struct sd_lun	*un = NULL;
23389 	struct dk_cinfo	*info;
23390 	dev_info_t	*pdip;
23391 	int		lun, tgt;
23392 
23393 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23394 		return (ENXIO);
23395 	}
23396 
23397 	info = (struct dk_cinfo *)
23398 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
23399 
23400 	switch (un->un_ctype) {
23401 	case CTYPE_CDROM:
23402 		info->dki_ctype = DKC_CDROM;
23403 		break;
23404 	default:
23405 		info->dki_ctype = DKC_SCSI_CCS;
23406 		break;
23407 	}
23408 	pdip = ddi_get_parent(SD_DEVINFO(un));
23409 	info->dki_cnum = ddi_get_instance(pdip);
23410 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
23411 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
23412 	} else {
23413 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
23414 		    DK_DEVLEN - 1);
23415 	}
23416 
23417 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
23418 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
23419 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
23420 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
23421 
23422 	/* Unit Information */
23423 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
23424 	info->dki_slave = ((tgt << 3) | lun);
23425 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
23426 	    DK_DEVLEN - 1);
23427 	info->dki_flags = DKI_FMTVOL;
23428 	info->dki_partition = SDPART(dev);
23429 
23430 	/* Max Transfer size of this device in blocks */
23431 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
23432 	info->dki_addr = 0;
23433 	info->dki_space = 0;
23434 	info->dki_prio = 0;
23435 	info->dki_vec = 0;
23436 
23437 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
23438 		kmem_free(info, sizeof (struct dk_cinfo));
23439 		return (EFAULT);
23440 	} else {
23441 		kmem_free(info, sizeof (struct dk_cinfo));
23442 		return (0);
23443 	}
23444 }
23445 
23446 /*
23447  *    Function: sd_get_media_info_com
23448  *
23449  * Description: This routine returns the information required to populate
23450  *		the fields for the dk_minfo/dk_minfo_ext structures.
23451  *
23452  *   Arguments: dev		- the device number
23453  *		dki_media_type	- media_type
23454  *		dki_lbsize	- logical block size
23455  *		dki_capacity	- capacity in blocks
23456  *		dki_pbsize	- physical block size (if requested)
23457  *
23458  * Return Code: 0
23459  *		EACCESS
23460  *		EFAULT
23461  *		ENXIO
23462  *		EIO
23463  */
23464 static int
23465 sd_get_media_info_com(dev_t dev, uint_t *dki_media_type, uint_t *dki_lbsize,
23466     diskaddr_t *dki_capacity, uint_t *dki_pbsize)
23467 {
23468 	struct sd_lun		*un = NULL;
23469 	struct uscsi_cmd	com;
23470 	struct scsi_inquiry	*sinq;
23471 	u_longlong_t		media_capacity;
23472 	uint64_t		capacity;
23473 	uint_t			lbasize;
23474 	uint_t			pbsize;
23475 	uchar_t			*out_data;
23476 	uchar_t			*rqbuf;
23477 	int			rval = 0;
23478 	int			rtn;
23479 	sd_ssc_t		*ssc;
23480 
23481 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
23482 	    (un->un_state == SD_STATE_OFFLINE)) {
23483 		return (ENXIO);
23484 	}
23485 
23486 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info_com: entry\n");
23487 
23488 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
23489 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
23490 	ssc = sd_ssc_init(un);
23491 
23492 	/* Issue a TUR to determine if the drive is ready with media present */
23493 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, SD_CHECK_FOR_MEDIA);
23494 	if (rval == ENXIO) {
23495 		goto done;
23496 	} else if (rval != 0) {
23497 		sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23498 	}
23499 
23500 	/* Now get configuration data */
23501 	if (ISCD(un)) {
23502 		*dki_media_type = DK_CDROM;
23503 
23504 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
23505 		if (un->un_f_mmc_cap == TRUE) {
23506 			rtn = sd_send_scsi_GET_CONFIGURATION(ssc, &com, rqbuf,
23507 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
23508 			    SD_PATH_STANDARD);
23509 
23510 			if (rtn) {
23511 				/*
23512 				 * We ignore all failures for CD and need to
23513 				 * put the assessment before processing code
23514 				 * to avoid missing assessment for FMA.
23515 				 */
23516 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23517 				/*
23518 				 * Failed for other than an illegal request
23519 				 * or command not supported
23520 				 */
23521 				if ((com.uscsi_status == STATUS_CHECK) &&
23522 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
23523 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
23524 					    (rqbuf[12] != 0x20)) {
23525 						rval = EIO;
23526 						goto no_assessment;
23527 					}
23528 				}
23529 			} else {
23530 				/*
23531 				 * The GET CONFIGURATION command succeeded
23532 				 * so set the media type according to the
23533 				 * returned data
23534 				 */
23535 				*dki_media_type = out_data[6];
23536 				*dki_media_type <<= 8;
23537 				*dki_media_type |= out_data[7];
23538 			}
23539 		}
23540 	} else {
23541 		/*
23542 		 * The profile list is not available, so we attempt to identify
23543 		 * the media type based on the inquiry data
23544 		 */
23545 		sinq = un->un_sd->sd_inq;
23546 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
23547 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
23548 			/* This is a direct access device  or optical disk */
23549 			*dki_media_type = DK_FIXED_DISK;
23550 
23551 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
23552 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
23553 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
23554 					*dki_media_type = DK_ZIP;
23555 				} else if (
23556 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
23557 					*dki_media_type = DK_JAZ;
23558 				}
23559 			}
23560 		} else {
23561 			/*
23562 			 * Not a CD, direct access or optical disk so return
23563 			 * unknown media
23564 			 */
23565 			*dki_media_type = DK_UNKNOWN;
23566 		}
23567 	}
23568 
23569 	/*
23570 	 * Now read the capacity so we can provide the lbasize,
23571 	 * pbsize and capacity.
23572 	 */
23573 	if (dki_pbsize && un->un_f_descr_format_supported) {
23574 		rval = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity, &lbasize,
23575 		    &pbsize, SD_PATH_DIRECT);
23576 
23577 		/*
23578 		 * Override the physical blocksize if the instance already
23579 		 * has a larger value.
23580 		 */
23581 		pbsize = MAX(pbsize, un->un_phy_blocksize);
23582 	}
23583 
23584 	if (dki_pbsize == NULL || rval != 0 ||
23585 	    !un->un_f_descr_format_supported) {
23586 		rval = sd_send_scsi_READ_CAPACITY(ssc, &capacity, &lbasize,
23587 		    SD_PATH_DIRECT);
23588 
23589 		switch (rval) {
23590 		case 0:
23591 			if (un->un_f_enable_rmw &&
23592 			    un->un_phy_blocksize != 0) {
23593 				pbsize = un->un_phy_blocksize;
23594 			} else {
23595 				pbsize = lbasize;
23596 			}
23597 			media_capacity = capacity;
23598 
23599 			/*
23600 			 * sd_send_scsi_READ_CAPACITY() reports capacity in
23601 			 * un->un_sys_blocksize chunks. So we need to convert
23602 			 * it into cap.lbsize chunks.
23603 			 */
23604 			if (un->un_f_has_removable_media) {
23605 				media_capacity *= un->un_sys_blocksize;
23606 				media_capacity /= lbasize;
23607 			}
23608 			break;
23609 		case EACCES:
23610 			rval = EACCES;
23611 			goto done;
23612 		default:
23613 			rval = EIO;
23614 			goto done;
23615 		}
23616 	} else {
23617 		if (un->un_f_enable_rmw &&
23618 		    !ISP2(pbsize % DEV_BSIZE)) {
23619 			pbsize = SSD_SECSIZE;
23620 		} else if (!ISP2(lbasize % DEV_BSIZE) ||
23621 		    !ISP2(pbsize % DEV_BSIZE)) {
23622 			pbsize = lbasize = DEV_BSIZE;
23623 		}
23624 		media_capacity = capacity;
23625 	}
23626 
23627 	/*
23628 	 * If lun is expanded dynamically, update the un structure.
23629 	 */
23630 	mutex_enter(SD_MUTEX(un));
23631 	if ((un->un_f_blockcount_is_valid == TRUE) &&
23632 	    (un->un_f_tgt_blocksize_is_valid == TRUE) &&
23633 	    (capacity > un->un_blockcount)) {
23634 		un->un_f_expnevent = B_FALSE;
23635 		sd_update_block_info(un, lbasize, capacity);
23636 	}
23637 	mutex_exit(SD_MUTEX(un));
23638 
23639 	*dki_lbsize = lbasize;
23640 	*dki_capacity = media_capacity;
23641 	if (dki_pbsize)
23642 		*dki_pbsize = pbsize;
23643 
23644 done:
23645 	if (rval != 0) {
23646 		if (rval == EIO)
23647 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23648 		else
23649 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23650 	}
23651 no_assessment:
23652 	sd_ssc_fini(ssc);
23653 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
23654 	kmem_free(rqbuf, SENSE_LENGTH);
23655 	return (rval);
23656 }
23657 
23658 /*
23659  *    Function: sd_get_media_info
23660  *
23661  * Description: This routine is the driver entry point for handling ioctl
23662  *		requests for the media type or command set profile used by the
23663  *		drive to operate on the media (DKIOCGMEDIAINFO).
23664  *
23665  *   Arguments: dev	- the device number
23666  *		arg	- pointer to user provided dk_minfo structure
23667  *			  specifying the media type, logical block size and
23668  *			  drive capacity.
23669  *		flag	- this argument is a pass through to ddi_copyxxx()
23670  *			  directly from the mode argument of ioctl().
23671  *
23672  * Return Code: returns the value from sd_get_media_info_com
23673  */
23674 static int
23675 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
23676 {
23677 	struct dk_minfo		mi;
23678 	int			rval;
23679 
23680 	rval = sd_get_media_info_com(dev, &mi.dki_media_type,
23681 	    &mi.dki_lbsize, &mi.dki_capacity, NULL);
23682 
23683 	if (rval)
23684 		return (rval);
23685 	if (ddi_copyout(&mi, arg, sizeof (struct dk_minfo), flag))
23686 		rval = EFAULT;
23687 	return (rval);
23688 }
23689 
23690 /*
23691  *    Function: sd_get_media_info_ext
23692  *
23693  * Description: This routine is the driver entry point for handling ioctl
23694  *		requests for the media type or command set profile used by the
23695  *		drive to operate on the media (DKIOCGMEDIAINFOEXT). The
23696  *		difference this ioctl and DKIOCGMEDIAINFO is the return value
23697  *		of this ioctl contains both logical block size and physical
23698  *		block size.
23699  *
23700  *
23701  *   Arguments: dev	- the device number
23702  *		arg	- pointer to user provided dk_minfo_ext structure
23703  *			  specifying the media type, logical block size,
23704  *			  physical block size and disk capacity.
23705  *		flag	- this argument is a pass through to ddi_copyxxx()
23706  *			  directly from the mode argument of ioctl().
23707  *
23708  * Return Code: returns the value from sd_get_media_info_com
23709  */
23710 static int
23711 sd_get_media_info_ext(dev_t dev, caddr_t arg, int flag)
23712 {
23713 	struct dk_minfo_ext	mie;
23714 	int			rval = 0;
23715 	size_t			len;
23716 
23717 	rval = sd_get_media_info_com(dev, &mie.dki_media_type,
23718 	    &mie.dki_lbsize, &mie.dki_capacity, &mie.dki_pbsize);
23719 
23720 	if (rval)
23721 		return (rval);
23722 
23723 	switch (ddi_model_convert_from(flag & FMODELS)) {
23724 	case DDI_MODEL_ILP32:
23725 		len = sizeof (struct dk_minfo_ext32);
23726 		break;
23727 	default:
23728 		len = sizeof (struct dk_minfo_ext);
23729 		break;
23730 	}
23731 
23732 	if (ddi_copyout(&mie, arg, len, flag))
23733 		rval = EFAULT;
23734 	return (rval);
23735 
23736 }
23737 
23738 /*
23739  *    Function: sd_watch_request_submit
23740  *
23741  * Description: Call scsi_watch_request_submit or scsi_mmc_watch_request_submit
23742  *		depending on which is supported by device.
23743  */
23744 static opaque_t
23745 sd_watch_request_submit(struct sd_lun *un)
23746 {
23747 	dev_t			dev;
23748 
23749 	/* All submissions are unified to use same device number */
23750 	dev = sd_make_device(SD_DEVINFO(un));
23751 
23752 	if (un->un_f_mmc_cap && un->un_f_mmc_gesn_polling) {
23753 		return (scsi_mmc_watch_request_submit(SD_SCSI_DEVP(un),
23754 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
23755 		    (caddr_t)dev));
23756 	} else {
23757 		return (scsi_watch_request_submit(SD_SCSI_DEVP(un),
23758 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
23759 		    (caddr_t)dev));
23760 	}
23761 }
23762 
23763 
23764 /*
23765  *    Function: sd_check_media
23766  *
23767  * Description: This utility routine implements the functionality for the
23768  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
23769  *		driver state changes from that specified by the user
23770  *		(inserted or ejected). For example, if the user specifies
23771  *		DKIO_EJECTED and the current media state is inserted this
23772  *		routine will immediately return DKIO_INSERTED. However, if the
23773  *		current media state is not inserted the user thread will be
23774  *		blocked until the drive state changes. If DKIO_NONE is specified
23775  *		the user thread will block until a drive state change occurs.
23776  *
23777  *   Arguments: dev  - the device number
23778  *		state  - user pointer to a dkio_state, updated with the current
23779  *			drive state at return.
23780  *
23781  * Return Code: ENXIO
23782  *		EIO
23783  *		EAGAIN
23784  *		EINTR
23785  */
23786 
23787 static int
23788 sd_check_media(dev_t dev, enum dkio_state state)
23789 {
23790 	struct sd_lun		*un = NULL;
23791 	enum dkio_state		prev_state;
23792 	opaque_t		token = NULL;
23793 	int			rval = 0;
23794 	sd_ssc_t		*ssc;
23795 
23796 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23797 		return (ENXIO);
23798 	}
23799 
23800 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
23801 
23802 	ssc = sd_ssc_init(un);
23803 
23804 	mutex_enter(SD_MUTEX(un));
23805 
23806 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
23807 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
23808 
23809 	prev_state = un->un_mediastate;
23810 
23811 	/* is there anything to do? */
23812 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
23813 		/*
23814 		 * submit the request to the scsi_watch service;
23815 		 * scsi_media_watch_cb() does the real work
23816 		 */
23817 		mutex_exit(SD_MUTEX(un));
23818 
23819 		/*
23820 		 * This change handles the case where a scsi watch request is
23821 		 * added to a device that is powered down. To accomplish this
23822 		 * we power up the device before adding the scsi watch request,
23823 		 * since the scsi watch sends a TUR directly to the device
23824 		 * which the device cannot handle if it is powered down.
23825 		 */
23826 		if (sd_pm_entry(un) != DDI_SUCCESS) {
23827 			mutex_enter(SD_MUTEX(un));
23828 			goto done;
23829 		}
23830 
23831 		token = sd_watch_request_submit(un);
23832 
23833 		sd_pm_exit(un);
23834 
23835 		mutex_enter(SD_MUTEX(un));
23836 		if (token == NULL) {
23837 			rval = EAGAIN;
23838 			goto done;
23839 		}
23840 
23841 		/*
23842 		 * This is a special case IOCTL that doesn't return
23843 		 * until the media state changes. Routine sdpower
23844 		 * knows about and handles this so don't count it
23845 		 * as an active cmd in the driver, which would
23846 		 * keep the device busy to the pm framework.
23847 		 * If the count isn't decremented the device can't
23848 		 * be powered down.
23849 		 */
23850 		un->un_ncmds_in_driver--;
23851 		ASSERT(un->un_ncmds_in_driver >= 0);
23852 
23853 		/*
23854 		 * if a prior request had been made, this will be the same
23855 		 * token, as scsi_watch was designed that way.
23856 		 */
23857 		un->un_swr_token = token;
23858 		un->un_specified_mediastate = state;
23859 
23860 		/*
23861 		 * now wait for media change
23862 		 * we will not be signalled unless mediastate == state but it is
23863 		 * still better to test for this condition, since there is a
23864 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
23865 		 */
23866 		SD_TRACE(SD_LOG_COMMON, un,
23867 		    "sd_check_media: waiting for media state change\n");
23868 		while (un->un_mediastate == state) {
23869 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
23870 				SD_TRACE(SD_LOG_COMMON, un,
23871 				    "sd_check_media: waiting for media state "
23872 				    "was interrupted\n");
23873 				un->un_ncmds_in_driver++;
23874 				rval = EINTR;
23875 				goto done;
23876 			}
23877 			SD_TRACE(SD_LOG_COMMON, un,
23878 			    "sd_check_media: received signal, state=%x\n",
23879 			    un->un_mediastate);
23880 		}
23881 		/*
23882 		 * Inc the counter to indicate the device once again
23883 		 * has an active outstanding cmd.
23884 		 */
23885 		un->un_ncmds_in_driver++;
23886 	}
23887 
23888 	/* invalidate geometry */
23889 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
23890 		sr_ejected(un);
23891 	}
23892 
23893 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
23894 		uint64_t	capacity;
23895 		uint_t		lbasize;
23896 
23897 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
23898 		mutex_exit(SD_MUTEX(un));
23899 		/*
23900 		 * Since the following routines use SD_PATH_DIRECT, we must
23901 		 * call PM directly before the upcoming disk accesses. This
23902 		 * may cause the disk to be power/spin up.
23903 		 */
23904 
23905 		if (sd_pm_entry(un) == DDI_SUCCESS) {
23906 			rval = sd_send_scsi_READ_CAPACITY(ssc,
23907 			    &capacity, &lbasize, SD_PATH_DIRECT);
23908 			if (rval != 0) {
23909 				sd_pm_exit(un);
23910 				if (rval == EIO)
23911 					sd_ssc_assessment(ssc,
23912 					    SD_FMT_STATUS_CHECK);
23913 				else
23914 					sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23915 				mutex_enter(SD_MUTEX(un));
23916 				goto done;
23917 			}
23918 		} else {
23919 			rval = EIO;
23920 			mutex_enter(SD_MUTEX(un));
23921 			goto done;
23922 		}
23923 		mutex_enter(SD_MUTEX(un));
23924 
23925 		sd_update_block_info(un, lbasize, capacity);
23926 
23927 		/*
23928 		 *  Check if the media in the device is writable or not
23929 		 */
23930 		if (ISCD(un)) {
23931 			sd_check_for_writable_cd(ssc, SD_PATH_DIRECT);
23932 		}
23933 
23934 		mutex_exit(SD_MUTEX(un));
23935 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
23936 		if ((cmlb_validate(un->un_cmlbhandle, 0,
23937 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
23938 			sd_set_pstats(un);
23939 			SD_TRACE(SD_LOG_IO_PARTITION, un,
23940 			    "sd_check_media: un:0x%p pstats created and "
23941 			    "set\n", un);
23942 		}
23943 
23944 		rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_PREVENT,
23945 		    SD_PATH_DIRECT);
23946 
23947 		sd_pm_exit(un);
23948 
23949 		if (rval != 0) {
23950 			if (rval == EIO)
23951 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
23952 			else
23953 				sd_ssc_assessment(ssc, SD_FMT_IGNORE);
23954 		}
23955 
23956 		mutex_enter(SD_MUTEX(un));
23957 	}
23958 done:
23959 	sd_ssc_fini(ssc);
23960 	un->un_f_watcht_stopped = FALSE;
23961 	if (token != NULL && un->un_swr_token != NULL) {
23962 		/*
23963 		 * Use of this local token and the mutex ensures that we avoid
23964 		 * some race conditions associated with terminating the
23965 		 * scsi watch.
23966 		 */
23967 		token = un->un_swr_token;
23968 		mutex_exit(SD_MUTEX(un));
23969 		(void) scsi_watch_request_terminate(token,
23970 		    SCSI_WATCH_TERMINATE_WAIT);
23971 		if (scsi_watch_get_ref_count(token) == 0) {
23972 			mutex_enter(SD_MUTEX(un));
23973 			un->un_swr_token = (opaque_t)NULL;
23974 		} else {
23975 			mutex_enter(SD_MUTEX(un));
23976 		}
23977 	}
23978 
23979 	/*
23980 	 * Update the capacity kstat value, if no media previously
23981 	 * (capacity kstat is 0) and a media has been inserted
23982 	 * (un_f_blockcount_is_valid == TRUE)
23983 	 */
23984 	if (un->un_errstats) {
23985 		struct sd_errstats	*stp = NULL;
23986 
23987 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
23988 		if ((stp->sd_capacity.value.ui64 == 0) &&
23989 		    (un->un_f_blockcount_is_valid == TRUE)) {
23990 			stp->sd_capacity.value.ui64 =
23991 			    (uint64_t)((uint64_t)un->un_blockcount *
23992 			    un->un_sys_blocksize);
23993 		}
23994 	}
23995 	mutex_exit(SD_MUTEX(un));
23996 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
23997 	return (rval);
23998 }
23999 
24000 
24001 /*
24002  *    Function: sd_delayed_cv_broadcast
24003  *
24004  * Description: Delayed cv_broadcast to allow for target to recover from media
24005  *		insertion.
24006  *
24007  *   Arguments: arg - driver soft state (unit) structure
24008  */
24009 
24010 static void
24011 sd_delayed_cv_broadcast(void *arg)
24012 {
24013 	struct sd_lun *un = arg;
24014 
24015 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
24016 
24017 	mutex_enter(SD_MUTEX(un));
24018 	un->un_dcvb_timeid = NULL;
24019 	cv_broadcast(&un->un_state_cv);
24020 	mutex_exit(SD_MUTEX(un));
24021 }
24022 
24023 
24024 /*
24025  *    Function: sd_media_watch_cb
24026  *
24027  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
24028  *		routine processes the TUR sense data and updates the driver
24029  *		state if a transition has occurred. The user thread
24030  *		(sd_check_media) is then signalled.
24031  *
24032  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
24033  *			among multiple watches that share this callback function
24034  *		resultp - scsi watch facility result packet containing scsi
24035  *			  packet, status byte and sense data
24036  *
24037  * Return Code: 0 for success, -1 for failure
24038  */
24039 
24040 static int
24041 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
24042 {
24043 	struct sd_lun			*un;
24044 	struct scsi_status		*statusp = resultp->statusp;
24045 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
24046 	enum dkio_state			state = DKIO_NONE;
24047 	dev_t				dev = (dev_t)arg;
24048 	uchar_t				actual_sense_length;
24049 	uint8_t				skey, asc, ascq;
24050 
24051 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24052 		return (-1);
24053 	}
24054 	actual_sense_length = resultp->actual_sense_length;
24055 
24056 	mutex_enter(SD_MUTEX(un));
24057 	SD_TRACE(SD_LOG_COMMON, un,
24058 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
24059 	    *((char *)statusp), (void *)sensep, actual_sense_length);
24060 
24061 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
24062 		un->un_mediastate = DKIO_DEV_GONE;
24063 		cv_broadcast(&un->un_state_cv);
24064 		mutex_exit(SD_MUTEX(un));
24065 
24066 		return (0);
24067 	}
24068 
24069 	if (un->un_f_mmc_cap && un->un_f_mmc_gesn_polling) {
24070 		if (sd_gesn_media_data_valid(resultp->mmc_data)) {
24071 			if ((resultp->mmc_data[5] &
24072 			    SD_GESN_MEDIA_EVENT_STATUS_PRESENT) != 0) {
24073 				state = DKIO_INSERTED;
24074 			} else {
24075 				state = DKIO_EJECTED;
24076 			}
24077 			if ((resultp->mmc_data[4] & SD_GESN_MEDIA_EVENT_CODE) ==
24078 			    SD_GESN_MEDIA_EVENT_EJECTREQUEST) {
24079 				sd_log_eject_request_event(un, KM_NOSLEEP);
24080 			}
24081 		}
24082 	} else if (sensep != NULL) {
24083 		/*
24084 		 * If there was a check condition then sensep points to valid
24085 		 * sense data. If status was not a check condition but a
24086 		 * reservation or busy status then the new state is DKIO_NONE.
24087 		 */
24088 		skey = scsi_sense_key(sensep);
24089 		asc = scsi_sense_asc(sensep);
24090 		ascq = scsi_sense_ascq(sensep);
24091 
24092 		SD_INFO(SD_LOG_COMMON, un,
24093 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
24094 		    skey, asc, ascq);
24095 		/* This routine only uses up to 13 bytes of sense data. */
24096 		if (actual_sense_length >= 13) {
24097 			if (skey == KEY_UNIT_ATTENTION) {
24098 				if (asc == 0x28) {
24099 					state = DKIO_INSERTED;
24100 				}
24101 			} else if (skey == KEY_NOT_READY) {
24102 				/*
24103 				 * Sense data of 02/06/00 means that the
24104 				 * drive could not read the media (No
24105 				 * reference position found). In this case
24106 				 * to prevent a hang on the DKIOCSTATE IOCTL
24107 				 * we set the media state to DKIO_INSERTED.
24108 				 */
24109 				if (asc == 0x06 && ascq == 0x00)
24110 					state = DKIO_INSERTED;
24111 
24112 				/*
24113 				 * if 02/04/02  means that the host
24114 				 * should send start command. Explicitly
24115 				 * leave the media state as is
24116 				 * (inserted) as the media is inserted
24117 				 * and host has stopped device for PM
24118 				 * reasons. Upon next true read/write
24119 				 * to this media will bring the
24120 				 * device to the right state good for
24121 				 * media access.
24122 				 */
24123 				if (asc == 0x3a) {
24124 					state = DKIO_EJECTED;
24125 				} else {
24126 					/*
24127 					 * If the drive is busy with an
24128 					 * operation or long write, keep the
24129 					 * media in an inserted state.
24130 					 */
24131 
24132 					if ((asc == 0x04) &&
24133 					    ((ascq == 0x02) ||
24134 					    (ascq == 0x07) ||
24135 					    (ascq == 0x08))) {
24136 						state = DKIO_INSERTED;
24137 					}
24138 				}
24139 			} else if (skey == KEY_NO_SENSE) {
24140 				if ((asc == 0x00) && (ascq == 0x00)) {
24141 					/*
24142 					 * Sense Data 00/00/00 does not provide
24143 					 * any information about the state of
24144 					 * the media. Ignore it.
24145 					 */
24146 					mutex_exit(SD_MUTEX(un));
24147 					return (0);
24148 				}
24149 			}
24150 		}
24151 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
24152 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
24153 		state = DKIO_INSERTED;
24154 	}
24155 
24156 	SD_TRACE(SD_LOG_COMMON, un,
24157 	    "sd_media_watch_cb: state=%x, specified=%x\n",
24158 	    state, un->un_specified_mediastate);
24159 
24160 	/*
24161 	 * now signal the waiting thread if this is *not* the specified state;
24162 	 * delay the signal if the state is DKIO_INSERTED to allow the target
24163 	 * to recover
24164 	 */
24165 	if (state != un->un_specified_mediastate) {
24166 		un->un_mediastate = state;
24167 		if (state == DKIO_INSERTED) {
24168 			/*
24169 			 * delay the signal to give the drive a chance
24170 			 * to do what it apparently needs to do
24171 			 */
24172 			SD_TRACE(SD_LOG_COMMON, un,
24173 			    "sd_media_watch_cb: delayed cv_broadcast\n");
24174 			if (un->un_dcvb_timeid == NULL) {
24175 				un->un_dcvb_timeid =
24176 				    timeout(sd_delayed_cv_broadcast, un,
24177 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
24178 			}
24179 		} else {
24180 			SD_TRACE(SD_LOG_COMMON, un,
24181 			    "sd_media_watch_cb: immediate cv_broadcast\n");
24182 			cv_broadcast(&un->un_state_cv);
24183 		}
24184 	}
24185 	mutex_exit(SD_MUTEX(un));
24186 	return (0);
24187 }
24188 
24189 
24190 /*
24191  *    Function: sd_dkio_get_temp
24192  *
24193  * Description: This routine is the driver entry point for handling ioctl
24194  *		requests to get the disk temperature.
24195  *
24196  *   Arguments: dev  - the device number
24197  *		arg  - pointer to user provided dk_temperature structure.
24198  *		flag - this argument is a pass through to ddi_copyxxx()
24199  *		       directly from the mode argument of ioctl().
24200  *
24201  * Return Code: 0
24202  *		EFAULT
24203  *		ENXIO
24204  *		EAGAIN
24205  */
24206 
24207 static int
24208 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
24209 {
24210 	struct sd_lun		*un = NULL;
24211 	struct dk_temperature	*dktemp = NULL;
24212 	uchar_t			*temperature_page;
24213 	int			rval = 0;
24214 	int			path_flag = SD_PATH_STANDARD;
24215 	sd_ssc_t		*ssc;
24216 
24217 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24218 		return (ENXIO);
24219 	}
24220 
24221 	ssc = sd_ssc_init(un);
24222 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
24223 
24224 	/* copyin the disk temp argument to get the user flags */
24225 	if (ddi_copyin((void *)arg, dktemp,
24226 	    sizeof (struct dk_temperature), flag) != 0) {
24227 		rval = EFAULT;
24228 		goto done;
24229 	}
24230 
24231 	/* Initialize the temperature to invalid. */
24232 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24233 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24234 
24235 	/*
24236 	 * Note: Investigate removing the "bypass pm" semantic.
24237 	 * Can we just bypass PM always?
24238 	 */
24239 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
24240 		path_flag = SD_PATH_DIRECT;
24241 		ASSERT(!mutex_owned(&un->un_pm_mutex));
24242 		mutex_enter(&un->un_pm_mutex);
24243 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
24244 			/*
24245 			 * If DKT_BYPASS_PM is set, and the drive happens to be
24246 			 * in low power mode, we can not wake it up, Need to
24247 			 * return EAGAIN.
24248 			 */
24249 			mutex_exit(&un->un_pm_mutex);
24250 			rval = EAGAIN;
24251 			goto done;
24252 		} else {
24253 			/*
24254 			 * Indicate to PM the device is busy. This is required
24255 			 * to avoid a race - i.e. the ioctl is issuing a
24256 			 * command and the pm framework brings down the device
24257 			 * to low power mode (possible power cut-off on some
24258 			 * platforms).
24259 			 */
24260 			mutex_exit(&un->un_pm_mutex);
24261 			if (sd_pm_entry(un) != DDI_SUCCESS) {
24262 				rval = EAGAIN;
24263 				goto done;
24264 			}
24265 		}
24266 	}
24267 
24268 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
24269 
24270 	rval = sd_send_scsi_LOG_SENSE(ssc, temperature_page,
24271 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag);
24272 	if (rval != 0)
24273 		goto done2;
24274 
24275 	/*
24276 	 * For the current temperature verify that the parameter length is 0x02
24277 	 * and the parameter code is 0x00
24278 	 */
24279 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
24280 	    (temperature_page[5] == 0x00)) {
24281 		if (temperature_page[9] == 0xFF) {
24282 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
24283 		} else {
24284 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
24285 		}
24286 	}
24287 
24288 	/*
24289 	 * For the reference temperature verify that the parameter
24290 	 * length is 0x02 and the parameter code is 0x01
24291 	 */
24292 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
24293 	    (temperature_page[11] == 0x01)) {
24294 		if (temperature_page[15] == 0xFF) {
24295 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
24296 		} else {
24297 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
24298 		}
24299 	}
24300 
24301 	/* Do the copyout regardless of the temperature commands status. */
24302 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
24303 	    flag) != 0) {
24304 		rval = EFAULT;
24305 		goto done1;
24306 	}
24307 
24308 done2:
24309 	if (rval != 0) {
24310 		if (rval == EIO)
24311 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24312 		else
24313 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24314 	}
24315 done1:
24316 	if (path_flag == SD_PATH_DIRECT) {
24317 		sd_pm_exit(un);
24318 	}
24319 
24320 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
24321 done:
24322 	sd_ssc_fini(ssc);
24323 	if (dktemp != NULL) {
24324 		kmem_free(dktemp, sizeof (struct dk_temperature));
24325 	}
24326 
24327 	return (rval);
24328 }
24329 
24330 
24331 /*
24332  *    Function: sd_log_page_supported
24333  *
24334  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
24335  *		supported log pages.
24336  *
24337  *   Arguments: ssc   - ssc contains pointer to driver soft state (unit)
24338  *                      structure for this target.
24339  *		log_page -
24340  *
24341  * Return Code: -1 - on error (log sense is optional and may not be supported).
24342  *		0  - log page not found.
24343  *		1  - log page found.
24344  */
24345 
24346 static int
24347 sd_log_page_supported(sd_ssc_t *ssc, int log_page)
24348 {
24349 	uchar_t *log_page_data;
24350 	int	i;
24351 	int	match = 0;
24352 	int	log_size;
24353 	int	status = 0;
24354 	struct sd_lun	*un;
24355 
24356 	ASSERT(ssc != NULL);
24357 	un = ssc->ssc_un;
24358 	ASSERT(un != NULL);
24359 
24360 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
24361 
24362 	status = sd_send_scsi_LOG_SENSE(ssc, log_page_data, 0xFF, 0, 0x01, 0,
24363 	    SD_PATH_DIRECT);
24364 
24365 	if (status != 0) {
24366 		if (status == EIO) {
24367 			/*
24368 			 * Some disks do not support log sense, we
24369 			 * should ignore this kind of error(sense key is
24370 			 * 0x5 - illegal request).
24371 			 */
24372 			uint8_t *sensep;
24373 			int senlen;
24374 
24375 			sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
24376 			senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
24377 			    ssc->ssc_uscsi_cmd->uscsi_rqresid);
24378 
24379 			if (senlen > 0 &&
24380 			    scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) {
24381 				sd_ssc_assessment(ssc,
24382 				    SD_FMT_IGNORE_COMPROMISE);
24383 			} else {
24384 				sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24385 			}
24386 		} else {
24387 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24388 		}
24389 
24390 		SD_ERROR(SD_LOG_COMMON, un,
24391 		    "sd_log_page_supported: failed log page retrieval\n");
24392 		kmem_free(log_page_data, 0xFF);
24393 		return (-1);
24394 	}
24395 
24396 	log_size = log_page_data[3];
24397 
24398 	/*
24399 	 * The list of supported log pages start from the fourth byte. Check
24400 	 * until we run out of log pages or a match is found.
24401 	 */
24402 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
24403 		if (log_page_data[i] == log_page) {
24404 			match++;
24405 		}
24406 	}
24407 	kmem_free(log_page_data, 0xFF);
24408 	return (match);
24409 }
24410 
24411 
24412 /*
24413  *    Function: sd_mhdioc_failfast
24414  *
24415  * Description: This routine is the driver entry point for handling ioctl
24416  *		requests to enable/disable the multihost failfast option.
24417  *		(MHIOCENFAILFAST)
24418  *
24419  *   Arguments: dev	- the device number
24420  *		arg	- user specified probing interval.
24421  *		flag	- this argument is a pass through to ddi_copyxxx()
24422  *			  directly from the mode argument of ioctl().
24423  *
24424  * Return Code: 0
24425  *		EFAULT
24426  *		ENXIO
24427  */
24428 
24429 static int
24430 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
24431 {
24432 	struct sd_lun	*un = NULL;
24433 	int		mh_time;
24434 	int		rval = 0;
24435 
24436 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24437 		return (ENXIO);
24438 	}
24439 
24440 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
24441 		return (EFAULT);
24442 
24443 	if (mh_time) {
24444 		mutex_enter(SD_MUTEX(un));
24445 		un->un_resvd_status |= SD_FAILFAST;
24446 		mutex_exit(SD_MUTEX(un));
24447 		/*
24448 		 * If mh_time is INT_MAX, then this ioctl is being used for
24449 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
24450 		 */
24451 		if (mh_time != INT_MAX) {
24452 			rval = sd_check_mhd(dev, mh_time);
24453 		}
24454 	} else {
24455 		(void) sd_check_mhd(dev, 0);
24456 		mutex_enter(SD_MUTEX(un));
24457 		un->un_resvd_status &= ~SD_FAILFAST;
24458 		mutex_exit(SD_MUTEX(un));
24459 	}
24460 	return (rval);
24461 }
24462 
24463 
24464 /*
24465  *    Function: sd_mhdioc_takeown
24466  *
24467  * Description: This routine is the driver entry point for handling ioctl
24468  *		requests to forcefully acquire exclusive access rights to the
24469  *		multihost disk (MHIOCTKOWN).
24470  *
24471  *   Arguments: dev	- the device number
24472  *		arg	- user provided structure specifying the delay
24473  *			  parameters in milliseconds
24474  *		flag	- this argument is a pass through to ddi_copyxxx()
24475  *			  directly from the mode argument of ioctl().
24476  *
24477  * Return Code: 0
24478  *		EFAULT
24479  *		ENXIO
24480  */
24481 
24482 static int
24483 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
24484 {
24485 	struct sd_lun		*un = NULL;
24486 	struct mhioctkown	*tkown = NULL;
24487 	int			rval = 0;
24488 
24489 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24490 		return (ENXIO);
24491 	}
24492 
24493 	if (arg != NULL) {
24494 		tkown = (struct mhioctkown *)
24495 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
24496 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
24497 		if (rval != 0) {
24498 			rval = EFAULT;
24499 			goto error;
24500 		}
24501 	}
24502 
24503 	rval = sd_take_ownership(dev, tkown);
24504 	mutex_enter(SD_MUTEX(un));
24505 	if (rval == 0) {
24506 		un->un_resvd_status |= SD_RESERVE;
24507 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
24508 			sd_reinstate_resv_delay =
24509 			    tkown->reinstate_resv_delay * 1000;
24510 		} else {
24511 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
24512 		}
24513 		/*
24514 		 * Give the scsi_watch routine interval set by
24515 		 * the MHIOCENFAILFAST ioctl precedence here.
24516 		 */
24517 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
24518 			mutex_exit(SD_MUTEX(un));
24519 			(void) sd_check_mhd(dev,
24520 			    sd_reinstate_resv_delay / 1000);
24521 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
24522 			    "sd_mhdioc_takeown : %d\n",
24523 			    sd_reinstate_resv_delay);
24524 		} else {
24525 			mutex_exit(SD_MUTEX(un));
24526 		}
24527 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
24528 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24529 	} else {
24530 		un->un_resvd_status &= ~SD_RESERVE;
24531 		mutex_exit(SD_MUTEX(un));
24532 	}
24533 
24534 error:
24535 	if (tkown != NULL) {
24536 		kmem_free(tkown, sizeof (struct mhioctkown));
24537 	}
24538 	return (rval);
24539 }
24540 
24541 
24542 /*
24543  *    Function: sd_mhdioc_release
24544  *
24545  * Description: This routine is the driver entry point for handling ioctl
24546  *		requests to release exclusive access rights to the multihost
24547  *		disk (MHIOCRELEASE).
24548  *
24549  *   Arguments: dev	- the device number
24550  *
24551  * Return Code: 0
24552  *		ENXIO
24553  */
24554 
24555 static int
24556 sd_mhdioc_release(dev_t dev)
24557 {
24558 	struct sd_lun		*un = NULL;
24559 	timeout_id_t		resvd_timeid_save;
24560 	int			resvd_status_save;
24561 	int			rval = 0;
24562 
24563 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24564 		return (ENXIO);
24565 	}
24566 
24567 	mutex_enter(SD_MUTEX(un));
24568 	resvd_status_save = un->un_resvd_status;
24569 	un->un_resvd_status &=
24570 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
24571 	if (un->un_resvd_timeid) {
24572 		resvd_timeid_save = un->un_resvd_timeid;
24573 		un->un_resvd_timeid = NULL;
24574 		mutex_exit(SD_MUTEX(un));
24575 		(void) untimeout(resvd_timeid_save);
24576 	} else {
24577 		mutex_exit(SD_MUTEX(un));
24578 	}
24579 
24580 	/*
24581 	 * destroy any pending timeout thread that may be attempting to
24582 	 * reinstate reservation on this device.
24583 	 */
24584 	sd_rmv_resv_reclaim_req(dev);
24585 
24586 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
24587 		mutex_enter(SD_MUTEX(un));
24588 		if ((un->un_mhd_token) &&
24589 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
24590 			mutex_exit(SD_MUTEX(un));
24591 			(void) sd_check_mhd(dev, 0);
24592 		} else {
24593 			mutex_exit(SD_MUTEX(un));
24594 		}
24595 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
24596 		    sd_mhd_reset_notify_cb, (caddr_t)un);
24597 	} else {
24598 		/*
24599 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
24600 		 */
24601 		mutex_enter(SD_MUTEX(un));
24602 		un->un_resvd_status = resvd_status_save;
24603 		mutex_exit(SD_MUTEX(un));
24604 	}
24605 	return (rval);
24606 }
24607 
24608 
24609 /*
24610  *    Function: sd_mhdioc_register_devid
24611  *
24612  * Description: This routine is the driver entry point for handling ioctl
24613  *		requests to register the device id (MHIOCREREGISTERDEVID).
24614  *
24615  *		Note: The implementation for this ioctl has been updated to
24616  *		be consistent with the original PSARC case (1999/357)
24617  *		(4375899, 4241671, 4220005)
24618  *
24619  *   Arguments: dev	- the device number
24620  *
24621  * Return Code: 0
24622  *		ENXIO
24623  */
24624 
24625 static int
24626 sd_mhdioc_register_devid(dev_t dev)
24627 {
24628 	struct sd_lun	*un = NULL;
24629 	int		rval = 0;
24630 	sd_ssc_t	*ssc;
24631 
24632 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24633 		return (ENXIO);
24634 	}
24635 
24636 	ASSERT(!mutex_owned(SD_MUTEX(un)));
24637 
24638 	mutex_enter(SD_MUTEX(un));
24639 
24640 	/* If a devid already exists, de-register it */
24641 	if (un->un_devid != NULL) {
24642 		ddi_devid_unregister(SD_DEVINFO(un));
24643 		/*
24644 		 * After unregister devid, needs to free devid memory
24645 		 */
24646 		ddi_devid_free(un->un_devid);
24647 		un->un_devid = NULL;
24648 	}
24649 
24650 	/* Check for reservation conflict */
24651 	mutex_exit(SD_MUTEX(un));
24652 	ssc = sd_ssc_init(un);
24653 	rval = sd_send_scsi_TEST_UNIT_READY(ssc, 0);
24654 	mutex_enter(SD_MUTEX(un));
24655 
24656 	switch (rval) {
24657 	case 0:
24658 		sd_register_devid(ssc, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
24659 		break;
24660 	case EACCES:
24661 		break;
24662 	default:
24663 		rval = EIO;
24664 	}
24665 
24666 	mutex_exit(SD_MUTEX(un));
24667 	if (rval != 0) {
24668 		if (rval == EIO)
24669 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
24670 		else
24671 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
24672 	}
24673 	sd_ssc_fini(ssc);
24674 	return (rval);
24675 }
24676 
24677 
24678 /*
24679  *    Function: sd_mhdioc_inkeys
24680  *
24681  * Description: This routine is the driver entry point for handling ioctl
24682  *		requests to issue the SCSI-3 Persistent In Read Keys command
24683  *		to the device (MHIOCGRP_INKEYS).
24684  *
24685  *   Arguments: dev	- the device number
24686  *		arg	- user provided in_keys structure
24687  *		flag	- this argument is a pass through to ddi_copyxxx()
24688  *			  directly from the mode argument of ioctl().
24689  *
24690  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
24691  *		ENXIO
24692  *		EFAULT
24693  */
24694 
24695 static int
24696 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
24697 {
24698 	struct sd_lun		*un;
24699 	mhioc_inkeys_t		inkeys;
24700 	int			rval = 0;
24701 
24702 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24703 		return (ENXIO);
24704 	}
24705 
24706 #ifdef _MULTI_DATAMODEL
24707 	switch (ddi_model_convert_from(flag & FMODELS)) {
24708 	case DDI_MODEL_ILP32: {
24709 		struct mhioc_inkeys32	inkeys32;
24710 
24711 		if (ddi_copyin(arg, &inkeys32,
24712 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
24713 			return (EFAULT);
24714 		}
24715 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
24716 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24717 		    &inkeys, flag)) != 0) {
24718 			return (rval);
24719 		}
24720 		inkeys32.generation = inkeys.generation;
24721 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
24722 		    flag) != 0) {
24723 			return (EFAULT);
24724 		}
24725 		break;
24726 	}
24727 	case DDI_MODEL_NONE:
24728 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
24729 		    flag) != 0) {
24730 			return (EFAULT);
24731 		}
24732 		if ((rval = sd_persistent_reservation_in_read_keys(un,
24733 		    &inkeys, flag)) != 0) {
24734 			return (rval);
24735 		}
24736 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
24737 		    flag) != 0) {
24738 			return (EFAULT);
24739 		}
24740 		break;
24741 	}
24742 
24743 #else /* ! _MULTI_DATAMODEL */
24744 
24745 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
24746 		return (EFAULT);
24747 	}
24748 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
24749 	if (rval != 0) {
24750 		return (rval);
24751 	}
24752 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
24753 		return (EFAULT);
24754 	}
24755 
24756 #endif /* _MULTI_DATAMODEL */
24757 
24758 	return (rval);
24759 }
24760 
24761 
24762 /*
24763  *    Function: sd_mhdioc_inresv
24764  *
24765  * Description: This routine is the driver entry point for handling ioctl
24766  *		requests to issue the SCSI-3 Persistent In Read Reservations
24767  *		command to the device (MHIOCGRP_INKEYS).
24768  *
24769  *   Arguments: dev	- the device number
24770  *		arg	- user provided in_resv structure
24771  *		flag	- this argument is a pass through to ddi_copyxxx()
24772  *			  directly from the mode argument of ioctl().
24773  *
24774  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
24775  *		ENXIO
24776  *		EFAULT
24777  */
24778 
24779 static int
24780 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
24781 {
24782 	struct sd_lun		*un;
24783 	mhioc_inresvs_t		inresvs;
24784 	int			rval = 0;
24785 
24786 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24787 		return (ENXIO);
24788 	}
24789 
24790 #ifdef _MULTI_DATAMODEL
24791 
24792 	switch (ddi_model_convert_from(flag & FMODELS)) {
24793 	case DDI_MODEL_ILP32: {
24794 		struct mhioc_inresvs32	inresvs32;
24795 
24796 		if (ddi_copyin(arg, &inresvs32,
24797 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24798 			return (EFAULT);
24799 		}
24800 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
24801 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24802 		    &inresvs, flag)) != 0) {
24803 			return (rval);
24804 		}
24805 		inresvs32.generation = inresvs.generation;
24806 		if (ddi_copyout(&inresvs32, arg,
24807 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
24808 			return (EFAULT);
24809 		}
24810 		break;
24811 	}
24812 	case DDI_MODEL_NONE:
24813 		if (ddi_copyin(arg, &inresvs,
24814 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24815 			return (EFAULT);
24816 		}
24817 		if ((rval = sd_persistent_reservation_in_read_resv(un,
24818 		    &inresvs, flag)) != 0) {
24819 			return (rval);
24820 		}
24821 		if (ddi_copyout(&inresvs, arg,
24822 		    sizeof (mhioc_inresvs_t), flag) != 0) {
24823 			return (EFAULT);
24824 		}
24825 		break;
24826 	}
24827 
24828 #else /* ! _MULTI_DATAMODEL */
24829 
24830 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
24831 		return (EFAULT);
24832 	}
24833 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
24834 	if (rval != 0) {
24835 		return (rval);
24836 	}
24837 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
24838 		return (EFAULT);
24839 	}
24840 
24841 #endif /* ! _MULTI_DATAMODEL */
24842 
24843 	return (rval);
24844 }
24845 
24846 
24847 /*
24848  * The following routines support the clustering functionality described below
24849  * and implement lost reservation reclaim functionality.
24850  *
24851  * Clustering
24852  * ----------
24853  * The clustering code uses two different, independent forms of SCSI
24854  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
24855  * Persistent Group Reservations. For any particular disk, it will use either
24856  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
24857  *
24858  * SCSI-2
24859  * The cluster software takes ownership of a multi-hosted disk by issuing the
24860  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
24861  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
24862  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
24863  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
24864  * driver. The meaning of failfast is that if the driver (on this host) ever
24865  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
24866  * it should immediately panic the host. The motivation for this ioctl is that
24867  * if this host does encounter reservation conflict, the underlying cause is
24868  * that some other host of the cluster has decided that this host is no longer
24869  * in the cluster and has seized control of the disks for itself. Since this
24870  * host is no longer in the cluster, it ought to panic itself. The
24871  * MHIOCENFAILFAST ioctl does two things:
24872  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
24873  *      error to panic the host
24874  *      (b) it sets up a periodic timer to test whether this host still has
24875  *      "access" (in that no other host has reserved the device):  if the
24876  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
24877  *      purpose of that periodic timer is to handle scenarios where the host is
24878  *      otherwise temporarily quiescent, temporarily doing no real i/o.
24879  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
24880  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
24881  * the device itself.
24882  *
24883  * SCSI-3 PGR
24884  * A direct semantic implementation of the SCSI-3 Persistent Reservation
24885  * facility is supported through the shared multihost disk ioctls
24886  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
24887  * MHIOCGRP_PREEMPTANDABORT, MHIOCGRP_CLEAR)
24888  *
24889  * Reservation Reclaim:
24890  * --------------------
24891  * To support the lost reservation reclaim operations this driver creates a
24892  * single thread to handle reinstating reservations on all devices that have
24893  * lost reservations sd_resv_reclaim_requests are logged for all devices that
24894  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
24895  * and the reservation reclaim thread loops through the requests to regain the
24896  * lost reservations.
24897  */
24898 
24899 /*
24900  *    Function: sd_check_mhd()
24901  *
24902  * Description: This function sets up and submits a scsi watch request or
24903  *		terminates an existing watch request. This routine is used in
24904  *		support of reservation reclaim.
24905  *
24906  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
24907  *			 among multiple watches that share the callback function
24908  *		interval - the number of microseconds specifying the watch
24909  *			   interval for issuing TEST UNIT READY commands. If
24910  *			   set to 0 the watch should be terminated. If the
24911  *			   interval is set to 0 and if the device is required
24912  *			   to hold reservation while disabling failfast, the
24913  *			   watch is restarted with an interval of
24914  *			   reinstate_resv_delay.
24915  *
24916  * Return Code: 0	   - Successful submit/terminate of scsi watch request
24917  *		ENXIO      - Indicates an invalid device was specified
24918  *		EAGAIN     - Unable to submit the scsi watch request
24919  */
24920 
24921 static int
24922 sd_check_mhd(dev_t dev, int interval)
24923 {
24924 	struct sd_lun	*un;
24925 	opaque_t	token;
24926 
24927 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24928 		return (ENXIO);
24929 	}
24930 
24931 	/* is this a watch termination request? */
24932 	if (interval == 0) {
24933 		mutex_enter(SD_MUTEX(un));
24934 		/* if there is an existing watch task then terminate it */
24935 		if (un->un_mhd_token) {
24936 			token = un->un_mhd_token;
24937 			un->un_mhd_token = NULL;
24938 			mutex_exit(SD_MUTEX(un));
24939 			(void) scsi_watch_request_terminate(token,
24940 			    SCSI_WATCH_TERMINATE_ALL_WAIT);
24941 			mutex_enter(SD_MUTEX(un));
24942 		} else {
24943 			mutex_exit(SD_MUTEX(un));
24944 			/*
24945 			 * Note: If we return here we don't check for the
24946 			 * failfast case. This is the original legacy
24947 			 * implementation but perhaps we should be checking
24948 			 * the failfast case.
24949 			 */
24950 			return (0);
24951 		}
24952 		/*
24953 		 * If the device is required to hold reservation while
24954 		 * disabling failfast, we need to restart the scsi_watch
24955 		 * routine with an interval of reinstate_resv_delay.
24956 		 */
24957 		if (un->un_resvd_status & SD_RESERVE) {
24958 			interval = sd_reinstate_resv_delay / 1000;
24959 		} else {
24960 			/* no failfast so bail */
24961 			mutex_exit(SD_MUTEX(un));
24962 			return (0);
24963 		}
24964 		mutex_exit(SD_MUTEX(un));
24965 	}
24966 
24967 	/*
24968 	 * adjust minimum time interval to 1 second,
24969 	 * and convert from msecs to usecs
24970 	 */
24971 	if (interval > 0 && interval < 1000) {
24972 		interval = 1000;
24973 	}
24974 	interval *= 1000;
24975 
24976 	/*
24977 	 * submit the request to the scsi_watch service
24978 	 */
24979 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
24980 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
24981 	if (token == NULL) {
24982 		return (EAGAIN);
24983 	}
24984 
24985 	/*
24986 	 * save token for termination later on
24987 	 */
24988 	mutex_enter(SD_MUTEX(un));
24989 	un->un_mhd_token = token;
24990 	mutex_exit(SD_MUTEX(un));
24991 	return (0);
24992 }
24993 
24994 
24995 /*
24996  *    Function: sd_mhd_watch_cb()
24997  *
24998  * Description: This function is the call back function used by the scsi watch
24999  *		facility. The scsi watch facility sends the "Test Unit Ready"
25000  *		and processes the status. If applicable (i.e. a "Unit Attention"
25001  *		status and automatic "Request Sense" not used) the scsi watch
25002  *		facility will send a "Request Sense" and retrieve the sense data
25003  *		to be passed to this callback function. In either case the
25004  *		automatic "Request Sense" or the facility submitting one, this
25005  *		callback is passed the status and sense data.
25006  *
25007  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
25008  *			among multiple watches that share this callback function
25009  *		resultp - scsi watch facility result packet containing scsi
25010  *			  packet, status byte and sense data
25011  *
25012  * Return Code: 0 - continue the watch task
25013  *		non-zero - terminate the watch task
25014  */
25015 
25016 static int
25017 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
25018 {
25019 	struct sd_lun			*un;
25020 	struct scsi_status		*statusp;
25021 	uint8_t				*sensep;
25022 	struct scsi_pkt			*pkt;
25023 	uchar_t				actual_sense_length;
25024 	dev_t				dev = (dev_t)arg;
25025 
25026 	ASSERT(resultp != NULL);
25027 	statusp			= resultp->statusp;
25028 	sensep			= (uint8_t *)resultp->sensep;
25029 	pkt			= resultp->pkt;
25030 	actual_sense_length	= resultp->actual_sense_length;
25031 
25032 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25033 		return (ENXIO);
25034 	}
25035 
25036 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25037 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
25038 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
25039 
25040 	/* Begin processing of the status and/or sense data */
25041 	if (pkt->pkt_reason != CMD_CMPLT) {
25042 		/* Handle the incomplete packet */
25043 		sd_mhd_watch_incomplete(un, pkt);
25044 		return (0);
25045 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
25046 		if (*((unsigned char *)statusp)
25047 		    == STATUS_RESERVATION_CONFLICT) {
25048 			/*
25049 			 * Handle a reservation conflict by panicking if
25050 			 * configured for failfast or by logging the conflict
25051 			 * and updating the reservation status
25052 			 */
25053 			mutex_enter(SD_MUTEX(un));
25054 			if ((un->un_resvd_status & SD_FAILFAST) &&
25055 			    (sd_failfast_enable)) {
25056 				sd_panic_for_res_conflict(un);
25057 				/*NOTREACHED*/
25058 			}
25059 			SD_INFO(SD_LOG_IOCTL_MHD, un,
25060 			    "sd_mhd_watch_cb: Reservation Conflict\n");
25061 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
25062 			mutex_exit(SD_MUTEX(un));
25063 		}
25064 	}
25065 
25066 	if (sensep != NULL) {
25067 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
25068 			mutex_enter(SD_MUTEX(un));
25069 			if ((scsi_sense_asc(sensep) ==
25070 			    SD_SCSI_RESET_SENSE_CODE) &&
25071 			    (un->un_resvd_status & SD_RESERVE)) {
25072 				/*
25073 				 * The additional sense code indicates a power
25074 				 * on or bus device reset has occurred; update
25075 				 * the reservation status.
25076 				 */
25077 				un->un_resvd_status |=
25078 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
25079 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25080 				    "sd_mhd_watch_cb: Lost Reservation\n");
25081 			}
25082 		} else {
25083 			return (0);
25084 		}
25085 	} else {
25086 		mutex_enter(SD_MUTEX(un));
25087 	}
25088 
25089 	if ((un->un_resvd_status & SD_RESERVE) &&
25090 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
25091 		if (un->un_resvd_status & SD_WANT_RESERVE) {
25092 			/*
25093 			 * A reset occurred in between the last probe and this
25094 			 * one so if a timeout is pending cancel it.
25095 			 */
25096 			if (un->un_resvd_timeid) {
25097 				timeout_id_t temp_id = un->un_resvd_timeid;
25098 				un->un_resvd_timeid = NULL;
25099 				mutex_exit(SD_MUTEX(un));
25100 				(void) untimeout(temp_id);
25101 				mutex_enter(SD_MUTEX(un));
25102 			}
25103 			un->un_resvd_status &= ~SD_WANT_RESERVE;
25104 		}
25105 		if (un->un_resvd_timeid == 0) {
25106 			/* Schedule a timeout to handle the lost reservation */
25107 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
25108 			    (void *)dev,
25109 			    drv_usectohz(sd_reinstate_resv_delay));
25110 		}
25111 	}
25112 	mutex_exit(SD_MUTEX(un));
25113 	return (0);
25114 }
25115 
25116 
25117 /*
25118  *    Function: sd_mhd_watch_incomplete()
25119  *
25120  * Description: This function is used to find out why a scsi pkt sent by the
25121  *		scsi watch facility was not completed. Under some scenarios this
25122  *		routine will return. Otherwise it will send a bus reset to see
25123  *		if the drive is still online.
25124  *
25125  *   Arguments: un  - driver soft state (unit) structure
25126  *		pkt - incomplete scsi pkt
25127  */
25128 
25129 static void
25130 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
25131 {
25132 	int	be_chatty;
25133 	int	perr;
25134 
25135 	ASSERT(pkt != NULL);
25136 	ASSERT(un != NULL);
25137 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
25138 	perr		= (pkt->pkt_statistics & STAT_PERR);
25139 
25140 	mutex_enter(SD_MUTEX(un));
25141 	if (un->un_state == SD_STATE_DUMPING) {
25142 		mutex_exit(SD_MUTEX(un));
25143 		return;
25144 	}
25145 
25146 	switch (pkt->pkt_reason) {
25147 	case CMD_UNX_BUS_FREE:
25148 		/*
25149 		 * If we had a parity error that caused the target to drop BSY*,
25150 		 * don't be chatty about it.
25151 		 */
25152 		if (perr && be_chatty) {
25153 			be_chatty = 0;
25154 		}
25155 		break;
25156 	case CMD_TAG_REJECT:
25157 		/*
25158 		 * The SCSI-2 spec states that a tag reject will be sent by the
25159 		 * target if tagged queuing is not supported. A tag reject may
25160 		 * also be sent during certain initialization periods or to
25161 		 * control internal resources. For the latter case the target
25162 		 * may also return Queue Full.
25163 		 *
25164 		 * If this driver receives a tag reject from a target that is
25165 		 * going through an init period or controlling internal
25166 		 * resources tagged queuing will be disabled. This is a less
25167 		 * than optimal behavior but the driver is unable to determine
25168 		 * the target state and assumes tagged queueing is not supported
25169 		 */
25170 		pkt->pkt_flags = 0;
25171 		un->un_tagflags = 0;
25172 
25173 		if (un->un_f_opt_queueing == TRUE) {
25174 			un->un_throttle = min(un->un_throttle, 3);
25175 		} else {
25176 			un->un_throttle = 1;
25177 		}
25178 		mutex_exit(SD_MUTEX(un));
25179 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
25180 		mutex_enter(SD_MUTEX(un));
25181 		break;
25182 	case CMD_INCOMPLETE:
25183 		/*
25184 		 * The transport stopped with an abnormal state, fallthrough and
25185 		 * reset the target and/or bus unless selection did not complete
25186 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
25187 		 * go through a target/bus reset
25188 		 */
25189 		if (pkt->pkt_state == STATE_GOT_BUS) {
25190 			break;
25191 		}
25192 		/*FALLTHROUGH*/
25193 
25194 	case CMD_TIMEOUT:
25195 	default:
25196 		/*
25197 		 * The lun may still be running the command, so a lun reset
25198 		 * should be attempted. If the lun reset fails or cannot be
25199 		 * issued, than try a target reset. Lastly try a bus reset.
25200 		 */
25201 		if ((pkt->pkt_statistics &
25202 		    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) == 0) {
25203 			int reset_retval = 0;
25204 			mutex_exit(SD_MUTEX(un));
25205 			if (un->un_f_allow_bus_device_reset == TRUE) {
25206 				if (un->un_f_lun_reset_enabled == TRUE) {
25207 					reset_retval =
25208 					    scsi_reset(SD_ADDRESS(un),
25209 					    RESET_LUN);
25210 				}
25211 				if (reset_retval == 0) {
25212 					reset_retval =
25213 					    scsi_reset(SD_ADDRESS(un),
25214 					    RESET_TARGET);
25215 				}
25216 			}
25217 			if (reset_retval == 0) {
25218 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
25219 			}
25220 			mutex_enter(SD_MUTEX(un));
25221 		}
25222 		break;
25223 	}
25224 
25225 	/* A device/bus reset has occurred; update the reservation status. */
25226 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
25227 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
25228 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25229 			un->un_resvd_status |=
25230 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
25231 			SD_INFO(SD_LOG_IOCTL_MHD, un,
25232 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
25233 		}
25234 	}
25235 
25236 	/*
25237 	 * The disk has been turned off; Update the device state.
25238 	 *
25239 	 * Note: Should we be offlining the disk here?
25240 	 */
25241 	if (pkt->pkt_state == STATE_GOT_BUS) {
25242 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
25243 		    "Disk not responding to selection\n");
25244 		if (un->un_state != SD_STATE_OFFLINE) {
25245 			New_state(un, SD_STATE_OFFLINE);
25246 		}
25247 	} else if (be_chatty) {
25248 		/*
25249 		 * suppress messages if they are all the same pkt reason;
25250 		 * with TQ, many (up to 256) are returned with the same
25251 		 * pkt_reason
25252 		 */
25253 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
25254 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
25255 			    "sd_mhd_watch_incomplete: "
25256 			    "SCSI transport failed: reason '%s'\n",
25257 			    scsi_rname(pkt->pkt_reason));
25258 		}
25259 	}
25260 	un->un_last_pkt_reason = pkt->pkt_reason;
25261 	mutex_exit(SD_MUTEX(un));
25262 }
25263 
25264 
25265 /*
25266  *    Function: sd_sname()
25267  *
25268  * Description: This is a simple little routine to return a string containing
25269  *		a printable description of command status byte for use in
25270  *		logging.
25271  *
25272  *   Arguments: status - pointer to a status byte
25273  *
25274  * Return Code: char * - string containing status description.
25275  */
25276 
25277 static char *
25278 sd_sname(uchar_t status)
25279 {
25280 	switch (status & STATUS_MASK) {
25281 	case STATUS_GOOD:
25282 		return ("good status");
25283 	case STATUS_CHECK:
25284 		return ("check condition");
25285 	case STATUS_MET:
25286 		return ("condition met");
25287 	case STATUS_BUSY:
25288 		return ("busy");
25289 	case STATUS_INTERMEDIATE:
25290 		return ("intermediate");
25291 	case STATUS_INTERMEDIATE_MET:
25292 		return ("intermediate - condition met");
25293 	case STATUS_RESERVATION_CONFLICT:
25294 		return ("reservation_conflict");
25295 	case STATUS_TERMINATED:
25296 		return ("command terminated");
25297 	case STATUS_QFULL:
25298 		return ("queue full");
25299 	default:
25300 		return ("<unknown status>");
25301 	}
25302 }
25303 
25304 
25305 /*
25306  *    Function: sd_mhd_resvd_recover()
25307  *
25308  * Description: This function adds a reservation entry to the
25309  *		sd_resv_reclaim_request list and signals the reservation
25310  *		reclaim thread that there is work pending. If the reservation
25311  *		reclaim thread has not been previously created this function
25312  *		will kick it off.
25313  *
25314  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
25315  *			among multiple watches that share this callback function
25316  *
25317  *     Context: This routine is called by timeout() and is run in interrupt
25318  *		context. It must not sleep or call other functions which may
25319  *		sleep.
25320  */
25321 
25322 static void
25323 sd_mhd_resvd_recover(void *arg)
25324 {
25325 	dev_t			dev = (dev_t)arg;
25326 	struct sd_lun		*un;
25327 	struct sd_thr_request	*sd_treq = NULL;
25328 	struct sd_thr_request	*sd_cur = NULL;
25329 	struct sd_thr_request	*sd_prev = NULL;
25330 	int			already_there = 0;
25331 
25332 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25333 		return;
25334 	}
25335 
25336 	mutex_enter(SD_MUTEX(un));
25337 	un->un_resvd_timeid = NULL;
25338 	if (un->un_resvd_status & SD_WANT_RESERVE) {
25339 		/*
25340 		 * There was a reset so don't issue the reserve, allow the
25341 		 * sd_mhd_watch_cb callback function to notice this and
25342 		 * reschedule the timeout for reservation.
25343 		 */
25344 		mutex_exit(SD_MUTEX(un));
25345 		return;
25346 	}
25347 	mutex_exit(SD_MUTEX(un));
25348 
25349 	/*
25350 	 * Add this device to the sd_resv_reclaim_request list and the
25351 	 * sd_resv_reclaim_thread should take care of the rest.
25352 	 *
25353 	 * Note: We can't sleep in this context so if the memory allocation
25354 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
25355 	 * reschedule the timeout for reservation.  (4378460)
25356 	 */
25357 	sd_treq = (struct sd_thr_request *)
25358 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
25359 	if (sd_treq == NULL) {
25360 		return;
25361 	}
25362 
25363 	sd_treq->sd_thr_req_next = NULL;
25364 	sd_treq->dev = dev;
25365 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25366 	if (sd_tr.srq_thr_req_head == NULL) {
25367 		sd_tr.srq_thr_req_head = sd_treq;
25368 	} else {
25369 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
25370 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
25371 			if (sd_cur->dev == dev) {
25372 				/*
25373 				 * already in Queue so don't log
25374 				 * another request for the device
25375 				 */
25376 				already_there = 1;
25377 				break;
25378 			}
25379 			sd_prev = sd_cur;
25380 		}
25381 		if (!already_there) {
25382 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
25383 			    "logging request for %lx\n", dev);
25384 			sd_prev->sd_thr_req_next = sd_treq;
25385 		} else {
25386 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
25387 		}
25388 	}
25389 
25390 	/*
25391 	 * Create a kernel thread to do the reservation reclaim and free up this
25392 	 * thread. We cannot block this thread while we go away to do the
25393 	 * reservation reclaim
25394 	 */
25395 	if (sd_tr.srq_resv_reclaim_thread == NULL)
25396 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
25397 		    sd_resv_reclaim_thread, NULL,
25398 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
25399 
25400 	/* Tell the reservation reclaim thread that it has work to do */
25401 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
25402 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25403 }
25404 
25405 /*
25406  *    Function: sd_resv_reclaim_thread()
25407  *
25408  * Description: This function implements the reservation reclaim operations
25409  *
25410  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
25411  *		      among multiple watches that share this callback function
25412  */
25413 
25414 static void
25415 sd_resv_reclaim_thread()
25416 {
25417 	struct sd_lun		*un;
25418 	struct sd_thr_request	*sd_mhreq;
25419 
25420 	/* Wait for work */
25421 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25422 	if (sd_tr.srq_thr_req_head == NULL) {
25423 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
25424 		    &sd_tr.srq_resv_reclaim_mutex);
25425 	}
25426 
25427 	/* Loop while we have work */
25428 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
25429 		un = ddi_get_soft_state(sd_state,
25430 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
25431 		if (un == NULL) {
25432 			/*
25433 			 * softstate structure is NULL so just
25434 			 * dequeue the request and continue
25435 			 */
25436 			sd_tr.srq_thr_req_head =
25437 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25438 			kmem_free(sd_tr.srq_thr_cur_req,
25439 			    sizeof (struct sd_thr_request));
25440 			continue;
25441 		}
25442 
25443 		/* dequeue the request */
25444 		sd_mhreq = sd_tr.srq_thr_cur_req;
25445 		sd_tr.srq_thr_req_head =
25446 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
25447 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25448 
25449 		/*
25450 		 * Reclaim reservation only if SD_RESERVE is still set. There
25451 		 * may have been a call to MHIOCRELEASE before we got here.
25452 		 */
25453 		mutex_enter(SD_MUTEX(un));
25454 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25455 			/*
25456 			 * Note: The SD_LOST_RESERVE flag is cleared before
25457 			 * reclaiming the reservation. If this is done after the
25458 			 * call to sd_reserve_release a reservation loss in the
25459 			 * window between pkt completion of reserve cmd and
25460 			 * mutex_enter below may not be recognized
25461 			 */
25462 			un->un_resvd_status &= ~SD_LOST_RESERVE;
25463 			mutex_exit(SD_MUTEX(un));
25464 
25465 			if (sd_reserve_release(sd_mhreq->dev,
25466 			    SD_RESERVE) == 0) {
25467 				mutex_enter(SD_MUTEX(un));
25468 				un->un_resvd_status |= SD_RESERVE;
25469 				mutex_exit(SD_MUTEX(un));
25470 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25471 				    "sd_resv_reclaim_thread: "
25472 				    "Reservation Recovered\n");
25473 			} else {
25474 				mutex_enter(SD_MUTEX(un));
25475 				un->un_resvd_status |= SD_LOST_RESERVE;
25476 				mutex_exit(SD_MUTEX(un));
25477 				SD_INFO(SD_LOG_IOCTL_MHD, un,
25478 				    "sd_resv_reclaim_thread: Failed "
25479 				    "Reservation Recovery\n");
25480 			}
25481 		} else {
25482 			mutex_exit(SD_MUTEX(un));
25483 		}
25484 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25485 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
25486 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25487 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
25488 		/*
25489 		 * wakeup the destroy thread if anyone is waiting on
25490 		 * us to complete.
25491 		 */
25492 		cv_signal(&sd_tr.srq_inprocess_cv);
25493 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
25494 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
25495 	}
25496 
25497 	/*
25498 	 * cleanup the sd_tr structure now that this thread will not exist
25499 	 */
25500 	ASSERT(sd_tr.srq_thr_req_head == NULL);
25501 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
25502 	sd_tr.srq_resv_reclaim_thread = NULL;
25503 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25504 	thread_exit();
25505 }
25506 
25507 
25508 /*
25509  *    Function: sd_rmv_resv_reclaim_req()
25510  *
25511  * Description: This function removes any pending reservation reclaim requests
25512  *		for the specified device.
25513  *
25514  *   Arguments: dev - the device 'dev_t'
25515  */
25516 
25517 static void
25518 sd_rmv_resv_reclaim_req(dev_t dev)
25519 {
25520 	struct sd_thr_request *sd_mhreq;
25521 	struct sd_thr_request *sd_prev;
25522 
25523 	/* Remove a reservation reclaim request from the list */
25524 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
25525 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
25526 		/*
25527 		 * We are attempting to reinstate reservation for
25528 		 * this device. We wait for sd_reserve_release()
25529 		 * to return before we return.
25530 		 */
25531 		cv_wait(&sd_tr.srq_inprocess_cv,
25532 		    &sd_tr.srq_resv_reclaim_mutex);
25533 	} else {
25534 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
25535 		if (sd_mhreq && sd_mhreq->dev == dev) {
25536 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
25537 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25538 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25539 			return;
25540 		}
25541 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
25542 			if (sd_mhreq && sd_mhreq->dev == dev) {
25543 				break;
25544 			}
25545 			sd_prev = sd_mhreq;
25546 		}
25547 		if (sd_mhreq != NULL) {
25548 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
25549 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
25550 		}
25551 	}
25552 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
25553 }
25554 
25555 
25556 /*
25557  *    Function: sd_mhd_reset_notify_cb()
25558  *
25559  * Description: This is a call back function for scsi_reset_notify. This
25560  *		function updates the softstate reserved status and logs the
25561  *		reset. The driver scsi watch facility callback function
25562  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
25563  *		will reclaim the reservation.
25564  *
25565  *   Arguments: arg  - driver soft state (unit) structure
25566  */
25567 
25568 static void
25569 sd_mhd_reset_notify_cb(caddr_t arg)
25570 {
25571 	struct sd_lun *un = (struct sd_lun *)arg;
25572 
25573 	mutex_enter(SD_MUTEX(un));
25574 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
25575 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
25576 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25577 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
25578 	}
25579 	mutex_exit(SD_MUTEX(un));
25580 }
25581 
25582 
25583 /*
25584  *    Function: sd_take_ownership()
25585  *
25586  * Description: This routine implements an algorithm to achieve a stable
25587  *		reservation on disks which don't implement priority reserve,
25588  *		and makes sure that other host lose re-reservation attempts.
25589  *		This algorithm contains of a loop that keeps issuing the RESERVE
25590  *		for some period of time (min_ownership_delay, default 6 seconds)
25591  *		During that loop, it looks to see if there has been a bus device
25592  *		reset or bus reset (both of which cause an existing reservation
25593  *		to be lost). If the reservation is lost issue RESERVE until a
25594  *		period of min_ownership_delay with no resets has gone by, or
25595  *		until max_ownership_delay has expired. This loop ensures that
25596  *		the host really did manage to reserve the device, in spite of
25597  *		resets. The looping for min_ownership_delay (default six
25598  *		seconds) is important to early generation clustering products,
25599  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
25600  *		MHIOCENFAILFAST periodic timer of two seconds. By having
25601  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
25602  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
25603  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
25604  *		have already noticed, via the MHIOCENFAILFAST polling, that it
25605  *		no longer "owns" the disk and will have panicked itself.  Thus,
25606  *		the host issuing the MHIOCTKOWN is assured (with timing
25607  *		dependencies) that by the time it actually starts to use the
25608  *		disk for real work, the old owner is no longer accessing it.
25609  *
25610  *		min_ownership_delay is the minimum amount of time for which the
25611  *		disk must be reserved continuously devoid of resets before the
25612  *		MHIOCTKOWN ioctl will return success.
25613  *
25614  *		max_ownership_delay indicates the amount of time by which the
25615  *		take ownership should succeed or timeout with an error.
25616  *
25617  *   Arguments: dev - the device 'dev_t'
25618  *		*p  - struct containing timing info.
25619  *
25620  * Return Code: 0 for success or error code
25621  */
25622 
25623 static int
25624 sd_take_ownership(dev_t dev, struct mhioctkown *p)
25625 {
25626 	struct sd_lun	*un;
25627 	int		rval;
25628 	int		err;
25629 	int		reservation_count   = 0;
25630 	int		min_ownership_delay =  6000000; /* in usec */
25631 	int		max_ownership_delay = 30000000; /* in usec */
25632 	clock_t		start_time;	/* starting time of this algorithm */
25633 	clock_t		end_time;	/* time limit for giving up */
25634 	clock_t		ownership_time;	/* time limit for stable ownership */
25635 	clock_t		current_time;
25636 	clock_t		previous_current_time;
25637 
25638 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25639 		return (ENXIO);
25640 	}
25641 
25642 	/*
25643 	 * Attempt a device reservation. A priority reservation is requested.
25644 	 */
25645 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
25646 	    != SD_SUCCESS) {
25647 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
25648 		    "sd_take_ownership: return(1)=%d\n", rval);
25649 		return (rval);
25650 	}
25651 
25652 	/* Update the softstate reserved status to indicate the reservation */
25653 	mutex_enter(SD_MUTEX(un));
25654 	un->un_resvd_status |= SD_RESERVE;
25655 	un->un_resvd_status &=
25656 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
25657 	mutex_exit(SD_MUTEX(un));
25658 
25659 	if (p != NULL) {
25660 		if (p->min_ownership_delay != 0) {
25661 			min_ownership_delay = p->min_ownership_delay * 1000;
25662 		}
25663 		if (p->max_ownership_delay != 0) {
25664 			max_ownership_delay = p->max_ownership_delay * 1000;
25665 		}
25666 	}
25667 	SD_INFO(SD_LOG_IOCTL_MHD, un,
25668 	    "sd_take_ownership: min, max delays: %d, %d\n",
25669 	    min_ownership_delay, max_ownership_delay);
25670 
25671 	start_time = ddi_get_lbolt();
25672 	current_time	= start_time;
25673 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
25674 	end_time	= start_time + drv_usectohz(max_ownership_delay);
25675 
25676 	while (current_time - end_time < 0) {
25677 		delay(drv_usectohz(500000));
25678 
25679 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
25680 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
25681 				mutex_enter(SD_MUTEX(un));
25682 				rval = (un->un_resvd_status &
25683 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
25684 				mutex_exit(SD_MUTEX(un));
25685 				break;
25686 			}
25687 		}
25688 		previous_current_time = current_time;
25689 		current_time = ddi_get_lbolt();
25690 		mutex_enter(SD_MUTEX(un));
25691 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
25692 			ownership_time = ddi_get_lbolt() +
25693 			    drv_usectohz(min_ownership_delay);
25694 			reservation_count = 0;
25695 		} else {
25696 			reservation_count++;
25697 		}
25698 		un->un_resvd_status |= SD_RESERVE;
25699 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
25700 		mutex_exit(SD_MUTEX(un));
25701 
25702 		SD_INFO(SD_LOG_IOCTL_MHD, un,
25703 		    "sd_take_ownership: ticks for loop iteration=%ld, "
25704 		    "reservation=%s\n", (current_time - previous_current_time),
25705 		    reservation_count ? "ok" : "reclaimed");
25706 
25707 		if (current_time - ownership_time >= 0 &&
25708 		    reservation_count >= 4) {
25709 			rval = 0; /* Achieved a stable ownership */
25710 			break;
25711 		}
25712 		if (current_time - end_time >= 0) {
25713 			rval = EACCES; /* No ownership in max possible time */
25714 			break;
25715 		}
25716 	}
25717 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
25718 	    "sd_take_ownership: return(2)=%d\n", rval);
25719 	return (rval);
25720 }
25721 
25722 
25723 /*
25724  *    Function: sd_reserve_release()
25725  *
25726  * Description: This function builds and sends scsi RESERVE, RELEASE, and
25727  *		PRIORITY RESERVE commands based on a user specified command type
25728  *
25729  *   Arguments: dev - the device 'dev_t'
25730  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
25731  *		      SD_RESERVE, SD_RELEASE
25732  *
25733  * Return Code: 0 or Error Code
25734  */
25735 
25736 static int
25737 sd_reserve_release(dev_t dev, int cmd)
25738 {
25739 	struct uscsi_cmd	*com = NULL;
25740 	struct sd_lun		*un = NULL;
25741 	char			cdb[CDB_GROUP0];
25742 	int			rval;
25743 
25744 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
25745 	    (cmd == SD_PRIORITY_RESERVE));
25746 
25747 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25748 		return (ENXIO);
25749 	}
25750 
25751 	/* instantiate and initialize the command and cdb */
25752 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25753 	bzero(cdb, CDB_GROUP0);
25754 	com->uscsi_flags   = USCSI_SILENT;
25755 	com->uscsi_timeout = un->un_reserve_release_time;
25756 	com->uscsi_cdblen  = CDB_GROUP0;
25757 	com->uscsi_cdb	   = cdb;
25758 	if (cmd == SD_RELEASE) {
25759 		cdb[0] = SCMD_RELEASE;
25760 	} else {
25761 		cdb[0] = SCMD_RESERVE;
25762 	}
25763 
25764 	/* Send the command. */
25765 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25766 	    SD_PATH_STANDARD);
25767 
25768 	/*
25769 	 * "break" a reservation that is held by another host, by issuing a
25770 	 * reset if priority reserve is desired, and we could not get the
25771 	 * device.
25772 	 */
25773 	if ((cmd == SD_PRIORITY_RESERVE) &&
25774 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25775 		/*
25776 		 * First try to reset the LUN. If we cannot, then try a target
25777 		 * reset, followed by a bus reset if the target reset fails.
25778 		 */
25779 		int reset_retval = 0;
25780 		if (un->un_f_lun_reset_enabled == TRUE) {
25781 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
25782 		}
25783 		if (reset_retval == 0) {
25784 			/* The LUN reset either failed or was not issued */
25785 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
25786 		}
25787 		if ((reset_retval == 0) &&
25788 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
25789 			rval = EIO;
25790 			kmem_free(com, sizeof (*com));
25791 			return (rval);
25792 		}
25793 
25794 		bzero(com, sizeof (struct uscsi_cmd));
25795 		com->uscsi_flags   = USCSI_SILENT;
25796 		com->uscsi_cdb	   = cdb;
25797 		com->uscsi_cdblen  = CDB_GROUP0;
25798 		com->uscsi_timeout = 5;
25799 
25800 		/*
25801 		 * Reissue the last reserve command, this time without request
25802 		 * sense.  Assume that it is just a regular reserve command.
25803 		 */
25804 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25805 		    SD_PATH_STANDARD);
25806 	}
25807 
25808 	/* Return an error if still getting a reservation conflict. */
25809 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
25810 		rval = EACCES;
25811 	}
25812 
25813 	kmem_free(com, sizeof (*com));
25814 	return (rval);
25815 }
25816 
25817 
25818 #define	SD_NDUMP_RETRIES	12
25819 /*
25820  *	System Crash Dump routine
25821  */
25822 
25823 static int
25824 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
25825 {
25826 	int		instance;
25827 	int		partition;
25828 	int		i;
25829 	int		err;
25830 	struct sd_lun	*un;
25831 	struct scsi_pkt *wr_pktp;
25832 	struct buf	*wr_bp;
25833 	struct buf	wr_buf;
25834 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
25835 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
25836 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
25837 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
25838 	size_t		io_start_offset;
25839 	int		doing_rmw = FALSE;
25840 	int		rval;
25841 	ssize_t		dma_resid;
25842 	daddr_t		oblkno;
25843 	diskaddr_t	nblks = 0;
25844 	diskaddr_t	start_block;
25845 
25846 	instance = SDUNIT(dev);
25847 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
25848 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
25849 		return (ENXIO);
25850 	}
25851 
25852 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
25853 
25854 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
25855 
25856 	partition = SDPART(dev);
25857 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
25858 
25859 	if (!(NOT_DEVBSIZE(un))) {
25860 		int secmask = 0;
25861 		int blknomask = 0;
25862 
25863 		blknomask = (un->un_tgt_blocksize / DEV_BSIZE) - 1;
25864 		secmask = un->un_tgt_blocksize - 1;
25865 
25866 		if (blkno & blknomask) {
25867 			SD_TRACE(SD_LOG_DUMP, un,
25868 			    "sddump: dump start block not modulo %d\n",
25869 			    un->un_tgt_blocksize);
25870 			return (EINVAL);
25871 		}
25872 
25873 		if ((nblk * DEV_BSIZE) & secmask) {
25874 			SD_TRACE(SD_LOG_DUMP, un,
25875 			    "sddump: dump length not modulo %d\n",
25876 			    un->un_tgt_blocksize);
25877 			return (EINVAL);
25878 		}
25879 
25880 	}
25881 
25882 	/* Validate blocks to dump at against partition size. */
25883 
25884 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
25885 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
25886 
25887 	if (NOT_DEVBSIZE(un)) {
25888 		if ((blkno + nblk) > nblks) {
25889 			SD_TRACE(SD_LOG_DUMP, un,
25890 			    "sddump: dump range larger than partition: "
25891 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
25892 			    blkno, nblk, nblks);
25893 			return (EINVAL);
25894 		}
25895 	} else {
25896 		if (((blkno / (un->un_tgt_blocksize / DEV_BSIZE)) +
25897 		    (nblk / (un->un_tgt_blocksize / DEV_BSIZE))) > nblks) {
25898 			SD_TRACE(SD_LOG_DUMP, un,
25899 			    "sddump: dump range larger than partition: "
25900 			    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
25901 			    blkno, nblk, nblks);
25902 			return (EINVAL);
25903 		}
25904 	}
25905 
25906 	mutex_enter(&un->un_pm_mutex);
25907 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
25908 		struct scsi_pkt *start_pktp;
25909 
25910 		mutex_exit(&un->un_pm_mutex);
25911 
25912 		/*
25913 		 * use pm framework to power on HBA 1st
25914 		 */
25915 		(void) pm_raise_power(SD_DEVINFO(un), 0,
25916 		    SD_PM_STATE_ACTIVE(un));
25917 
25918 		/*
25919 		 * Dump no long uses sdpower to power on a device, it's
25920 		 * in-line here so it can be done in polled mode.
25921 		 */
25922 
25923 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
25924 
25925 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
25926 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
25927 
25928 		if (start_pktp == NULL) {
25929 			/* We were not given a SCSI packet, fail. */
25930 			return (EIO);
25931 		}
25932 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
25933 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
25934 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
25935 		start_pktp->pkt_flags = FLAG_NOINTR;
25936 
25937 		mutex_enter(SD_MUTEX(un));
25938 		SD_FILL_SCSI1_LUN(un, start_pktp);
25939 		mutex_exit(SD_MUTEX(un));
25940 		/*
25941 		 * Scsi_poll returns 0 (success) if the command completes and
25942 		 * the status block is STATUS_GOOD.
25943 		 */
25944 		if (sd_scsi_poll(un, start_pktp) != 0) {
25945 			scsi_destroy_pkt(start_pktp);
25946 			return (EIO);
25947 		}
25948 		scsi_destroy_pkt(start_pktp);
25949 		(void) sd_pm_state_change(un, SD_PM_STATE_ACTIVE(un),
25950 		    SD_PM_STATE_CHANGE);
25951 	} else {
25952 		mutex_exit(&un->un_pm_mutex);
25953 	}
25954 
25955 	mutex_enter(SD_MUTEX(un));
25956 	un->un_throttle = 0;
25957 
25958 	/*
25959 	 * The first time through, reset the specific target device.
25960 	 * However, when cpr calls sddump we know that sd is in a
25961 	 * a good state so no bus reset is required.
25962 	 * Clear sense data via Request Sense cmd.
25963 	 * In sddump we don't care about allow_bus_device_reset anymore
25964 	 */
25965 
25966 	if ((un->un_state != SD_STATE_SUSPENDED) &&
25967 	    (un->un_state != SD_STATE_DUMPING)) {
25968 
25969 		New_state(un, SD_STATE_DUMPING);
25970 
25971 		if (un->un_f_is_fibre == FALSE) {
25972 			mutex_exit(SD_MUTEX(un));
25973 			/*
25974 			 * Attempt a bus reset for parallel scsi.
25975 			 *
25976 			 * Note: A bus reset is required because on some host
25977 			 * systems (i.e. E420R) a bus device reset is
25978 			 * insufficient to reset the state of the target.
25979 			 *
25980 			 * Note: Don't issue the reset for fibre-channel,
25981 			 * because this tends to hang the bus (loop) for
25982 			 * too long while everyone is logging out and in
25983 			 * and the deadman timer for dumping will fire
25984 			 * before the dump is complete.
25985 			 */
25986 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
25987 				mutex_enter(SD_MUTEX(un));
25988 				Restore_state(un);
25989 				mutex_exit(SD_MUTEX(un));
25990 				return (EIO);
25991 			}
25992 
25993 			/* Delay to give the device some recovery time. */
25994 			drv_usecwait(10000);
25995 
25996 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
25997 				SD_INFO(SD_LOG_DUMP, un,
25998 				    "sddump: sd_send_polled_RQS failed\n");
25999 			}
26000 			mutex_enter(SD_MUTEX(un));
26001 		}
26002 	}
26003 
26004 	/*
26005 	 * Convert the partition-relative block number to a
26006 	 * disk physical block number.
26007 	 */
26008 	if (NOT_DEVBSIZE(un)) {
26009 		blkno += start_block;
26010 	} else {
26011 		blkno = blkno / (un->un_tgt_blocksize / DEV_BSIZE);
26012 		blkno += start_block;
26013 	}
26014 
26015 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
26016 
26017 
26018 	/*
26019 	 * Check if the device has a non-512 block size.
26020 	 */
26021 	wr_bp = NULL;
26022 	if (NOT_DEVBSIZE(un)) {
26023 		tgt_byte_offset = blkno * un->un_sys_blocksize;
26024 		tgt_byte_count = nblk * un->un_sys_blocksize;
26025 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
26026 		    (tgt_byte_count % un->un_tgt_blocksize)) {
26027 			doing_rmw = TRUE;
26028 			/*
26029 			 * Calculate the block number and number of block
26030 			 * in terms of the media block size.
26031 			 */
26032 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
26033 			tgt_nblk =
26034 			    ((tgt_byte_offset + tgt_byte_count +
26035 			    (un->un_tgt_blocksize - 1)) /
26036 			    un->un_tgt_blocksize) - tgt_blkno;
26037 
26038 			/*
26039 			 * Invoke the routine which is going to do read part
26040 			 * of read-modify-write.
26041 			 * Note that this routine returns a pointer to
26042 			 * a valid bp in wr_bp.
26043 			 */
26044 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
26045 			    &wr_bp);
26046 			if (err) {
26047 				mutex_exit(SD_MUTEX(un));
26048 				return (err);
26049 			}
26050 			/*
26051 			 * Offset is being calculated as -
26052 			 * (original block # * system block size) -
26053 			 * (new block # * target block size)
26054 			 */
26055 			io_start_offset =
26056 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
26057 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
26058 
26059 			ASSERT(io_start_offset < un->un_tgt_blocksize);
26060 			/*
26061 			 * Do the modify portion of read modify write.
26062 			 */
26063 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
26064 			    (size_t)nblk * un->un_sys_blocksize);
26065 		} else {
26066 			doing_rmw = FALSE;
26067 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
26068 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
26069 		}
26070 
26071 		/* Convert blkno and nblk to target blocks */
26072 		blkno = tgt_blkno;
26073 		nblk = tgt_nblk;
26074 	} else {
26075 		wr_bp = &wr_buf;
26076 		bzero(wr_bp, sizeof (struct buf));
26077 		wr_bp->b_flags		= B_BUSY;
26078 		wr_bp->b_un.b_addr	= addr;
26079 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
26080 		wr_bp->b_resid		= 0;
26081 	}
26082 
26083 	mutex_exit(SD_MUTEX(un));
26084 
26085 	/*
26086 	 * Obtain a SCSI packet for the write command.
26087 	 * It should be safe to call the allocator here without
26088 	 * worrying about being locked for DVMA mapping because
26089 	 * the address we're passed is already a DVMA mapping
26090 	 *
26091 	 * We are also not going to worry about semaphore ownership
26092 	 * in the dump buffer. Dumping is single threaded at present.
26093 	 */
26094 
26095 	wr_pktp = NULL;
26096 
26097 	dma_resid = wr_bp->b_bcount;
26098 	oblkno = blkno;
26099 
26100 	if (!(NOT_DEVBSIZE(un))) {
26101 		nblk = nblk / (un->un_tgt_blocksize / DEV_BSIZE);
26102 	}
26103 
26104 	while (dma_resid != 0) {
26105 
26106 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26107 		wr_bp->b_flags &= ~B_ERROR;
26108 
26109 		if (un->un_partial_dma_supported == 1) {
26110 			blkno = oblkno +
26111 			    ((wr_bp->b_bcount - dma_resid) /
26112 			    un->un_tgt_blocksize);
26113 			nblk = dma_resid / un->un_tgt_blocksize;
26114 
26115 			if (wr_pktp) {
26116 				/*
26117 				 * Partial DMA transfers after initial transfer
26118 				 */
26119 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
26120 				    blkno, nblk);
26121 			} else {
26122 				/* Initial transfer */
26123 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26124 				    un->un_pkt_flags, NULL_FUNC, NULL,
26125 				    blkno, nblk);
26126 			}
26127 		} else {
26128 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
26129 			    0, NULL_FUNC, NULL, blkno, nblk);
26130 		}
26131 
26132 		if (rval == 0) {
26133 			/* We were given a SCSI packet, continue. */
26134 			break;
26135 		}
26136 
26137 		if (i == 0) {
26138 			if (wr_bp->b_flags & B_ERROR) {
26139 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26140 				    "no resources for dumping; "
26141 				    "error code: 0x%x, retrying",
26142 				    geterror(wr_bp));
26143 			} else {
26144 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26145 				    "no resources for dumping; retrying");
26146 			}
26147 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
26148 			if (wr_bp->b_flags & B_ERROR) {
26149 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26150 				    "no resources for dumping; error code: "
26151 				    "0x%x, retrying\n", geterror(wr_bp));
26152 			}
26153 		} else {
26154 			if (wr_bp->b_flags & B_ERROR) {
26155 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26156 				    "no resources for dumping; "
26157 				    "error code: 0x%x, retries failed, "
26158 				    "giving up.\n", geterror(wr_bp));
26159 			} else {
26160 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26161 				    "no resources for dumping; "
26162 				    "retries failed, giving up.\n");
26163 			}
26164 			mutex_enter(SD_MUTEX(un));
26165 			Restore_state(un);
26166 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
26167 				mutex_exit(SD_MUTEX(un));
26168 				scsi_free_consistent_buf(wr_bp);
26169 			} else {
26170 				mutex_exit(SD_MUTEX(un));
26171 			}
26172 			return (EIO);
26173 		}
26174 		drv_usecwait(10000);
26175 	}
26176 
26177 	if (un->un_partial_dma_supported == 1) {
26178 		/*
26179 		 * save the resid from PARTIAL_DMA
26180 		 */
26181 		dma_resid = wr_pktp->pkt_resid;
26182 		if (dma_resid != 0)
26183 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
26184 		wr_pktp->pkt_resid = 0;
26185 	} else {
26186 		dma_resid = 0;
26187 	}
26188 
26189 	/* SunBug 1222170 */
26190 	wr_pktp->pkt_flags = FLAG_NOINTR;
26191 
26192 	err = EIO;
26193 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26194 
26195 		/*
26196 		 * Scsi_poll returns 0 (success) if the command completes and
26197 		 * the status block is STATUS_GOOD.  We should only check
26198 		 * errors if this condition is not true.  Even then we should
26199 		 * send our own request sense packet only if we have a check
26200 		 * condition and auto request sense has not been performed by
26201 		 * the hba.
26202 		 */
26203 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
26204 
26205 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
26206 		    (wr_pktp->pkt_resid == 0)) {
26207 			err = SD_SUCCESS;
26208 			break;
26209 		}
26210 
26211 		/*
26212 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
26213 		 */
26214 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
26215 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26216 			    "Error while dumping state...Device is gone\n");
26217 			break;
26218 		}
26219 
26220 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
26221 			SD_INFO(SD_LOG_DUMP, un,
26222 			    "sddump: write failed with CHECK, try # %d\n", i);
26223 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
26224 				(void) sd_send_polled_RQS(un);
26225 			}
26226 
26227 			continue;
26228 		}
26229 
26230 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
26231 			int reset_retval = 0;
26232 
26233 			SD_INFO(SD_LOG_DUMP, un,
26234 			    "sddump: write failed with BUSY, try # %d\n", i);
26235 
26236 			if (un->un_f_lun_reset_enabled == TRUE) {
26237 				reset_retval = scsi_reset(SD_ADDRESS(un),
26238 				    RESET_LUN);
26239 			}
26240 			if (reset_retval == 0) {
26241 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26242 			}
26243 			(void) sd_send_polled_RQS(un);
26244 
26245 		} else {
26246 			SD_INFO(SD_LOG_DUMP, un,
26247 			    "sddump: write failed with 0x%x, try # %d\n",
26248 			    SD_GET_PKT_STATUS(wr_pktp), i);
26249 			mutex_enter(SD_MUTEX(un));
26250 			sd_reset_target(un, wr_pktp);
26251 			mutex_exit(SD_MUTEX(un));
26252 		}
26253 
26254 		/*
26255 		 * If we are not getting anywhere with lun/target resets,
26256 		 * let's reset the bus.
26257 		 */
26258 		if (i == SD_NDUMP_RETRIES / 2) {
26259 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26260 			(void) sd_send_polled_RQS(un);
26261 		}
26262 	}
26263 	}
26264 
26265 	scsi_destroy_pkt(wr_pktp);
26266 	mutex_enter(SD_MUTEX(un));
26267 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
26268 		mutex_exit(SD_MUTEX(un));
26269 		scsi_free_consistent_buf(wr_bp);
26270 	} else {
26271 		mutex_exit(SD_MUTEX(un));
26272 	}
26273 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
26274 	return (err);
26275 }
26276 
26277 /*
26278  *    Function: sd_scsi_poll()
26279  *
26280  * Description: This is a wrapper for the scsi_poll call.
26281  *
26282  *   Arguments: sd_lun - The unit structure
26283  *              scsi_pkt - The scsi packet being sent to the device.
26284  *
26285  * Return Code: 0 - Command completed successfully with good status
26286  *             -1 - Command failed.  This could indicate a check condition
26287  *                  or other status value requiring recovery action.
26288  *
26289  * NOTE: This code is only called off sddump().
26290  */
26291 
26292 static int
26293 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
26294 {
26295 	int status;
26296 
26297 	ASSERT(un != NULL);
26298 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26299 	ASSERT(pktp != NULL);
26300 
26301 	status = SD_SUCCESS;
26302 
26303 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
26304 		pktp->pkt_flags |= un->un_tagflags;
26305 		pktp->pkt_flags &= ~FLAG_NODISCON;
26306 	}
26307 
26308 	status = sd_ddi_scsi_poll(pktp);
26309 	/*
26310 	 * Scsi_poll returns 0 (success) if the command completes and the
26311 	 * status block is STATUS_GOOD.  We should only check errors if this
26312 	 * condition is not true.  Even then we should send our own request
26313 	 * sense packet only if we have a check condition and auto
26314 	 * request sense has not been performed by the hba.
26315 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
26316 	 */
26317 	if ((status != SD_SUCCESS) &&
26318 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
26319 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
26320 	    (pktp->pkt_reason != CMD_DEV_GONE))
26321 		(void) sd_send_polled_RQS(un);
26322 
26323 	return (status);
26324 }
26325 
26326 /*
26327  *    Function: sd_send_polled_RQS()
26328  *
26329  * Description: This sends the request sense command to a device.
26330  *
26331  *   Arguments: sd_lun - The unit structure
26332  *
26333  * Return Code: 0 - Command completed successfully with good status
26334  *             -1 - Command failed.
26335  *
26336  */
26337 
26338 static int
26339 sd_send_polled_RQS(struct sd_lun *un)
26340 {
26341 	int	ret_val;
26342 	struct	scsi_pkt	*rqs_pktp;
26343 	struct	buf		*rqs_bp;
26344 
26345 	ASSERT(un != NULL);
26346 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26347 
26348 	ret_val = SD_SUCCESS;
26349 
26350 	rqs_pktp = un->un_rqs_pktp;
26351 	rqs_bp	 = un->un_rqs_bp;
26352 
26353 	mutex_enter(SD_MUTEX(un));
26354 
26355 	if (un->un_sense_isbusy) {
26356 		ret_val = SD_FAILURE;
26357 		mutex_exit(SD_MUTEX(un));
26358 		return (ret_val);
26359 	}
26360 
26361 	/*
26362 	 * If the request sense buffer (and packet) is not in use,
26363 	 * let's set the un_sense_isbusy and send our packet
26364 	 */
26365 	un->un_sense_isbusy = 1;
26366 	rqs_pktp->pkt_resid = 0;
26367 	rqs_pktp->pkt_reason = 0;
26368 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
26369 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
26370 
26371 	mutex_exit(SD_MUTEX(un));
26372 
26373 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
26374 	    " 0x%p\n", rqs_bp->b_un.b_addr);
26375 
26376 	/*
26377 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
26378 	 * axle - it has a call into us!
26379 	 */
26380 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
26381 		SD_INFO(SD_LOG_COMMON, un,
26382 		    "sd_send_polled_RQS: RQS failed\n");
26383 	}
26384 
26385 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
26386 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
26387 
26388 	mutex_enter(SD_MUTEX(un));
26389 	un->un_sense_isbusy = 0;
26390 	mutex_exit(SD_MUTEX(un));
26391 
26392 	return (ret_val);
26393 }
26394 
26395 /*
26396  * Defines needed for localized version of the scsi_poll routine.
26397  */
26398 #define	CSEC		10000			/* usecs */
26399 #define	SEC_TO_CSEC	(1000000 / CSEC)
26400 
26401 /*
26402  *    Function: sd_ddi_scsi_poll()
26403  *
26404  * Description: Localized version of the scsi_poll routine.  The purpose is to
26405  *		send a scsi_pkt to a device as a polled command.  This version
26406  *		is to ensure more robust handling of transport errors.
26407  *		Specifically this routine cures not ready, coming ready
26408  *		transition for power up and reset.
26409  *
26410  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
26411  *
26412  * Return Code: 0 - Command completed successfully with good status
26413  *             -1 - Command failed.
26414  *
26415  * NOTE: This code is almost identical to scsi_poll, however before 6668774 can
26416  * be fixed (removing this code), we need to determine how to handle the
26417  * KEY_UNIT_ATTENTION condition below in conditions not as limited as sddump().
26418  *
26419  * NOTE: This code is only called off sddump().
26420  */
26421 static int
26422 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
26423 {
26424 	int			rval = -1;
26425 	int			savef;
26426 	long			savet;
26427 	void			(*savec)();
26428 	int			timeout;
26429 	int			busy_count;
26430 	int			poll_delay;
26431 	int			rc;
26432 	uint8_t			*sensep;
26433 	struct scsi_arq_status	*arqstat;
26434 	extern int		do_polled_io;
26435 
26436 	ASSERT(pkt->pkt_scbp);
26437 
26438 	/*
26439 	 * save old flags..
26440 	 */
26441 	savef = pkt->pkt_flags;
26442 	savec = pkt->pkt_comp;
26443 	savet = pkt->pkt_time;
26444 
26445 	pkt->pkt_flags |= FLAG_NOINTR;
26446 
26447 	/*
26448 	 * XXX there is nothing in the SCSA spec that states that we should not
26449 	 * do a callback for polled cmds; however, removing this will break sd
26450 	 * and probably other target drivers
26451 	 */
26452 	pkt->pkt_comp = NULL;
26453 
26454 	/*
26455 	 * we don't like a polled command without timeout.
26456 	 * 60 seconds seems long enough.
26457 	 */
26458 	if (pkt->pkt_time == 0)
26459 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
26460 
26461 	/*
26462 	 * Send polled cmd.
26463 	 *
26464 	 * We do some error recovery for various errors.  Tran_busy,
26465 	 * queue full, and non-dispatched commands are retried every 10 msec.
26466 	 * as they are typically transient failures.  Busy status and Not
26467 	 * Ready are retried every second as this status takes a while to
26468 	 * change.
26469 	 */
26470 	timeout = pkt->pkt_time * SEC_TO_CSEC;
26471 
26472 	for (busy_count = 0; busy_count < timeout; busy_count++) {
26473 		/*
26474 		 * Initialize pkt status variables.
26475 		 */
26476 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
26477 
26478 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
26479 			if (rc != TRAN_BUSY) {
26480 				/* Transport failed - give up. */
26481 				break;
26482 			} else {
26483 				/* Transport busy - try again. */
26484 				poll_delay = 1 * CSEC;		/* 10 msec. */
26485 			}
26486 		} else {
26487 			/*
26488 			 * Transport accepted - check pkt status.
26489 			 */
26490 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
26491 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26492 			    (rc == STATUS_CHECK) &&
26493 			    (pkt->pkt_state & STATE_ARQ_DONE)) {
26494 				arqstat =
26495 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
26496 				sensep = (uint8_t *)&arqstat->sts_sensedata;
26497 			} else {
26498 				sensep = NULL;
26499 			}
26500 
26501 			if ((pkt->pkt_reason == CMD_CMPLT) &&
26502 			    (rc == STATUS_GOOD)) {
26503 				/* No error - we're done */
26504 				rval = 0;
26505 				break;
26506 
26507 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
26508 				/* Lost connection - give up */
26509 				break;
26510 
26511 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
26512 			    (pkt->pkt_state == 0)) {
26513 				/* Pkt not dispatched - try again. */
26514 				poll_delay = 1 * CSEC;		/* 10 msec. */
26515 
26516 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26517 			    (rc == STATUS_QFULL)) {
26518 				/* Queue full - try again. */
26519 				poll_delay = 1 * CSEC;		/* 10 msec. */
26520 
26521 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
26522 			    (rc == STATUS_BUSY)) {
26523 				/* Busy - try again. */
26524 				poll_delay = 100 * CSEC;	/* 1 sec. */
26525 				busy_count += (SEC_TO_CSEC - 1);
26526 
26527 			} else if ((sensep != NULL) &&
26528 			    (scsi_sense_key(sensep) == KEY_UNIT_ATTENTION)) {
26529 				/*
26530 				 * Unit Attention - try again.
26531 				 * Pretend it took 1 sec.
26532 				 * NOTE: 'continue' avoids poll_delay
26533 				 */
26534 				busy_count += (SEC_TO_CSEC - 1);
26535 				continue;
26536 
26537 			} else if ((sensep != NULL) &&
26538 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
26539 			    (scsi_sense_asc(sensep) == 0x04) &&
26540 			    (scsi_sense_ascq(sensep) == 0x01)) {
26541 				/*
26542 				 * Not ready -> ready - try again.
26543 				 * 04h/01h: LUN IS IN PROCESS OF BECOMING READY
26544 				 * ...same as STATUS_BUSY
26545 				 */
26546 				poll_delay = 100 * CSEC;	/* 1 sec. */
26547 				busy_count += (SEC_TO_CSEC - 1);
26548 
26549 			} else {
26550 				/* BAD status - give up. */
26551 				break;
26552 			}
26553 		}
26554 
26555 		if (((curthread->t_flag & T_INTR_THREAD) == 0) &&
26556 		    !do_polled_io) {
26557 			delay(drv_usectohz(poll_delay));
26558 		} else {
26559 			/* we busy wait during cpr_dump or interrupt threads */
26560 			drv_usecwait(poll_delay);
26561 		}
26562 	}
26563 
26564 	pkt->pkt_flags = savef;
26565 	pkt->pkt_comp = savec;
26566 	pkt->pkt_time = savet;
26567 
26568 	/* return on error */
26569 	if (rval)
26570 		return (rval);
26571 
26572 	/*
26573 	 * This is not a performance critical code path.
26574 	 *
26575 	 * As an accommodation for scsi_poll callers, to avoid ddi_dma_sync()
26576 	 * issues associated with looking at DMA memory prior to
26577 	 * scsi_pkt_destroy(), we scsi_sync_pkt() prior to return.
26578 	 */
26579 	scsi_sync_pkt(pkt);
26580 	return (0);
26581 }
26582 
26583 
26584 
26585 /*
26586  *    Function: sd_persistent_reservation_in_read_keys
26587  *
26588  * Description: This routine is the driver entry point for handling CD-ROM
26589  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
26590  *		by sending the SCSI-3 PRIN commands to the device.
26591  *		Processes the read keys command response by copying the
26592  *		reservation key information into the user provided buffer.
26593  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
26594  *
26595  *   Arguments: un   -  Pointer to soft state struct for the target.
26596  *		usrp -	user provided pointer to multihost Persistent In Read
26597  *			Keys structure (mhioc_inkeys_t)
26598  *		flag -	this argument is a pass through to ddi_copyxxx()
26599  *			directly from the mode argument of ioctl().
26600  *
26601  * Return Code: 0   - Success
26602  *		EACCES
26603  *		ENOTSUP
26604  *		errno return code from sd_send_scsi_cmd()
26605  *
26606  *     Context: Can sleep. Does not return until command is completed.
26607  */
26608 
26609 static int
26610 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
26611     mhioc_inkeys_t *usrp, int flag)
26612 {
26613 #ifdef _MULTI_DATAMODEL
26614 	struct mhioc_key_list32	li32;
26615 #endif
26616 	sd_prin_readkeys_t	*in;
26617 	mhioc_inkeys_t		*ptr;
26618 	mhioc_key_list_t	li;
26619 	uchar_t			*data_bufp = NULL;
26620 	int			data_len = 0;
26621 	int			rval = 0;
26622 	size_t			copysz = 0;
26623 	sd_ssc_t		*ssc;
26624 
26625 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
26626 		return (EINVAL);
26627 	}
26628 	bzero(&li, sizeof (mhioc_key_list_t));
26629 
26630 	ssc = sd_ssc_init(un);
26631 
26632 	/*
26633 	 * Get the listsize from user
26634 	 */
26635 #ifdef _MULTI_DATAMODEL
26636 	switch (ddi_model_convert_from(flag & FMODELS)) {
26637 	case DDI_MODEL_ILP32:
26638 		copysz = sizeof (struct mhioc_key_list32);
26639 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
26640 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26641 			    "sd_persistent_reservation_in_read_keys: "
26642 			    "failed ddi_copyin: mhioc_key_list32_t\n");
26643 			rval = EFAULT;
26644 			goto done;
26645 		}
26646 		li.listsize = li32.listsize;
26647 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
26648 		break;
26649 
26650 	case DDI_MODEL_NONE:
26651 		copysz = sizeof (mhioc_key_list_t);
26652 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26653 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26654 			    "sd_persistent_reservation_in_read_keys: "
26655 			    "failed ddi_copyin: mhioc_key_list_t\n");
26656 			rval = EFAULT;
26657 			goto done;
26658 		}
26659 		break;
26660 	}
26661 
26662 #else /* ! _MULTI_DATAMODEL */
26663 	copysz = sizeof (mhioc_key_list_t);
26664 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
26665 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26666 		    "sd_persistent_reservation_in_read_keys: "
26667 		    "failed ddi_copyin: mhioc_key_list_t\n");
26668 		rval = EFAULT;
26669 		goto done;
26670 	}
26671 #endif
26672 
26673 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
26674 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
26675 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26676 
26677 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_KEYS,
26678 	    data_len, data_bufp);
26679 	if (rval != 0) {
26680 		if (rval == EIO)
26681 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
26682 		else
26683 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
26684 		goto done;
26685 	}
26686 	in = (sd_prin_readkeys_t *)data_bufp;
26687 	ptr->generation = BE_32(in->generation);
26688 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
26689 
26690 	/*
26691 	 * Return the min(listsize, listlen) keys
26692 	 */
26693 #ifdef _MULTI_DATAMODEL
26694 
26695 	switch (ddi_model_convert_from(flag & FMODELS)) {
26696 	case DDI_MODEL_ILP32:
26697 		li32.listlen = li.listlen;
26698 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
26699 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26700 			    "sd_persistent_reservation_in_read_keys: "
26701 			    "failed ddi_copyout: mhioc_key_list32_t\n");
26702 			rval = EFAULT;
26703 			goto done;
26704 		}
26705 		break;
26706 
26707 	case DDI_MODEL_NONE:
26708 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26709 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26710 			    "sd_persistent_reservation_in_read_keys: "
26711 			    "failed ddi_copyout: mhioc_key_list_t\n");
26712 			rval = EFAULT;
26713 			goto done;
26714 		}
26715 		break;
26716 	}
26717 
26718 #else /* ! _MULTI_DATAMODEL */
26719 
26720 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
26721 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26722 		    "sd_persistent_reservation_in_read_keys: "
26723 		    "failed ddi_copyout: mhioc_key_list_t\n");
26724 		rval = EFAULT;
26725 		goto done;
26726 	}
26727 
26728 #endif /* _MULTI_DATAMODEL */
26729 
26730 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
26731 	    li.listsize * MHIOC_RESV_KEY_SIZE);
26732 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
26733 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26734 		    "sd_persistent_reservation_in_read_keys: "
26735 		    "failed ddi_copyout: keylist\n");
26736 		rval = EFAULT;
26737 	}
26738 done:
26739 	sd_ssc_fini(ssc);
26740 	kmem_free(data_bufp, data_len);
26741 	return (rval);
26742 }
26743 
26744 
26745 /*
26746  *    Function: sd_persistent_reservation_in_read_resv
26747  *
26748  * Description: This routine is the driver entry point for handling CD-ROM
26749  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
26750  *		by sending the SCSI-3 PRIN commands to the device.
26751  *		Process the read persistent reservations command response by
26752  *		copying the reservation information into the user provided
26753  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
26754  *
26755  *   Arguments: un   -  Pointer to soft state struct for the target.
26756  *		usrp -	user provided pointer to multihost Persistent In Read
26757  *			Keys structure (mhioc_inkeys_t)
26758  *		flag -	this argument is a pass through to ddi_copyxxx()
26759  *			directly from the mode argument of ioctl().
26760  *
26761  * Return Code: 0   - Success
26762  *		EACCES
26763  *		ENOTSUP
26764  *		errno return code from sd_send_scsi_cmd()
26765  *
26766  *     Context: Can sleep. Does not return until command is completed.
26767  */
26768 
26769 static int
26770 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
26771     mhioc_inresvs_t *usrp, int flag)
26772 {
26773 #ifdef _MULTI_DATAMODEL
26774 	struct mhioc_resv_desc_list32 resvlist32;
26775 #endif
26776 	sd_prin_readresv_t	*in;
26777 	mhioc_inresvs_t		*ptr;
26778 	sd_readresv_desc_t	*readresv_ptr;
26779 	mhioc_resv_desc_list_t	resvlist;
26780 	mhioc_resv_desc_t	resvdesc;
26781 	uchar_t			*data_bufp = NULL;
26782 	int			data_len;
26783 	int			rval = 0;
26784 	int			i;
26785 	size_t			copysz = 0;
26786 	mhioc_resv_desc_t	*bufp;
26787 	sd_ssc_t		*ssc;
26788 
26789 	if ((ptr = usrp) == NULL) {
26790 		return (EINVAL);
26791 	}
26792 
26793 	ssc = sd_ssc_init(un);
26794 
26795 	/*
26796 	 * Get the listsize from user
26797 	 */
26798 #ifdef _MULTI_DATAMODEL
26799 	switch (ddi_model_convert_from(flag & FMODELS)) {
26800 	case DDI_MODEL_ILP32:
26801 		copysz = sizeof (struct mhioc_resv_desc_list32);
26802 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
26803 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26804 			    "sd_persistent_reservation_in_read_resv: "
26805 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26806 			rval = EFAULT;
26807 			goto done;
26808 		}
26809 		resvlist.listsize = resvlist32.listsize;
26810 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
26811 		break;
26812 
26813 	case DDI_MODEL_NONE:
26814 		copysz = sizeof (mhioc_resv_desc_list_t);
26815 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26816 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26817 			    "sd_persistent_reservation_in_read_resv: "
26818 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26819 			rval = EFAULT;
26820 			goto done;
26821 		}
26822 		break;
26823 	}
26824 #else /* ! _MULTI_DATAMODEL */
26825 	copysz = sizeof (mhioc_resv_desc_list_t);
26826 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
26827 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26828 		    "sd_persistent_reservation_in_read_resv: "
26829 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
26830 		rval = EFAULT;
26831 		goto done;
26832 	}
26833 #endif /* ! _MULTI_DATAMODEL */
26834 
26835 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
26836 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
26837 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
26838 
26839 	rval = sd_send_scsi_PERSISTENT_RESERVE_IN(ssc, SD_READ_RESV,
26840 	    data_len, data_bufp);
26841 	if (rval != 0) {
26842 		if (rval == EIO)
26843 			sd_ssc_assessment(ssc, SD_FMT_IGNORE_COMPROMISE);
26844 		else
26845 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
26846 		goto done;
26847 	}
26848 	in = (sd_prin_readresv_t *)data_bufp;
26849 	ptr->generation = BE_32(in->generation);
26850 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
26851 
26852 	/*
26853 	 * Return the min(listsize, listlen( keys
26854 	 */
26855 #ifdef _MULTI_DATAMODEL
26856 
26857 	switch (ddi_model_convert_from(flag & FMODELS)) {
26858 	case DDI_MODEL_ILP32:
26859 		resvlist32.listlen = resvlist.listlen;
26860 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
26861 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26862 			    "sd_persistent_reservation_in_read_resv: "
26863 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26864 			rval = EFAULT;
26865 			goto done;
26866 		}
26867 		break;
26868 
26869 	case DDI_MODEL_NONE:
26870 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26871 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26872 			    "sd_persistent_reservation_in_read_resv: "
26873 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26874 			rval = EFAULT;
26875 			goto done;
26876 		}
26877 		break;
26878 	}
26879 
26880 #else /* ! _MULTI_DATAMODEL */
26881 
26882 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
26883 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
26884 		    "sd_persistent_reservation_in_read_resv: "
26885 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
26886 		rval = EFAULT;
26887 		goto done;
26888 	}
26889 
26890 #endif /* ! _MULTI_DATAMODEL */
26891 
26892 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
26893 	bufp = resvlist.list;
26894 	copysz = sizeof (mhioc_resv_desc_t);
26895 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
26896 	    i++, readresv_ptr++, bufp++) {
26897 
26898 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
26899 		    MHIOC_RESV_KEY_SIZE);
26900 		resvdesc.type  = readresv_ptr->type;
26901 		resvdesc.scope = readresv_ptr->scope;
26902 		resvdesc.scope_specific_addr =
26903 		    BE_32(readresv_ptr->scope_specific_addr);
26904 
26905 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
26906 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
26907 			    "sd_persistent_reservation_in_read_resv: "
26908 			    "failed ddi_copyout: resvlist\n");
26909 			rval = EFAULT;
26910 			goto done;
26911 		}
26912 	}
26913 done:
26914 	sd_ssc_fini(ssc);
26915 	/* only if data_bufp is allocated, we need to free it */
26916 	if (data_bufp) {
26917 		kmem_free(data_bufp, data_len);
26918 	}
26919 	return (rval);
26920 }
26921 
26922 
26923 /*
26924  *    Function: sr_change_blkmode()
26925  *
26926  * Description: This routine is the driver entry point for handling CD-ROM
26927  *		block mode ioctl requests. Support for returning and changing
26928  *		the current block size in use by the device is implemented. The
26929  *		LBA size is changed via a MODE SELECT Block Descriptor.
26930  *
26931  *		This routine issues a mode sense with an allocation length of
26932  *		12 bytes for the mode page header and a single block descriptor.
26933  *
26934  *   Arguments: dev - the device 'dev_t'
26935  *		cmd - the request type; one of CDROMGBLKMODE (get) or
26936  *		      CDROMSBLKMODE (set)
26937  *		data - current block size or requested block size
26938  *		flag - this argument is a pass through to ddi_copyxxx() directly
26939  *		       from the mode argument of ioctl().
26940  *
26941  * Return Code: the code returned by sd_send_scsi_cmd()
26942  *		EINVAL if invalid arguments are provided
26943  *		EFAULT if ddi_copyxxx() fails
26944  *		ENXIO if fail ddi_get_soft_state
26945  *		EIO if invalid mode sense block descriptor length
26946  *
26947  */
26948 
26949 static int
26950 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
26951 {
26952 	struct sd_lun			*un = NULL;
26953 	struct mode_header		*sense_mhp, *select_mhp;
26954 	struct block_descriptor		*sense_desc, *select_desc;
26955 	int				current_bsize;
26956 	int				rval = EINVAL;
26957 	uchar_t				*sense = NULL;
26958 	uchar_t				*select = NULL;
26959 	sd_ssc_t			*ssc;
26960 
26961 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
26962 
26963 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26964 		return (ENXIO);
26965 	}
26966 
26967 	/*
26968 	 * The block length is changed via the Mode Select block descriptor, the
26969 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
26970 	 * required as part of this routine. Therefore the mode sense allocation
26971 	 * length is specified to be the length of a mode page header and a
26972 	 * block descriptor.
26973 	 */
26974 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
26975 
26976 	ssc = sd_ssc_init(un);
26977 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
26978 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD);
26979 	sd_ssc_fini(ssc);
26980 	if (rval != 0) {
26981 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26982 		    "sr_change_blkmode: Mode Sense Failed\n");
26983 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26984 		return (rval);
26985 	}
26986 
26987 	/* Check the block descriptor len to handle only 1 block descriptor */
26988 	sense_mhp = (struct mode_header *)sense;
26989 	if ((sense_mhp->bdesc_length == 0) ||
26990 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
26991 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26992 		    "sr_change_blkmode: Mode Sense returned invalid block"
26993 		    " descriptor length\n");
26994 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
26995 		return (EIO);
26996 	}
26997 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
26998 	current_bsize = ((sense_desc->blksize_hi << 16) |
26999 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
27000 
27001 	/* Process command */
27002 	switch (cmd) {
27003 	case CDROMGBLKMODE:
27004 		/* Return the block size obtained during the mode sense */
27005 		if (ddi_copyout(&current_bsize, (void *)data,
27006 		    sizeof (int), flag) != 0)
27007 			rval = EFAULT;
27008 		break;
27009 	case CDROMSBLKMODE:
27010 		/* Validate the requested block size */
27011 		switch (data) {
27012 		case CDROM_BLK_512:
27013 		case CDROM_BLK_1024:
27014 		case CDROM_BLK_2048:
27015 		case CDROM_BLK_2056:
27016 		case CDROM_BLK_2336:
27017 		case CDROM_BLK_2340:
27018 		case CDROM_BLK_2352:
27019 		case CDROM_BLK_2368:
27020 		case CDROM_BLK_2448:
27021 		case CDROM_BLK_2646:
27022 		case CDROM_BLK_2647:
27023 			break;
27024 		default:
27025 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27026 			    "sr_change_blkmode: "
27027 			    "Block Size '%ld' Not Supported\n", data);
27028 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27029 			return (EINVAL);
27030 		}
27031 
27032 		/*
27033 		 * The current block size matches the requested block size so
27034 		 * there is no need to send the mode select to change the size
27035 		 */
27036 		if (current_bsize == data) {
27037 			break;
27038 		}
27039 
27040 		/* Build the select data for the requested block size */
27041 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
27042 		select_mhp = (struct mode_header *)select;
27043 		select_desc =
27044 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
27045 		/*
27046 		 * The LBA size is changed via the block descriptor, so the
27047 		 * descriptor is built according to the user data
27048 		 */
27049 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
27050 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
27051 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
27052 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
27053 
27054 		/* Send the mode select for the requested block size */
27055 		ssc = sd_ssc_init(un);
27056 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
27057 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
27058 		    SD_PATH_STANDARD);
27059 		sd_ssc_fini(ssc);
27060 		if (rval != 0) {
27061 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27062 			    "sr_change_blkmode: Mode Select Failed\n");
27063 			/*
27064 			 * The mode select failed for the requested block size,
27065 			 * so reset the data for the original block size and
27066 			 * send it to the target. The error is indicated by the
27067 			 * return value for the failed mode select.
27068 			 */
27069 			select_desc->blksize_hi  = sense_desc->blksize_hi;
27070 			select_desc->blksize_mid = sense_desc->blksize_mid;
27071 			select_desc->blksize_lo  = sense_desc->blksize_lo;
27072 			ssc = sd_ssc_init(un);
27073 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0,
27074 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
27075 			    SD_PATH_STANDARD);
27076 			sd_ssc_fini(ssc);
27077 		} else {
27078 			ASSERT(!mutex_owned(SD_MUTEX(un)));
27079 			mutex_enter(SD_MUTEX(un));
27080 			sd_update_block_info(un, (uint32_t)data, 0);
27081 			mutex_exit(SD_MUTEX(un));
27082 		}
27083 		break;
27084 	default:
27085 		/* should not reach here, but check anyway */
27086 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27087 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
27088 		rval = EINVAL;
27089 		break;
27090 	}
27091 
27092 	if (select) {
27093 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
27094 	}
27095 	if (sense) {
27096 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
27097 	}
27098 	return (rval);
27099 }
27100 
27101 
27102 /*
27103  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
27104  * implement driver support for getting and setting the CD speed. The command
27105  * set used will be based on the device type. If the device has not been
27106  * identified as MMC the Toshiba vendor specific mode page will be used. If
27107  * the device is MMC but does not support the Real Time Streaming feature
27108  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
27109  * be used to read the speed.
27110  */
27111 
27112 /*
27113  *    Function: sr_change_speed()
27114  *
27115  * Description: This routine is the driver entry point for handling CD-ROM
27116  *		drive speed ioctl requests for devices supporting the Toshiba
27117  *		vendor specific drive speed mode page. Support for returning
27118  *		and changing the current drive speed in use by the device is
27119  *		implemented.
27120  *
27121  *   Arguments: dev - the device 'dev_t'
27122  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
27123  *		      CDROMSDRVSPEED (set)
27124  *		data - current drive speed or requested drive speed
27125  *		flag - this argument is a pass through to ddi_copyxxx() directly
27126  *		       from the mode argument of ioctl().
27127  *
27128  * Return Code: the code returned by sd_send_scsi_cmd()
27129  *		EINVAL if invalid arguments are provided
27130  *		EFAULT if ddi_copyxxx() fails
27131  *		ENXIO if fail ddi_get_soft_state
27132  *		EIO if invalid mode sense block descriptor length
27133  */
27134 
27135 static int
27136 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27137 {
27138 	struct sd_lun			*un = NULL;
27139 	struct mode_header		*sense_mhp, *select_mhp;
27140 	struct mode_speed		*sense_page, *select_page;
27141 	int				current_speed;
27142 	int				rval = EINVAL;
27143 	int				bd_len;
27144 	uchar_t				*sense = NULL;
27145 	uchar_t				*select = NULL;
27146 	sd_ssc_t			*ssc;
27147 
27148 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27149 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27150 		return (ENXIO);
27151 	}
27152 
27153 	/*
27154 	 * Note: The drive speed is being modified here according to a Toshiba
27155 	 * vendor specific mode page (0x31).
27156 	 */
27157 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27158 
27159 	ssc = sd_ssc_init(un);
27160 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
27161 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
27162 	    SD_PATH_STANDARD);
27163 	sd_ssc_fini(ssc);
27164 	if (rval != 0) {
27165 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27166 		    "sr_change_speed: Mode Sense Failed\n");
27167 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27168 		return (rval);
27169 	}
27170 	sense_mhp  = (struct mode_header *)sense;
27171 
27172 	/* Check the block descriptor len to handle only 1 block descriptor */
27173 	bd_len = sense_mhp->bdesc_length;
27174 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27175 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27176 		    "sr_change_speed: Mode Sense returned invalid block "
27177 		    "descriptor length\n");
27178 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27179 		return (EIO);
27180 	}
27181 
27182 	sense_page = (struct mode_speed *)
27183 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
27184 	current_speed = sense_page->speed;
27185 
27186 	/* Process command */
27187 	switch (cmd) {
27188 	case CDROMGDRVSPEED:
27189 		/* Return the drive speed obtained during the mode sense */
27190 		if (current_speed == 0x2) {
27191 			current_speed = CDROM_TWELVE_SPEED;
27192 		}
27193 		if (ddi_copyout(&current_speed, (void *)data,
27194 		    sizeof (int), flag) != 0) {
27195 			rval = EFAULT;
27196 		}
27197 		break;
27198 	case CDROMSDRVSPEED:
27199 		/* Validate the requested drive speed */
27200 		switch ((uchar_t)data) {
27201 		case CDROM_TWELVE_SPEED:
27202 			data = 0x2;
27203 			/*FALLTHROUGH*/
27204 		case CDROM_NORMAL_SPEED:
27205 		case CDROM_DOUBLE_SPEED:
27206 		case CDROM_QUAD_SPEED:
27207 		case CDROM_MAXIMUM_SPEED:
27208 			break;
27209 		default:
27210 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27211 			    "sr_change_speed: "
27212 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
27213 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27214 			return (EINVAL);
27215 		}
27216 
27217 		/*
27218 		 * The current drive speed matches the requested drive speed so
27219 		 * there is no need to send the mode select to change the speed
27220 		 */
27221 		if (current_speed == data) {
27222 			break;
27223 		}
27224 
27225 		/* Build the select data for the requested drive speed */
27226 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
27227 		select_mhp = (struct mode_header *)select;
27228 		select_mhp->bdesc_length = 0;
27229 		select_page =
27230 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27231 		select_page =
27232 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
27233 		select_page->mode_page.code = CDROM_MODE_SPEED;
27234 		select_page->mode_page.length = 2;
27235 		select_page->speed = (uchar_t)data;
27236 
27237 		/* Send the mode select for the requested block size */
27238 		ssc = sd_ssc_init(un);
27239 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27240 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27241 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27242 		sd_ssc_fini(ssc);
27243 		if (rval != 0) {
27244 			/*
27245 			 * The mode select failed for the requested drive speed,
27246 			 * so reset the data for the original drive speed and
27247 			 * send it to the target. The error is indicated by the
27248 			 * return value for the failed mode select.
27249 			 */
27250 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27251 			    "sr_drive_speed: Mode Select Failed\n");
27252 			select_page->speed = sense_page->speed;
27253 			ssc = sd_ssc_init(un);
27254 			(void) sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
27255 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
27256 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
27257 			sd_ssc_fini(ssc);
27258 		}
27259 		break;
27260 	default:
27261 		/* should not reach here, but check anyway */
27262 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27263 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
27264 		rval = EINVAL;
27265 		break;
27266 	}
27267 
27268 	if (select) {
27269 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
27270 	}
27271 	if (sense) {
27272 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
27273 	}
27274 
27275 	return (rval);
27276 }
27277 
27278 
27279 /*
27280  *    Function: sr_atapi_change_speed()
27281  *
27282  * Description: This routine is the driver entry point for handling CD-ROM
27283  *		drive speed ioctl requests for MMC devices that do not support
27284  *		the Real Time Streaming feature (0x107).
27285  *
27286  *		Note: This routine will use the SET SPEED command which may not
27287  *		be supported by all devices.
27288  *
27289  *   Arguments: dev- the device 'dev_t'
27290  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
27291  *		     CDROMSDRVSPEED (set)
27292  *		data- current drive speed or requested drive speed
27293  *		flag- this argument is a pass through to ddi_copyxxx() directly
27294  *		      from the mode argument of ioctl().
27295  *
27296  * Return Code: the code returned by sd_send_scsi_cmd()
27297  *		EINVAL if invalid arguments are provided
27298  *		EFAULT if ddi_copyxxx() fails
27299  *		ENXIO if fail ddi_get_soft_state
27300  *		EIO if invalid mode sense block descriptor length
27301  */
27302 
27303 static int
27304 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
27305 {
27306 	struct sd_lun			*un;
27307 	struct uscsi_cmd		*com = NULL;
27308 	struct mode_header_grp2		*sense_mhp;
27309 	uchar_t				*sense_page;
27310 	uchar_t				*sense = NULL;
27311 	char				cdb[CDB_GROUP5];
27312 	int				bd_len;
27313 	int				current_speed = 0;
27314 	int				max_speed = 0;
27315 	int				rval;
27316 	sd_ssc_t			*ssc;
27317 
27318 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
27319 
27320 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27321 		return (ENXIO);
27322 	}
27323 
27324 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
27325 
27326 	ssc = sd_ssc_init(un);
27327 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
27328 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
27329 	    SD_PATH_STANDARD);
27330 	sd_ssc_fini(ssc);
27331 	if (rval != 0) {
27332 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27333 		    "sr_atapi_change_speed: Mode Sense Failed\n");
27334 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27335 		return (rval);
27336 	}
27337 
27338 	/* Check the block descriptor len to handle only 1 block descriptor */
27339 	sense_mhp = (struct mode_header_grp2 *)sense;
27340 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
27341 	if (bd_len > MODE_BLK_DESC_LENGTH) {
27342 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27343 		    "sr_atapi_change_speed: Mode Sense returned invalid "
27344 		    "block descriptor length\n");
27345 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27346 		return (EIO);
27347 	}
27348 
27349 	/* Calculate the current and maximum drive speeds */
27350 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
27351 	current_speed = (sense_page[14] << 8) | sense_page[15];
27352 	max_speed = (sense_page[8] << 8) | sense_page[9];
27353 
27354 	/* Process the command */
27355 	switch (cmd) {
27356 	case CDROMGDRVSPEED:
27357 		current_speed /= SD_SPEED_1X;
27358 		if (ddi_copyout(&current_speed, (void *)data,
27359 		    sizeof (int), flag) != 0)
27360 			rval = EFAULT;
27361 		break;
27362 	case CDROMSDRVSPEED:
27363 		/* Convert the speed code to KB/sec */
27364 		switch ((uchar_t)data) {
27365 		case CDROM_NORMAL_SPEED:
27366 			current_speed = SD_SPEED_1X;
27367 			break;
27368 		case CDROM_DOUBLE_SPEED:
27369 			current_speed = 2 * SD_SPEED_1X;
27370 			break;
27371 		case CDROM_QUAD_SPEED:
27372 			current_speed = 4 * SD_SPEED_1X;
27373 			break;
27374 		case CDROM_TWELVE_SPEED:
27375 			current_speed = 12 * SD_SPEED_1X;
27376 			break;
27377 		case CDROM_MAXIMUM_SPEED:
27378 			current_speed = 0xffff;
27379 			break;
27380 		default:
27381 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27382 			    "sr_atapi_change_speed: invalid drive speed %d\n",
27383 			    (uchar_t)data);
27384 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27385 			return (EINVAL);
27386 		}
27387 
27388 		/* Check the request against the drive's max speed. */
27389 		if (current_speed != 0xffff) {
27390 			if (current_speed > max_speed) {
27391 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27392 				return (EINVAL);
27393 			}
27394 		}
27395 
27396 		/*
27397 		 * Build and send the SET SPEED command
27398 		 *
27399 		 * Note: The SET SPEED (0xBB) command used in this routine is
27400 		 * obsolete per the SCSI MMC spec but still supported in the
27401 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27402 		 * therefore the command is still implemented in this routine.
27403 		 */
27404 		bzero(cdb, sizeof (cdb));
27405 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
27406 		cdb[2] = (uchar_t)(current_speed >> 8);
27407 		cdb[3] = (uchar_t)current_speed;
27408 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27409 		com->uscsi_cdb	   = (caddr_t)cdb;
27410 		com->uscsi_cdblen  = CDB_GROUP5;
27411 		com->uscsi_bufaddr = NULL;
27412 		com->uscsi_buflen  = 0;
27413 		com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT;
27414 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
27415 		break;
27416 	default:
27417 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27418 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
27419 		rval = EINVAL;
27420 	}
27421 
27422 	if (sense) {
27423 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
27424 	}
27425 	if (com) {
27426 		kmem_free(com, sizeof (*com));
27427 	}
27428 	return (rval);
27429 }
27430 
27431 
27432 /*
27433  *    Function: sr_pause_resume()
27434  *
27435  * Description: This routine is the driver entry point for handling CD-ROM
27436  *		pause/resume ioctl requests. This only affects the audio play
27437  *		operation.
27438  *
27439  *   Arguments: dev - the device 'dev_t'
27440  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
27441  *		      for setting the resume bit of the cdb.
27442  *
27443  * Return Code: the code returned by sd_send_scsi_cmd()
27444  *		EINVAL if invalid mode specified
27445  *
27446  */
27447 
27448 static int
27449 sr_pause_resume(dev_t dev, int cmd)
27450 {
27451 	struct sd_lun		*un;
27452 	struct uscsi_cmd	*com;
27453 	char			cdb[CDB_GROUP1];
27454 	int			rval;
27455 
27456 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27457 		return (ENXIO);
27458 	}
27459 
27460 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27461 	bzero(cdb, CDB_GROUP1);
27462 	cdb[0] = SCMD_PAUSE_RESUME;
27463 	switch (cmd) {
27464 	case CDROMRESUME:
27465 		cdb[8] = 1;
27466 		break;
27467 	case CDROMPAUSE:
27468 		cdb[8] = 0;
27469 		break;
27470 	default:
27471 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
27472 		    " Command '%x' Not Supported\n", cmd);
27473 		rval = EINVAL;
27474 		goto done;
27475 	}
27476 
27477 	com->uscsi_cdb    = cdb;
27478 	com->uscsi_cdblen = CDB_GROUP1;
27479 	com->uscsi_flags  = USCSI_DIAGNOSE | USCSI_SILENT;
27480 
27481 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27482 	    SD_PATH_STANDARD);
27483 
27484 done:
27485 	kmem_free(com, sizeof (*com));
27486 	return (rval);
27487 }
27488 
27489 
27490 /*
27491  *    Function: sr_play_msf()
27492  *
27493  * Description: This routine is the driver entry point for handling CD-ROM
27494  *		ioctl requests to output the audio signals at the specified
27495  *		starting address and continue the audio play until the specified
27496  *		ending address (CDROMPLAYMSF) The address is in Minute Second
27497  *		Frame (MSF) format.
27498  *
27499  *   Arguments: dev	- the device 'dev_t'
27500  *		data	- pointer to user provided audio msf structure,
27501  *		          specifying start/end addresses.
27502  *		flag	- this argument is a pass through to ddi_copyxxx()
27503  *		          directly from the mode argument of ioctl().
27504  *
27505  * Return Code: the code returned by sd_send_scsi_cmd()
27506  *		EFAULT if ddi_copyxxx() fails
27507  *		ENXIO if fail ddi_get_soft_state
27508  *		EINVAL if data pointer is NULL
27509  */
27510 
27511 static int
27512 sr_play_msf(dev_t dev, caddr_t data, int flag)
27513 {
27514 	struct sd_lun		*un;
27515 	struct uscsi_cmd	*com;
27516 	struct cdrom_msf	msf_struct;
27517 	struct cdrom_msf	*msf = &msf_struct;
27518 	char			cdb[CDB_GROUP1];
27519 	int			rval;
27520 
27521 	if (data == NULL) {
27522 		return (EINVAL);
27523 	}
27524 
27525 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27526 		return (ENXIO);
27527 	}
27528 
27529 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
27530 		return (EFAULT);
27531 	}
27532 
27533 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27534 	bzero(cdb, CDB_GROUP1);
27535 	cdb[0] = SCMD_PLAYAUDIO_MSF;
27536 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
27537 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
27538 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
27539 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
27540 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
27541 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
27542 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
27543 	} else {
27544 		cdb[3] = msf->cdmsf_min0;
27545 		cdb[4] = msf->cdmsf_sec0;
27546 		cdb[5] = msf->cdmsf_frame0;
27547 		cdb[6] = msf->cdmsf_min1;
27548 		cdb[7] = msf->cdmsf_sec1;
27549 		cdb[8] = msf->cdmsf_frame1;
27550 	}
27551 	com->uscsi_cdb    = cdb;
27552 	com->uscsi_cdblen = CDB_GROUP1;
27553 	com->uscsi_flags  = USCSI_DIAGNOSE | USCSI_SILENT;
27554 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27555 	    SD_PATH_STANDARD);
27556 	kmem_free(com, sizeof (*com));
27557 	return (rval);
27558 }
27559 
27560 
27561 /*
27562  *    Function: sr_play_trkind()
27563  *
27564  * Description: This routine is the driver entry point for handling CD-ROM
27565  *		ioctl requests to output the audio signals at the specified
27566  *		starting address and continue the audio play until the specified
27567  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
27568  *		format.
27569  *
27570  *   Arguments: dev	- the device 'dev_t'
27571  *		data	- pointer to user provided audio track/index structure,
27572  *		          specifying start/end addresses.
27573  *		flag	- this argument is a pass through to ddi_copyxxx()
27574  *		          directly from the mode argument of ioctl().
27575  *
27576  * Return Code: the code returned by sd_send_scsi_cmd()
27577  *		EFAULT if ddi_copyxxx() fails
27578  *		ENXIO if fail ddi_get_soft_state
27579  *		EINVAL if data pointer is NULL
27580  */
27581 
27582 static int
27583 sr_play_trkind(dev_t dev, caddr_t data, int flag)
27584 {
27585 	struct cdrom_ti		ti_struct;
27586 	struct cdrom_ti		*ti = &ti_struct;
27587 	struct uscsi_cmd	*com = NULL;
27588 	char			cdb[CDB_GROUP1];
27589 	int			rval;
27590 
27591 	if (data == NULL) {
27592 		return (EINVAL);
27593 	}
27594 
27595 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
27596 		return (EFAULT);
27597 	}
27598 
27599 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27600 	bzero(cdb, CDB_GROUP1);
27601 	cdb[0] = SCMD_PLAYAUDIO_TI;
27602 	cdb[4] = ti->cdti_trk0;
27603 	cdb[5] = ti->cdti_ind0;
27604 	cdb[7] = ti->cdti_trk1;
27605 	cdb[8] = ti->cdti_ind1;
27606 	com->uscsi_cdb    = cdb;
27607 	com->uscsi_cdblen = CDB_GROUP1;
27608 	com->uscsi_flags  = USCSI_DIAGNOSE | USCSI_SILENT;
27609 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27610 	    SD_PATH_STANDARD);
27611 	kmem_free(com, sizeof (*com));
27612 	return (rval);
27613 }
27614 
27615 
27616 /*
27617  *    Function: sr_read_all_subcodes()
27618  *
27619  * Description: This routine is the driver entry point for handling CD-ROM
27620  *		ioctl requests to return raw subcode data while the target is
27621  *		playing audio (CDROMSUBCODE).
27622  *
27623  *   Arguments: dev	- the device 'dev_t'
27624  *		data	- pointer to user provided cdrom subcode structure,
27625  *		          specifying the transfer length and address.
27626  *		flag	- this argument is a pass through to ddi_copyxxx()
27627  *		          directly from the mode argument of ioctl().
27628  *
27629  * Return Code: the code returned by sd_send_scsi_cmd()
27630  *		EFAULT if ddi_copyxxx() fails
27631  *		ENXIO if fail ddi_get_soft_state
27632  *		EINVAL if data pointer is NULL
27633  */
27634 
27635 static int
27636 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
27637 {
27638 	struct sd_lun		*un = NULL;
27639 	struct uscsi_cmd	*com = NULL;
27640 	struct cdrom_subcode	*subcode = NULL;
27641 	int			rval;
27642 	size_t			buflen;
27643 	char			cdb[CDB_GROUP5];
27644 
27645 #ifdef _MULTI_DATAMODEL
27646 	/* To support ILP32 applications in an LP64 world */
27647 	struct cdrom_subcode32		cdrom_subcode32;
27648 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
27649 #endif
27650 	if (data == NULL) {
27651 		return (EINVAL);
27652 	}
27653 
27654 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
27655 		return (ENXIO);
27656 	}
27657 
27658 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
27659 
27660 #ifdef _MULTI_DATAMODEL
27661 	switch (ddi_model_convert_from(flag & FMODELS)) {
27662 	case DDI_MODEL_ILP32:
27663 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
27664 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27665 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27666 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27667 			return (EFAULT);
27668 		}
27669 		/* Convert the ILP32 uscsi data from the application to LP64 */
27670 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
27671 		break;
27672 	case DDI_MODEL_NONE:
27673 		if (ddi_copyin(data, subcode,
27674 		    sizeof (struct cdrom_subcode), flag)) {
27675 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27676 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
27677 			kmem_free(subcode, sizeof (struct cdrom_subcode));
27678 			return (EFAULT);
27679 		}
27680 		break;
27681 	}
27682 #else /* ! _MULTI_DATAMODEL */
27683 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
27684 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27685 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
27686 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27687 		return (EFAULT);
27688 	}
27689 #endif /* _MULTI_DATAMODEL */
27690 
27691 	/*
27692 	 * Since MMC-2 expects max 3 bytes for length, check if the
27693 	 * length input is greater than 3 bytes
27694 	 */
27695 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
27696 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27697 		    "sr_read_all_subcodes: "
27698 		    "cdrom transfer length too large: %d (limit %d)\n",
27699 		    subcode->cdsc_length, 0xFFFFFF);
27700 		kmem_free(subcode, sizeof (struct cdrom_subcode));
27701 		return (EINVAL);
27702 	}
27703 
27704 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
27705 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27706 	bzero(cdb, CDB_GROUP5);
27707 
27708 	if (un->un_f_mmc_cap == TRUE) {
27709 		cdb[0] = (char)SCMD_READ_CD;
27710 		cdb[2] = (char)0xff;
27711 		cdb[3] = (char)0xff;
27712 		cdb[4] = (char)0xff;
27713 		cdb[5] = (char)0xff;
27714 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27715 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27716 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
27717 		cdb[10] = 1;
27718 	} else {
27719 		/*
27720 		 * Note: A vendor specific command (0xDF) is being used here to
27721 		 * request a read of all subcodes.
27722 		 */
27723 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
27724 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
27725 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
27726 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
27727 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
27728 	}
27729 	com->uscsi_cdb	   = cdb;
27730 	com->uscsi_cdblen  = CDB_GROUP5;
27731 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
27732 	com->uscsi_buflen  = buflen;
27733 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
27734 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
27735 	    SD_PATH_STANDARD);
27736 	kmem_free(subcode, sizeof (struct cdrom_subcode));
27737 	kmem_free(com, sizeof (*com));
27738 	return (rval);
27739 }
27740 
27741 
27742 /*
27743  *    Function: sr_read_subchannel()
27744  *
27745  * Description: This routine is the driver entry point for handling CD-ROM
27746  *		ioctl requests to return the Q sub-channel data of the CD
27747  *		current position block. (CDROMSUBCHNL) The data includes the
27748  *		track number, index number, absolute CD-ROM address (LBA or MSF
27749  *		format per the user) , track relative CD-ROM address (LBA or MSF
27750  *		format per the user), control data and audio status.
27751  *
27752  *   Arguments: dev	- the device 'dev_t'
27753  *		data	- pointer to user provided cdrom sub-channel structure
27754  *		flag	- this argument is a pass through to ddi_copyxxx()
27755  *		          directly from the mode argument of ioctl().
27756  *
27757  * Return Code: the code returned by sd_send_scsi_cmd()
27758  *		EFAULT if ddi_copyxxx() fails
27759  *		ENXIO if fail ddi_get_soft_state
27760  *		EINVAL if data pointer is NULL
27761  */
27762 
27763 static int
27764 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
27765 {
27766 	struct sd_lun		*un;
27767 	struct uscsi_cmd	*com;
27768 	struct cdrom_subchnl	subchanel;
27769 	struct cdrom_subchnl	*subchnl = &subchanel;
27770 	char			cdb[CDB_GROUP1];
27771 	caddr_t			buffer;
27772 	int			rval;
27773 
27774 	if (data == NULL) {
27775 		return (EINVAL);
27776 	}
27777 
27778 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27779 	    (un->un_state == SD_STATE_OFFLINE)) {
27780 		return (ENXIO);
27781 	}
27782 
27783 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
27784 		return (EFAULT);
27785 	}
27786 
27787 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
27788 	bzero(cdb, CDB_GROUP1);
27789 	cdb[0] = SCMD_READ_SUBCHANNEL;
27790 	/* Set the MSF bit based on the user requested address format */
27791 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
27792 	/*
27793 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
27794 	 * returned
27795 	 */
27796 	cdb[2] = 0x40;
27797 	/*
27798 	 * Set byte 3 to specify the return data format. A value of 0x01
27799 	 * indicates that the CD-ROM current position should be returned.
27800 	 */
27801 	cdb[3] = 0x01;
27802 	cdb[8] = 0x10;
27803 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27804 	com->uscsi_cdb	   = cdb;
27805 	com->uscsi_cdblen  = CDB_GROUP1;
27806 	com->uscsi_bufaddr = buffer;
27807 	com->uscsi_buflen  = 16;
27808 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
27809 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27810 	    SD_PATH_STANDARD);
27811 	if (rval != 0) {
27812 		kmem_free(buffer, 16);
27813 		kmem_free(com, sizeof (*com));
27814 		return (rval);
27815 	}
27816 
27817 	/* Process the returned Q sub-channel data */
27818 	subchnl->cdsc_audiostatus = buffer[1];
27819 	subchnl->cdsc_adr	= (buffer[5] & 0xF0) >> 4;
27820 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
27821 	subchnl->cdsc_trk	= buffer[6];
27822 	subchnl->cdsc_ind	= buffer[7];
27823 	if (subchnl->cdsc_format & CDROM_LBA) {
27824 		subchnl->cdsc_absaddr.lba =
27825 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
27826 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
27827 		subchnl->cdsc_reladdr.lba =
27828 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
27829 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
27830 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
27831 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
27832 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
27833 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
27834 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
27835 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
27836 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
27837 	} else {
27838 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
27839 		subchnl->cdsc_absaddr.msf.second = buffer[10];
27840 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
27841 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
27842 		subchnl->cdsc_reladdr.msf.second = buffer[14];
27843 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
27844 	}
27845 	kmem_free(buffer, 16);
27846 	kmem_free(com, sizeof (*com));
27847 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
27848 	    != 0) {
27849 		return (EFAULT);
27850 	}
27851 	return (rval);
27852 }
27853 
27854 
27855 /*
27856  *    Function: sr_read_tocentry()
27857  *
27858  * Description: This routine is the driver entry point for handling CD-ROM
27859  *		ioctl requests to read from the Table of Contents (TOC)
27860  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
27861  *		fields, the starting address (LBA or MSF format per the user)
27862  *		and the data mode if the user specified track is a data track.
27863  *
27864  *		Note: The READ HEADER (0x44) command used in this routine is
27865  *		obsolete per the SCSI MMC spec but still supported in the
27866  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
27867  *		therefore the command is still implemented in this routine.
27868  *
27869  *   Arguments: dev	- the device 'dev_t'
27870  *		data	- pointer to user provided toc entry structure,
27871  *			  specifying the track # and the address format
27872  *			  (LBA or MSF).
27873  *		flag	- this argument is a pass through to ddi_copyxxx()
27874  *		          directly from the mode argument of ioctl().
27875  *
27876  * Return Code: the code returned by sd_send_scsi_cmd()
27877  *		EFAULT if ddi_copyxxx() fails
27878  *		ENXIO if fail ddi_get_soft_state
27879  *		EINVAL if data pointer is NULL
27880  */
27881 
27882 static int
27883 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
27884 {
27885 	struct sd_lun		*un = NULL;
27886 	struct uscsi_cmd	*com;
27887 	struct cdrom_tocentry	toc_entry;
27888 	struct cdrom_tocentry	*entry = &toc_entry;
27889 	caddr_t			buffer;
27890 	int			rval;
27891 	char			cdb[CDB_GROUP1];
27892 
27893 	if (data == NULL) {
27894 		return (EINVAL);
27895 	}
27896 
27897 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
27898 	    (un->un_state == SD_STATE_OFFLINE)) {
27899 		return (ENXIO);
27900 	}
27901 
27902 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
27903 		return (EFAULT);
27904 	}
27905 
27906 	/* Validate the requested track and address format */
27907 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
27908 		return (EINVAL);
27909 	}
27910 
27911 	if (entry->cdte_track == 0) {
27912 		return (EINVAL);
27913 	}
27914 
27915 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
27916 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
27917 	bzero(cdb, CDB_GROUP1);
27918 
27919 	cdb[0] = SCMD_READ_TOC;
27920 	/* Set the MSF bit based on the user requested address format  */
27921 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
27922 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
27923 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
27924 	} else {
27925 		cdb[6] = entry->cdte_track;
27926 	}
27927 
27928 	/*
27929 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
27930 	 * (4 byte TOC response header + 8 byte track descriptor)
27931 	 */
27932 	cdb[8] = 12;
27933 	com->uscsi_cdb	   = cdb;
27934 	com->uscsi_cdblen  = CDB_GROUP1;
27935 	com->uscsi_bufaddr = buffer;
27936 	com->uscsi_buflen  = 0x0C;
27937 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
27938 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27939 	    SD_PATH_STANDARD);
27940 	if (rval != 0) {
27941 		kmem_free(buffer, 12);
27942 		kmem_free(com, sizeof (*com));
27943 		return (rval);
27944 	}
27945 
27946 	/* Process the toc entry */
27947 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
27948 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
27949 	if (entry->cdte_format & CDROM_LBA) {
27950 		entry->cdte_addr.lba =
27951 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
27952 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
27953 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
27954 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
27955 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
27956 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
27957 		/*
27958 		 * Send a READ TOC command using the LBA address format to get
27959 		 * the LBA for the track requested so it can be used in the
27960 		 * READ HEADER request
27961 		 *
27962 		 * Note: The MSF bit of the READ HEADER command specifies the
27963 		 * output format. The block address specified in that command
27964 		 * must be in LBA format.
27965 		 */
27966 		cdb[1] = 0;
27967 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27968 		    SD_PATH_STANDARD);
27969 		if (rval != 0) {
27970 			kmem_free(buffer, 12);
27971 			kmem_free(com, sizeof (*com));
27972 			return (rval);
27973 		}
27974 	} else {
27975 		entry->cdte_addr.msf.minute	= buffer[9];
27976 		entry->cdte_addr.msf.second	= buffer[10];
27977 		entry->cdte_addr.msf.frame	= buffer[11];
27978 		/*
27979 		 * Send a READ TOC command using the LBA address format to get
27980 		 * the LBA for the track requested so it can be used in the
27981 		 * READ HEADER request
27982 		 *
27983 		 * Note: The MSF bit of the READ HEADER command specifies the
27984 		 * output format. The block address specified in that command
27985 		 * must be in LBA format.
27986 		 */
27987 		cdb[1] = 0;
27988 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
27989 		    SD_PATH_STANDARD);
27990 		if (rval != 0) {
27991 			kmem_free(buffer, 12);
27992 			kmem_free(com, sizeof (*com));
27993 			return (rval);
27994 		}
27995 	}
27996 
27997 	/*
27998 	 * Build and send the READ HEADER command to determine the data mode of
27999 	 * the user specified track.
28000 	 */
28001 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
28002 	    (entry->cdte_track != CDROM_LEADOUT)) {
28003 		bzero(cdb, CDB_GROUP1);
28004 		cdb[0] = SCMD_READ_HEADER;
28005 		cdb[2] = buffer[8];
28006 		cdb[3] = buffer[9];
28007 		cdb[4] = buffer[10];
28008 		cdb[5] = buffer[11];
28009 		cdb[8] = 0x08;
28010 		com->uscsi_buflen = 0x08;
28011 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28012 		    SD_PATH_STANDARD);
28013 		if (rval == 0) {
28014 			entry->cdte_datamode = buffer[0];
28015 		} else {
28016 			/*
28017 			 * READ HEADER command failed, since this is
28018 			 * obsoleted in one spec, its better to return
28019 			 * -1 for an invlid track so that we can still
28020 			 * receive the rest of the TOC data.
28021 			 */
28022 			entry->cdte_datamode = (uchar_t)-1;
28023 		}
28024 	} else {
28025 		entry->cdte_datamode = (uchar_t)-1;
28026 	}
28027 
28028 	kmem_free(buffer, 12);
28029 	kmem_free(com, sizeof (*com));
28030 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
28031 		return (EFAULT);
28032 
28033 	return (rval);
28034 }
28035 
28036 
28037 /*
28038  *    Function: sr_read_tochdr()
28039  *
28040  * Description: This routine is the driver entry point for handling CD-ROM
28041  *		ioctl requests to read the Table of Contents (TOC) header
28042  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
28043  *		and ending track numbers
28044  *
28045  *   Arguments: dev	- the device 'dev_t'
28046  *		data	- pointer to user provided toc header structure,
28047  *			  specifying the starting and ending track numbers.
28048  *		flag	- this argument is a pass through to ddi_copyxxx()
28049  *			  directly from the mode argument of ioctl().
28050  *
28051  * Return Code: the code returned by sd_send_scsi_cmd()
28052  *		EFAULT if ddi_copyxxx() fails
28053  *		ENXIO if fail ddi_get_soft_state
28054  *		EINVAL if data pointer is NULL
28055  */
28056 
28057 static int
28058 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
28059 {
28060 	struct sd_lun		*un;
28061 	struct uscsi_cmd	*com;
28062 	struct cdrom_tochdr	toc_header;
28063 	struct cdrom_tochdr	*hdr = &toc_header;
28064 	char			cdb[CDB_GROUP1];
28065 	int			rval;
28066 	caddr_t			buffer;
28067 
28068 	if (data == NULL) {
28069 		return (EINVAL);
28070 	}
28071 
28072 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28073 	    (un->un_state == SD_STATE_OFFLINE)) {
28074 		return (ENXIO);
28075 	}
28076 
28077 	buffer = kmem_zalloc(4, KM_SLEEP);
28078 	bzero(cdb, CDB_GROUP1);
28079 	cdb[0] = SCMD_READ_TOC;
28080 	/*
28081 	 * Specifying a track number of 0x00 in the READ TOC command indicates
28082 	 * that the TOC header should be returned
28083 	 */
28084 	cdb[6] = 0x00;
28085 	/*
28086 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
28087 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
28088 	 */
28089 	cdb[8] = 0x04;
28090 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28091 	com->uscsi_cdb	   = cdb;
28092 	com->uscsi_cdblen  = CDB_GROUP1;
28093 	com->uscsi_bufaddr = buffer;
28094 	com->uscsi_buflen  = 0x04;
28095 	com->uscsi_timeout = 300;
28096 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28097 
28098 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
28099 	    SD_PATH_STANDARD);
28100 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
28101 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
28102 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
28103 	} else {
28104 		hdr->cdth_trk0 = buffer[2];
28105 		hdr->cdth_trk1 = buffer[3];
28106 	}
28107 	kmem_free(buffer, 4);
28108 	kmem_free(com, sizeof (*com));
28109 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
28110 		return (EFAULT);
28111 	}
28112 	return (rval);
28113 }
28114 
28115 
28116 /*
28117  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
28118  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
28119  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
28120  * digital audio and extended architecture digital audio. These modes are
28121  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
28122  * MMC specs.
28123  *
28124  * In addition to support for the various data formats these routines also
28125  * include support for devices that implement only the direct access READ
28126  * commands (0x08, 0x28), devices that implement the READ_CD commands
28127  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
28128  * READ CDXA commands (0xD8, 0xDB)
28129  */
28130 
28131 /*
28132  *    Function: sr_read_mode1()
28133  *
28134  * Description: This routine is the driver entry point for handling CD-ROM
28135  *		ioctl read mode1 requests (CDROMREADMODE1).
28136  *
28137  *   Arguments: dev	- the device 'dev_t'
28138  *		data	- pointer to user provided cd read structure specifying
28139  *			  the lba buffer address and length.
28140  *		flag	- this argument is a pass through to ddi_copyxxx()
28141  *			  directly from the mode argument of ioctl().
28142  *
28143  * Return Code: the code returned by sd_send_scsi_cmd()
28144  *		EFAULT if ddi_copyxxx() fails
28145  *		ENXIO if fail ddi_get_soft_state
28146  *		EINVAL if data pointer is NULL
28147  */
28148 
28149 static int
28150 sr_read_mode1(dev_t dev, caddr_t data, int flag)
28151 {
28152 	struct sd_lun		*un;
28153 	struct cdrom_read	mode1_struct;
28154 	struct cdrom_read	*mode1 = &mode1_struct;
28155 	int			rval;
28156 	sd_ssc_t		*ssc;
28157 
28158 #ifdef _MULTI_DATAMODEL
28159 	/* To support ILP32 applications in an LP64 world */
28160 	struct cdrom_read32	cdrom_read32;
28161 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28162 #endif /* _MULTI_DATAMODEL */
28163 
28164 	if (data == NULL) {
28165 		return (EINVAL);
28166 	}
28167 
28168 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28169 	    (un->un_state == SD_STATE_OFFLINE)) {
28170 		return (ENXIO);
28171 	}
28172 
28173 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28174 	    "sd_read_mode1: entry: un:0x%p\n", un);
28175 
28176 #ifdef _MULTI_DATAMODEL
28177 	switch (ddi_model_convert_from(flag & FMODELS)) {
28178 	case DDI_MODEL_ILP32:
28179 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28180 			return (EFAULT);
28181 		}
28182 		/* Convert the ILP32 uscsi data from the application to LP64 */
28183 		cdrom_read32tocdrom_read(cdrd32, mode1);
28184 		break;
28185 	case DDI_MODEL_NONE:
28186 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28187 			return (EFAULT);
28188 		}
28189 	}
28190 #else /* ! _MULTI_DATAMODEL */
28191 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
28192 		return (EFAULT);
28193 	}
28194 #endif /* _MULTI_DATAMODEL */
28195 
28196 	ssc = sd_ssc_init(un);
28197 	rval = sd_send_scsi_READ(ssc, mode1->cdread_bufaddr,
28198 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
28199 	sd_ssc_fini(ssc);
28200 
28201 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28202 	    "sd_read_mode1: exit: un:0x%p\n", un);
28203 
28204 	return (rval);
28205 }
28206 
28207 
28208 /*
28209  *    Function: sr_read_cd_mode2()
28210  *
28211  * Description: This routine is the driver entry point for handling CD-ROM
28212  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28213  *		support the READ CD (0xBE) command or the 1st generation
28214  *		READ CD (0xD4) command.
28215  *
28216  *   Arguments: dev	- the device 'dev_t'
28217  *		data	- pointer to user provided cd read structure specifying
28218  *			  the lba buffer address and length.
28219  *		flag	- this argument is a pass through to ddi_copyxxx()
28220  *			  directly from the mode argument of ioctl().
28221  *
28222  * Return Code: the code returned by sd_send_scsi_cmd()
28223  *		EFAULT if ddi_copyxxx() fails
28224  *		ENXIO if fail ddi_get_soft_state
28225  *		EINVAL if data pointer is NULL
28226  */
28227 
28228 static int
28229 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
28230 {
28231 	struct sd_lun		*un;
28232 	struct uscsi_cmd	*com;
28233 	struct cdrom_read	mode2_struct;
28234 	struct cdrom_read	*mode2 = &mode2_struct;
28235 	uchar_t			cdb[CDB_GROUP5];
28236 	int			nblocks;
28237 	int			rval;
28238 #ifdef _MULTI_DATAMODEL
28239 	/*  To support ILP32 applications in an LP64 world */
28240 	struct cdrom_read32	cdrom_read32;
28241 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28242 #endif /* _MULTI_DATAMODEL */
28243 
28244 	if (data == NULL) {
28245 		return (EINVAL);
28246 	}
28247 
28248 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28249 	    (un->un_state == SD_STATE_OFFLINE)) {
28250 		return (ENXIO);
28251 	}
28252 
28253 #ifdef _MULTI_DATAMODEL
28254 	switch (ddi_model_convert_from(flag & FMODELS)) {
28255 	case DDI_MODEL_ILP32:
28256 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28257 			return (EFAULT);
28258 		}
28259 		/* Convert the ILP32 uscsi data from the application to LP64 */
28260 		cdrom_read32tocdrom_read(cdrd32, mode2);
28261 		break;
28262 	case DDI_MODEL_NONE:
28263 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28264 			return (EFAULT);
28265 		}
28266 		break;
28267 	}
28268 
28269 #else /* ! _MULTI_DATAMODEL */
28270 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28271 		return (EFAULT);
28272 	}
28273 #endif /* _MULTI_DATAMODEL */
28274 
28275 	bzero(cdb, sizeof (cdb));
28276 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
28277 		/* Read command supported by 1st generation atapi drives */
28278 		cdb[0] = SCMD_READ_CDD4;
28279 	} else {
28280 		/* Universal CD Access Command */
28281 		cdb[0] = SCMD_READ_CD;
28282 	}
28283 
28284 	/*
28285 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
28286 	 */
28287 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
28288 
28289 	/* set the start address */
28290 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
28291 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
28292 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28293 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
28294 
28295 	/* set the transfer length */
28296 	nblocks = mode2->cdread_buflen / 2336;
28297 	cdb[6] = (uchar_t)(nblocks >> 16);
28298 	cdb[7] = (uchar_t)(nblocks >> 8);
28299 	cdb[8] = (uchar_t)nblocks;
28300 
28301 	/* set the filter bits */
28302 	cdb[9] = CDROM_READ_CD_USERDATA;
28303 
28304 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28305 	com->uscsi_cdb = (caddr_t)cdb;
28306 	com->uscsi_cdblen = sizeof (cdb);
28307 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28308 	com->uscsi_buflen = mode2->cdread_buflen;
28309 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28310 
28311 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28312 	    SD_PATH_STANDARD);
28313 	kmem_free(com, sizeof (*com));
28314 	return (rval);
28315 }
28316 
28317 
28318 /*
28319  *    Function: sr_read_mode2()
28320  *
28321  * Description: This routine is the driver entry point for handling CD-ROM
28322  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
28323  *		do not support the READ CD (0xBE) command.
28324  *
28325  *   Arguments: dev	- the device 'dev_t'
28326  *		data	- pointer to user provided cd read structure specifying
28327  *			  the lba buffer address and length.
28328  *		flag	- this argument is a pass through to ddi_copyxxx()
28329  *			  directly from the mode argument of ioctl().
28330  *
28331  * Return Code: the code returned by sd_send_scsi_cmd()
28332  *		EFAULT if ddi_copyxxx() fails
28333  *		ENXIO if fail ddi_get_soft_state
28334  *		EINVAL if data pointer is NULL
28335  *		EIO if fail to reset block size
28336  *		EAGAIN if commands are in progress in the driver
28337  */
28338 
28339 static int
28340 sr_read_mode2(dev_t dev, caddr_t data, int flag)
28341 {
28342 	struct sd_lun		*un;
28343 	struct cdrom_read	mode2_struct;
28344 	struct cdrom_read	*mode2 = &mode2_struct;
28345 	int			rval;
28346 	uint32_t		restore_blksize;
28347 	struct uscsi_cmd	*com;
28348 	uchar_t			cdb[CDB_GROUP0];
28349 	int			nblocks;
28350 
28351 #ifdef _MULTI_DATAMODEL
28352 	/* To support ILP32 applications in an LP64 world */
28353 	struct cdrom_read32	cdrom_read32;
28354 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
28355 #endif /* _MULTI_DATAMODEL */
28356 
28357 	if (data == NULL) {
28358 		return (EINVAL);
28359 	}
28360 
28361 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28362 	    (un->un_state == SD_STATE_OFFLINE)) {
28363 		return (ENXIO);
28364 	}
28365 
28366 	/*
28367 	 * Because this routine will update the device and driver block size
28368 	 * being used we want to make sure there are no commands in progress.
28369 	 * If commands are in progress the user will have to try again.
28370 	 *
28371 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
28372 	 * in sdioctl to protect commands from sdioctl through to the top of
28373 	 * sd_uscsi_strategy. See sdioctl for details.
28374 	 */
28375 	mutex_enter(SD_MUTEX(un));
28376 	if (un->un_ncmds_in_driver != 1) {
28377 		mutex_exit(SD_MUTEX(un));
28378 		return (EAGAIN);
28379 	}
28380 	mutex_exit(SD_MUTEX(un));
28381 
28382 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28383 	    "sd_read_mode2: entry: un:0x%p\n", un);
28384 
28385 #ifdef _MULTI_DATAMODEL
28386 	switch (ddi_model_convert_from(flag & FMODELS)) {
28387 	case DDI_MODEL_ILP32:
28388 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
28389 			return (EFAULT);
28390 		}
28391 		/* Convert the ILP32 uscsi data from the application to LP64 */
28392 		cdrom_read32tocdrom_read(cdrd32, mode2);
28393 		break;
28394 	case DDI_MODEL_NONE:
28395 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
28396 			return (EFAULT);
28397 		}
28398 		break;
28399 	}
28400 #else /* ! _MULTI_DATAMODEL */
28401 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
28402 		return (EFAULT);
28403 	}
28404 #endif /* _MULTI_DATAMODEL */
28405 
28406 	/* Store the current target block size for restoration later */
28407 	restore_blksize = un->un_tgt_blocksize;
28408 
28409 	/* Change the device and soft state target block size to 2336 */
28410 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
28411 		rval = EIO;
28412 		goto done;
28413 	}
28414 
28415 
28416 	bzero(cdb, sizeof (cdb));
28417 
28418 	/* set READ operation */
28419 	cdb[0] = SCMD_READ;
28420 
28421 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
28422 	mode2->cdread_lba >>= 2;
28423 
28424 	/* set the start address */
28425 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
28426 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
28427 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
28428 
28429 	/* set the transfer length */
28430 	nblocks = mode2->cdread_buflen / 2336;
28431 	cdb[4] = (uchar_t)nblocks & 0xFF;
28432 
28433 	/* build command */
28434 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28435 	com->uscsi_cdb = (caddr_t)cdb;
28436 	com->uscsi_cdblen = sizeof (cdb);
28437 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
28438 	com->uscsi_buflen = mode2->cdread_buflen;
28439 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28440 
28441 	/*
28442 	 * Issue SCSI command with user space address for read buffer.
28443 	 *
28444 	 * This sends the command through main channel in the driver.
28445 	 *
28446 	 * Since this is accessed via an IOCTL call, we go through the
28447 	 * standard path, so that if the device was powered down, then
28448 	 * it would be 'awakened' to handle the command.
28449 	 */
28450 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28451 	    SD_PATH_STANDARD);
28452 
28453 	kmem_free(com, sizeof (*com));
28454 
28455 	/* Restore the device and soft state target block size */
28456 	if (sr_sector_mode(dev, restore_blksize) != 0) {
28457 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28458 		    "can't do switch back to mode 1\n");
28459 		/*
28460 		 * If sd_send_scsi_READ succeeded we still need to report
28461 		 * an error because we failed to reset the block size
28462 		 */
28463 		if (rval == 0) {
28464 			rval = EIO;
28465 		}
28466 	}
28467 
28468 done:
28469 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
28470 	    "sd_read_mode2: exit: un:0x%p\n", un);
28471 
28472 	return (rval);
28473 }
28474 
28475 
28476 /*
28477  *    Function: sr_sector_mode()
28478  *
28479  * Description: This utility function is used by sr_read_mode2 to set the target
28480  *		block size based on the user specified size. This is a legacy
28481  *		implementation based upon a vendor specific mode page
28482  *
28483  *   Arguments: dev	- the device 'dev_t'
28484  *		data	- flag indicating if block size is being set to 2336 or
28485  *			  512.
28486  *
28487  * Return Code: the code returned by sd_send_scsi_cmd()
28488  *		EFAULT if ddi_copyxxx() fails
28489  *		ENXIO if fail ddi_get_soft_state
28490  *		EINVAL if data pointer is NULL
28491  */
28492 
28493 static int
28494 sr_sector_mode(dev_t dev, uint32_t blksize)
28495 {
28496 	struct sd_lun	*un;
28497 	uchar_t		*sense;
28498 	uchar_t		*select;
28499 	int		rval;
28500 	sd_ssc_t	*ssc;
28501 
28502 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28503 	    (un->un_state == SD_STATE_OFFLINE)) {
28504 		return (ENXIO);
28505 	}
28506 
28507 	sense = kmem_zalloc(20, KM_SLEEP);
28508 
28509 	/* Note: This is a vendor specific mode page (0x81) */
28510 	ssc = sd_ssc_init(un);
28511 	rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, 20, 0x81,
28512 	    SD_PATH_STANDARD);
28513 	sd_ssc_fini(ssc);
28514 	if (rval != 0) {
28515 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28516 		    "sr_sector_mode: Mode Sense failed\n");
28517 		kmem_free(sense, 20);
28518 		return (rval);
28519 	}
28520 	select = kmem_zalloc(20, KM_SLEEP);
28521 	select[3] = 0x08;
28522 	select[10] = ((blksize >> 8) & 0xff);
28523 	select[11] = (blksize & 0xff);
28524 	select[12] = 0x01;
28525 	select[13] = 0x06;
28526 	select[14] = sense[14];
28527 	select[15] = sense[15];
28528 	if (blksize == SD_MODE2_BLKSIZE) {
28529 		select[14] |= 0x01;
28530 	}
28531 
28532 	ssc = sd_ssc_init(un);
28533 	rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select, 20,
28534 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
28535 	sd_ssc_fini(ssc);
28536 	if (rval != 0) {
28537 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
28538 		    "sr_sector_mode: Mode Select failed\n");
28539 	} else {
28540 		/*
28541 		 * Only update the softstate block size if we successfully
28542 		 * changed the device block mode.
28543 		 */
28544 		mutex_enter(SD_MUTEX(un));
28545 		sd_update_block_info(un, blksize, 0);
28546 		mutex_exit(SD_MUTEX(un));
28547 	}
28548 	kmem_free(sense, 20);
28549 	kmem_free(select, 20);
28550 	return (rval);
28551 }
28552 
28553 
28554 /*
28555  *    Function: sr_read_cdda()
28556  *
28557  * Description: This routine is the driver entry point for handling CD-ROM
28558  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
28559  *		the target supports CDDA these requests are handled via a vendor
28560  *		specific command (0xD8) If the target does not support CDDA
28561  *		these requests are handled via the READ CD command (0xBE).
28562  *
28563  *   Arguments: dev	- the device 'dev_t'
28564  *		data	- pointer to user provided CD-DA structure specifying
28565  *			  the track starting address, transfer length, and
28566  *			  subcode options.
28567  *		flag	- this argument is a pass through to ddi_copyxxx()
28568  *			  directly from the mode argument of ioctl().
28569  *
28570  * Return Code: the code returned by sd_send_scsi_cmd()
28571  *		EFAULT if ddi_copyxxx() fails
28572  *		ENXIO if fail ddi_get_soft_state
28573  *		EINVAL if invalid arguments are provided
28574  *		ENOTTY
28575  */
28576 
28577 static int
28578 sr_read_cdda(dev_t dev, caddr_t data, int flag)
28579 {
28580 	struct sd_lun			*un;
28581 	struct uscsi_cmd		*com;
28582 	struct cdrom_cdda		*cdda;
28583 	int				rval;
28584 	size_t				buflen;
28585 	char				cdb[CDB_GROUP5];
28586 
28587 #ifdef _MULTI_DATAMODEL
28588 	/* To support ILP32 applications in an LP64 world */
28589 	struct cdrom_cdda32	cdrom_cdda32;
28590 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
28591 #endif /* _MULTI_DATAMODEL */
28592 
28593 	if (data == NULL) {
28594 		return (EINVAL);
28595 	}
28596 
28597 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28598 		return (ENXIO);
28599 	}
28600 
28601 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
28602 
28603 #ifdef _MULTI_DATAMODEL
28604 	switch (ddi_model_convert_from(flag & FMODELS)) {
28605 	case DDI_MODEL_ILP32:
28606 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
28607 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28608 			    "sr_read_cdda: ddi_copyin Failed\n");
28609 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28610 			return (EFAULT);
28611 		}
28612 		/* Convert the ILP32 uscsi data from the application to LP64 */
28613 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
28614 		break;
28615 	case DDI_MODEL_NONE:
28616 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28617 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28618 			    "sr_read_cdda: ddi_copyin Failed\n");
28619 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28620 			return (EFAULT);
28621 		}
28622 		break;
28623 	}
28624 #else /* ! _MULTI_DATAMODEL */
28625 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
28626 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28627 		    "sr_read_cdda: ddi_copyin Failed\n");
28628 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28629 		return (EFAULT);
28630 	}
28631 #endif /* _MULTI_DATAMODEL */
28632 
28633 	/*
28634 	 * Since MMC-2 expects max 3 bytes for length, check if the
28635 	 * length input is greater than 3 bytes
28636 	 */
28637 	if ((cdda->cdda_length & 0xFF000000) != 0) {
28638 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
28639 		    "cdrom transfer length too large: %d (limit %d)\n",
28640 		    cdda->cdda_length, 0xFFFFFF);
28641 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28642 		return (EINVAL);
28643 	}
28644 
28645 	switch (cdda->cdda_subcode) {
28646 	case CDROM_DA_NO_SUBCODE:
28647 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
28648 		break;
28649 	case CDROM_DA_SUBQ:
28650 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
28651 		break;
28652 	case CDROM_DA_ALL_SUBCODE:
28653 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
28654 		break;
28655 	case CDROM_DA_SUBCODE_ONLY:
28656 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
28657 		break;
28658 	default:
28659 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28660 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
28661 		    cdda->cdda_subcode);
28662 		kmem_free(cdda, sizeof (struct cdrom_cdda));
28663 		return (EINVAL);
28664 	}
28665 
28666 	/* Build and send the command */
28667 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28668 	bzero(cdb, CDB_GROUP5);
28669 
28670 	if (un->un_f_cfg_cdda == TRUE) {
28671 		cdb[0] = (char)SCMD_READ_CD;
28672 		cdb[1] = 0x04;
28673 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28674 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28675 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28676 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28677 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28678 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28679 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
28680 		cdb[9] = 0x10;
28681 		switch (cdda->cdda_subcode) {
28682 		case CDROM_DA_NO_SUBCODE :
28683 			cdb[10] = 0x0;
28684 			break;
28685 		case CDROM_DA_SUBQ :
28686 			cdb[10] = 0x2;
28687 			break;
28688 		case CDROM_DA_ALL_SUBCODE :
28689 			cdb[10] = 0x1;
28690 			break;
28691 		case CDROM_DA_SUBCODE_ONLY :
28692 			/* FALLTHROUGH */
28693 		default :
28694 			kmem_free(cdda, sizeof (struct cdrom_cdda));
28695 			kmem_free(com, sizeof (*com));
28696 			return (ENOTTY);
28697 		}
28698 	} else {
28699 		cdb[0] = (char)SCMD_READ_CDDA;
28700 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
28701 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
28702 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
28703 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
28704 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
28705 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
28706 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
28707 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
28708 		cdb[10] = cdda->cdda_subcode;
28709 	}
28710 
28711 	com->uscsi_cdb = cdb;
28712 	com->uscsi_cdblen = CDB_GROUP5;
28713 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
28714 	com->uscsi_buflen = buflen;
28715 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28716 
28717 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28718 	    SD_PATH_STANDARD);
28719 
28720 	kmem_free(cdda, sizeof (struct cdrom_cdda));
28721 	kmem_free(com, sizeof (*com));
28722 	return (rval);
28723 }
28724 
28725 
28726 /*
28727  *    Function: sr_read_cdxa()
28728  *
28729  * Description: This routine is the driver entry point for handling CD-ROM
28730  *		ioctl requests to return CD-XA (Extended Architecture) data.
28731  *		(CDROMCDXA).
28732  *
28733  *   Arguments: dev	- the device 'dev_t'
28734  *		data	- pointer to user provided CD-XA structure specifying
28735  *			  the data starting address, transfer length, and format
28736  *		flag	- this argument is a pass through to ddi_copyxxx()
28737  *			  directly from the mode argument of ioctl().
28738  *
28739  * Return Code: the code returned by sd_send_scsi_cmd()
28740  *		EFAULT if ddi_copyxxx() fails
28741  *		ENXIO if fail ddi_get_soft_state
28742  *		EINVAL if data pointer is NULL
28743  */
28744 
28745 static int
28746 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
28747 {
28748 	struct sd_lun		*un;
28749 	struct uscsi_cmd	*com;
28750 	struct cdrom_cdxa	*cdxa;
28751 	int			rval;
28752 	size_t			buflen;
28753 	char			cdb[CDB_GROUP5];
28754 	uchar_t			read_flags;
28755 
28756 #ifdef _MULTI_DATAMODEL
28757 	/* To support ILP32 applications in an LP64 world */
28758 	struct cdrom_cdxa32		cdrom_cdxa32;
28759 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
28760 #endif /* _MULTI_DATAMODEL */
28761 
28762 	if (data == NULL) {
28763 		return (EINVAL);
28764 	}
28765 
28766 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
28767 		return (ENXIO);
28768 	}
28769 
28770 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
28771 
28772 #ifdef _MULTI_DATAMODEL
28773 	switch (ddi_model_convert_from(flag & FMODELS)) {
28774 	case DDI_MODEL_ILP32:
28775 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
28776 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28777 			return (EFAULT);
28778 		}
28779 		/*
28780 		 * Convert the ILP32 uscsi data from the
28781 		 * application to LP64 for internal use.
28782 		 */
28783 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
28784 		break;
28785 	case DDI_MODEL_NONE:
28786 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28787 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28788 			return (EFAULT);
28789 		}
28790 		break;
28791 	}
28792 #else /* ! _MULTI_DATAMODEL */
28793 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
28794 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28795 		return (EFAULT);
28796 	}
28797 #endif /* _MULTI_DATAMODEL */
28798 
28799 	/*
28800 	 * Since MMC-2 expects max 3 bytes for length, check if the
28801 	 * length input is greater than 3 bytes
28802 	 */
28803 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
28804 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
28805 		    "cdrom transfer length too large: %d (limit %d)\n",
28806 		    cdxa->cdxa_length, 0xFFFFFF);
28807 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28808 		return (EINVAL);
28809 	}
28810 
28811 	switch (cdxa->cdxa_format) {
28812 	case CDROM_XA_DATA:
28813 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
28814 		read_flags = 0x10;
28815 		break;
28816 	case CDROM_XA_SECTOR_DATA:
28817 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
28818 		read_flags = 0xf8;
28819 		break;
28820 	case CDROM_XA_DATA_W_ERROR:
28821 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
28822 		read_flags = 0xfc;
28823 		break;
28824 	default:
28825 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
28826 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
28827 		    cdxa->cdxa_format);
28828 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28829 		return (EINVAL);
28830 	}
28831 
28832 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
28833 	bzero(cdb, CDB_GROUP5);
28834 	if (un->un_f_mmc_cap == TRUE) {
28835 		cdb[0] = (char)SCMD_READ_CD;
28836 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28837 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28838 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28839 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28840 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28841 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28842 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
28843 		cdb[9] = (char)read_flags;
28844 	} else {
28845 		/*
28846 		 * Note: A vendor specific command (0xDB) is being used her to
28847 		 * request a read of all subcodes.
28848 		 */
28849 		cdb[0] = (char)SCMD_READ_CDXA;
28850 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
28851 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
28852 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
28853 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
28854 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
28855 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
28856 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
28857 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
28858 		cdb[10] = cdxa->cdxa_format;
28859 	}
28860 	com->uscsi_cdb	   = cdb;
28861 	com->uscsi_cdblen  = CDB_GROUP5;
28862 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
28863 	com->uscsi_buflen  = buflen;
28864 	com->uscsi_flags   = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
28865 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
28866 	    SD_PATH_STANDARD);
28867 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
28868 	kmem_free(com, sizeof (*com));
28869 	return (rval);
28870 }
28871 
28872 
28873 /*
28874  *    Function: sr_eject()
28875  *
28876  * Description: This routine is the driver entry point for handling CD-ROM
28877  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
28878  *
28879  *   Arguments: dev	- the device 'dev_t'
28880  *
28881  * Return Code: the code returned by sd_send_scsi_cmd()
28882  */
28883 
28884 static int
28885 sr_eject(dev_t dev)
28886 {
28887 	struct sd_lun	*un;
28888 	int		rval;
28889 	sd_ssc_t	*ssc;
28890 
28891 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
28892 	    (un->un_state == SD_STATE_OFFLINE)) {
28893 		return (ENXIO);
28894 	}
28895 
28896 	/*
28897 	 * To prevent race conditions with the eject
28898 	 * command, keep track of an eject command as
28899 	 * it progresses. If we are already handling
28900 	 * an eject command in the driver for the given
28901 	 * unit and another request to eject is received
28902 	 * immediately return EAGAIN so we don't lose
28903 	 * the command if the current eject command fails.
28904 	 */
28905 	mutex_enter(SD_MUTEX(un));
28906 	if (un->un_f_ejecting == TRUE) {
28907 		mutex_exit(SD_MUTEX(un));
28908 		return (EAGAIN);
28909 	}
28910 	un->un_f_ejecting = TRUE;
28911 	mutex_exit(SD_MUTEX(un));
28912 
28913 	ssc = sd_ssc_init(un);
28914 	rval = sd_send_scsi_DOORLOCK(ssc, SD_REMOVAL_ALLOW,
28915 	    SD_PATH_STANDARD);
28916 	sd_ssc_fini(ssc);
28917 
28918 	if (rval != 0) {
28919 		mutex_enter(SD_MUTEX(un));
28920 		un->un_f_ejecting = FALSE;
28921 		mutex_exit(SD_MUTEX(un));
28922 		return (rval);
28923 	}
28924 
28925 	ssc = sd_ssc_init(un);
28926 	rval = sd_send_scsi_START_STOP_UNIT(ssc, SD_START_STOP,
28927 	    SD_TARGET_EJECT, SD_PATH_STANDARD);
28928 	sd_ssc_fini(ssc);
28929 
28930 	if (rval == 0) {
28931 		mutex_enter(SD_MUTEX(un));
28932 		sr_ejected(un);
28933 		un->un_mediastate = DKIO_EJECTED;
28934 		un->un_f_ejecting = FALSE;
28935 		cv_broadcast(&un->un_state_cv);
28936 		mutex_exit(SD_MUTEX(un));
28937 	} else {
28938 		mutex_enter(SD_MUTEX(un));
28939 		un->un_f_ejecting = FALSE;
28940 		mutex_exit(SD_MUTEX(un));
28941 	}
28942 	return (rval);
28943 }
28944 
28945 
28946 /*
28947  *    Function: sr_ejected()
28948  *
28949  * Description: This routine updates the soft state structure to invalidate the
28950  *		geometry information after the media has been ejected or a
28951  *		media eject has been detected.
28952  *
28953  *   Arguments: un - driver soft state (unit) structure
28954  */
28955 
28956 static void
28957 sr_ejected(struct sd_lun *un)
28958 {
28959 	struct sd_errstats *stp;
28960 
28961 	ASSERT(un != NULL);
28962 	ASSERT(mutex_owned(SD_MUTEX(un)));
28963 
28964 	un->un_f_blockcount_is_valid	= FALSE;
28965 	un->un_f_tgt_blocksize_is_valid	= FALSE;
28966 	mutex_exit(SD_MUTEX(un));
28967 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
28968 	mutex_enter(SD_MUTEX(un));
28969 
28970 	if (un->un_errstats != NULL) {
28971 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
28972 		stp->sd_capacity.value.ui64 = 0;
28973 	}
28974 }
28975 
28976 
28977 /*
28978  *    Function: sr_check_wp()
28979  *
28980  * Description: This routine checks the write protection of a removable
28981  *      media disk and hotpluggable devices via the write protect bit of
28982  *      the Mode Page Header device specific field. Some devices choke
28983  *      on unsupported mode page. In order to workaround this issue,
28984  *      this routine has been implemented to use 0x3f mode page(request
28985  *      for all pages) for all device types.
28986  *
28987  *   Arguments: dev             - the device 'dev_t'
28988  *
28989  * Return Code: int indicating if the device is write protected (1) or not (0)
28990  *
28991  *     Context: Kernel thread.
28992  *
28993  */
28994 
28995 static int
28996 sr_check_wp(dev_t dev)
28997 {
28998 	struct sd_lun	*un;
28999 	uchar_t		device_specific;
29000 	uchar_t		*sense;
29001 	int		hdrlen;
29002 	int		rval = FALSE;
29003 	int		status;
29004 	sd_ssc_t	*ssc;
29005 
29006 	/*
29007 	 * Note: The return codes for this routine should be reworked to
29008 	 * properly handle the case of a NULL softstate.
29009 	 */
29010 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
29011 		return (FALSE);
29012 	}
29013 
29014 	if (un->un_f_cfg_is_atapi == TRUE) {
29015 		/*
29016 		 * The mode page contents are not required; set the allocation
29017 		 * length for the mode page header only
29018 		 */
29019 		hdrlen = MODE_HEADER_LENGTH_GRP2;
29020 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
29021 		ssc = sd_ssc_init(un);
29022 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense, hdrlen,
29023 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
29024 		sd_ssc_fini(ssc);
29025 		if (status != 0)
29026 			goto err_exit;
29027 		device_specific =
29028 		    ((struct mode_header_grp2 *)sense)->device_specific;
29029 	} else {
29030 		hdrlen = MODE_HEADER_LENGTH;
29031 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
29032 		ssc = sd_ssc_init(un);
29033 		status = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense, hdrlen,
29034 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD);
29035 		sd_ssc_fini(ssc);
29036 		if (status != 0)
29037 			goto err_exit;
29038 		device_specific =
29039 		    ((struct mode_header *)sense)->device_specific;
29040 	}
29041 
29042 
29043 	/*
29044 	 * Write protect mode sense failed; not all disks
29045 	 * understand this query. Return FALSE assuming that
29046 	 * these devices are not writable.
29047 	 */
29048 	if (device_specific & WRITE_PROTECT) {
29049 		rval = TRUE;
29050 	}
29051 
29052 err_exit:
29053 	kmem_free(sense, hdrlen);
29054 	return (rval);
29055 }
29056 
29057 /*
29058  *    Function: sr_volume_ctrl()
29059  *
29060  * Description: This routine is the driver entry point for handling CD-ROM
29061  *		audio output volume ioctl requests. (CDROMVOLCTRL)
29062  *
29063  *   Arguments: dev	- the device 'dev_t'
29064  *		data	- pointer to user audio volume control structure
29065  *		flag	- this argument is a pass through to ddi_copyxxx()
29066  *			  directly from the mode argument of ioctl().
29067  *
29068  * Return Code: the code returned by sd_send_scsi_cmd()
29069  *		EFAULT if ddi_copyxxx() fails
29070  *		ENXIO if fail ddi_get_soft_state
29071  *		EINVAL if data pointer is NULL
29072  *
29073  */
29074 
29075 static int
29076 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
29077 {
29078 	struct sd_lun		*un;
29079 	struct cdrom_volctrl    volume;
29080 	struct cdrom_volctrl    *vol = &volume;
29081 	uchar_t			*sense_page;
29082 	uchar_t			*select_page;
29083 	uchar_t			*sense;
29084 	uchar_t			*select;
29085 	int			sense_buflen;
29086 	int			select_buflen;
29087 	int			rval;
29088 	sd_ssc_t		*ssc;
29089 
29090 	if (data == NULL) {
29091 		return (EINVAL);
29092 	}
29093 
29094 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29095 	    (un->un_state == SD_STATE_OFFLINE)) {
29096 		return (ENXIO);
29097 	}
29098 
29099 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
29100 		return (EFAULT);
29101 	}
29102 
29103 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
29104 		struct mode_header_grp2		*sense_mhp;
29105 		struct mode_header_grp2		*select_mhp;
29106 		int				bd_len;
29107 
29108 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
29109 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
29110 		    MODEPAGE_AUDIO_CTRL_LEN;
29111 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
29112 		select = kmem_zalloc(select_buflen, KM_SLEEP);
29113 		ssc = sd_ssc_init(un);
29114 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP1, sense,
29115 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
29116 		    SD_PATH_STANDARD);
29117 		sd_ssc_fini(ssc);
29118 
29119 		if (rval != 0) {
29120 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
29121 			    "sr_volume_ctrl: Mode Sense Failed\n");
29122 			kmem_free(sense, sense_buflen);
29123 			kmem_free(select, select_buflen);
29124 			return (rval);
29125 		}
29126 		sense_mhp = (struct mode_header_grp2 *)sense;
29127 		select_mhp = (struct mode_header_grp2 *)select;
29128 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
29129 		    sense_mhp->bdesc_length_lo;
29130 		if (bd_len > MODE_BLK_DESC_LENGTH) {
29131 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29132 			    "sr_volume_ctrl: Mode Sense returned invalid "
29133 			    "block descriptor length\n");
29134 			kmem_free(sense, sense_buflen);
29135 			kmem_free(select, select_buflen);
29136 			return (EIO);
29137 		}
29138 		sense_page = (uchar_t *)
29139 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
29140 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
29141 		select_mhp->length_msb = 0;
29142 		select_mhp->length_lsb = 0;
29143 		select_mhp->bdesc_length_hi = 0;
29144 		select_mhp->bdesc_length_lo = 0;
29145 	} else {
29146 		struct mode_header		*sense_mhp, *select_mhp;
29147 
29148 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29149 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
29150 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
29151 		select = kmem_zalloc(select_buflen, KM_SLEEP);
29152 		ssc = sd_ssc_init(un);
29153 		rval = sd_send_scsi_MODE_SENSE(ssc, CDB_GROUP0, sense,
29154 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
29155 		    SD_PATH_STANDARD);
29156 		sd_ssc_fini(ssc);
29157 
29158 		if (rval != 0) {
29159 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29160 			    "sr_volume_ctrl: Mode Sense Failed\n");
29161 			kmem_free(sense, sense_buflen);
29162 			kmem_free(select, select_buflen);
29163 			return (rval);
29164 		}
29165 		sense_mhp  = (struct mode_header *)sense;
29166 		select_mhp = (struct mode_header *)select;
29167 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
29168 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29169 			    "sr_volume_ctrl: Mode Sense returned invalid "
29170 			    "block descriptor length\n");
29171 			kmem_free(sense, sense_buflen);
29172 			kmem_free(select, select_buflen);
29173 			return (EIO);
29174 		}
29175 		sense_page = (uchar_t *)
29176 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
29177 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
29178 		select_mhp->length = 0;
29179 		select_mhp->bdesc_length = 0;
29180 	}
29181 	/*
29182 	 * Note: An audio control data structure could be created and overlayed
29183 	 * on the following in place of the array indexing method implemented.
29184 	 */
29185 
29186 	/* Build the select data for the user volume data */
29187 	select_page[0] = MODEPAGE_AUDIO_CTRL;
29188 	select_page[1] = 0xE;
29189 	/* Set the immediate bit */
29190 	select_page[2] = 0x04;
29191 	/* Zero out reserved fields */
29192 	select_page[3] = 0x00;
29193 	select_page[4] = 0x00;
29194 	/* Return sense data for fields not to be modified */
29195 	select_page[5] = sense_page[5];
29196 	select_page[6] = sense_page[6];
29197 	select_page[7] = sense_page[7];
29198 	/* Set the user specified volume levels for channel 0 and 1 */
29199 	select_page[8] = 0x01;
29200 	select_page[9] = vol->channel0;
29201 	select_page[10] = 0x02;
29202 	select_page[11] = vol->channel1;
29203 	/* Channel 2 and 3 are currently unsupported so return the sense data */
29204 	select_page[12] = sense_page[12];
29205 	select_page[13] = sense_page[13];
29206 	select_page[14] = sense_page[14];
29207 	select_page[15] = sense_page[15];
29208 
29209 	ssc = sd_ssc_init(un);
29210 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
29211 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP1, select,
29212 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29213 	} else {
29214 		rval = sd_send_scsi_MODE_SELECT(ssc, CDB_GROUP0, select,
29215 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
29216 	}
29217 	sd_ssc_fini(ssc);
29218 
29219 	kmem_free(sense, sense_buflen);
29220 	kmem_free(select, select_buflen);
29221 	return (rval);
29222 }
29223 
29224 
29225 /*
29226  *    Function: sr_read_sony_session_offset()
29227  *
29228  * Description: This routine is the driver entry point for handling CD-ROM
29229  *		ioctl requests for session offset information. (CDROMREADOFFSET)
29230  *		The address of the first track in the last session of a
29231  *		multi-session CD-ROM is returned
29232  *
29233  *		Note: This routine uses a vendor specific key value in the
29234  *		command control field without implementing any vendor check here
29235  *		or in the ioctl routine.
29236  *
29237  *   Arguments: dev	- the device 'dev_t'
29238  *		data	- pointer to an int to hold the requested address
29239  *		flag	- this argument is a pass through to ddi_copyxxx()
29240  *			  directly from the mode argument of ioctl().
29241  *
29242  * Return Code: the code returned by sd_send_scsi_cmd()
29243  *		EFAULT if ddi_copyxxx() fails
29244  *		ENXIO if fail ddi_get_soft_state
29245  *		EINVAL if data pointer is NULL
29246  */
29247 
29248 static int
29249 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
29250 {
29251 	struct sd_lun		*un;
29252 	struct uscsi_cmd	*com;
29253 	caddr_t			buffer;
29254 	char			cdb[CDB_GROUP1];
29255 	int			session_offset = 0;
29256 	int			rval;
29257 
29258 	if (data == NULL) {
29259 		return (EINVAL);
29260 	}
29261 
29262 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
29263 	    (un->un_state == SD_STATE_OFFLINE)) {
29264 		return (ENXIO);
29265 	}
29266 
29267 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
29268 	bzero(cdb, CDB_GROUP1);
29269 	cdb[0] = SCMD_READ_TOC;
29270 	/*
29271 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
29272 	 * (4 byte TOC response header + 8 byte response data)
29273 	 */
29274 	cdb[8] = SONY_SESSION_OFFSET_LEN;
29275 	/* Byte 9 is the control byte. A vendor specific value is used */
29276 	cdb[9] = SONY_SESSION_OFFSET_KEY;
29277 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
29278 	com->uscsi_cdb = cdb;
29279 	com->uscsi_cdblen = CDB_GROUP1;
29280 	com->uscsi_bufaddr = buffer;
29281 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
29282 	com->uscsi_flags = USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ;
29283 
29284 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
29285 	    SD_PATH_STANDARD);
29286 	if (rval != 0) {
29287 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29288 		kmem_free(com, sizeof (*com));
29289 		return (rval);
29290 	}
29291 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
29292 		session_offset =
29293 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
29294 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
29295 		/*
29296 		 * Offset returned offset in current lbasize block's. Convert to
29297 		 * 2k block's to return to the user
29298 		 */
29299 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
29300 			session_offset >>= 2;
29301 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
29302 			session_offset >>= 1;
29303 		}
29304 	}
29305 
29306 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
29307 		rval = EFAULT;
29308 	}
29309 
29310 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
29311 	kmem_free(com, sizeof (*com));
29312 	return (rval);
29313 }
29314 
29315 
29316 /*
29317  *    Function: sd_wm_cache_constructor()
29318  *
29319  * Description: Cache Constructor for the wmap cache for the read/modify/write
29320  *		devices.
29321  *
29322  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29323  *		un	- sd_lun structure for the device.
29324  *		flag	- the km flags passed to constructor
29325  *
29326  * Return Code: 0 on success.
29327  *		-1 on failure.
29328  */
29329 
29330 /*ARGSUSED*/
29331 static int
29332 sd_wm_cache_constructor(void *wm, void *un, int flags)
29333 {
29334 	bzero(wm, sizeof (struct sd_w_map));
29335 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
29336 	return (0);
29337 }
29338 
29339 
29340 /*
29341  *    Function: sd_wm_cache_destructor()
29342  *
29343  * Description: Cache destructor for the wmap cache for the read/modify/write
29344  *		devices.
29345  *
29346  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
29347  *		un	- sd_lun structure for the device.
29348  */
29349 /*ARGSUSED*/
29350 static void
29351 sd_wm_cache_destructor(void *wm, void *un)
29352 {
29353 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
29354 }
29355 
29356 
29357 /*
29358  *    Function: sd_range_lock()
29359  *
29360  * Description: Lock the range of blocks specified as parameter to ensure
29361  *		that read, modify write is atomic and no other i/o writes
29362  *		to the same location. The range is specified in terms
29363  *		of start and end blocks. Block numbers are the actual
29364  *		media block numbers and not system.
29365  *
29366  *   Arguments: un	- sd_lun structure for the device.
29367  *		startb - The starting block number
29368  *		endb - The end block number
29369  *		typ - type of i/o - simple/read_modify_write
29370  *
29371  * Return Code: wm  - pointer to the wmap structure.
29372  *
29373  *     Context: This routine can sleep.
29374  */
29375 
29376 static struct sd_w_map *
29377 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
29378 {
29379 	struct sd_w_map *wmp = NULL;
29380 	struct sd_w_map *sl_wmp = NULL;
29381 	struct sd_w_map *tmp_wmp;
29382 	wm_state state = SD_WM_CHK_LIST;
29383 
29384 
29385 	ASSERT(un != NULL);
29386 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29387 
29388 	mutex_enter(SD_MUTEX(un));
29389 
29390 	while (state != SD_WM_DONE) {
29391 
29392 		switch (state) {
29393 		case SD_WM_CHK_LIST:
29394 			/*
29395 			 * This is the starting state. Check the wmap list
29396 			 * to see if the range is currently available.
29397 			 */
29398 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
29399 				/*
29400 				 * If this is a simple write and no rmw
29401 				 * i/o is pending then try to lock the
29402 				 * range as the range should be available.
29403 				 */
29404 				state = SD_WM_LOCK_RANGE;
29405 			} else {
29406 				tmp_wmp = sd_get_range(un, startb, endb);
29407 				if (tmp_wmp != NULL) {
29408 					if ((wmp != NULL) && ONLIST(un, wmp)) {
29409 						/*
29410 						 * Should not keep onlist wmps
29411 						 * while waiting this macro
29412 						 * will also do wmp = NULL;
29413 						 */
29414 						FREE_ONLIST_WMAP(un, wmp);
29415 					}
29416 					/*
29417 					 * sl_wmp is the wmap on which wait
29418 					 * is done, since the tmp_wmp points
29419 					 * to the inuse wmap, set sl_wmp to
29420 					 * tmp_wmp and change the state to sleep
29421 					 */
29422 					sl_wmp = tmp_wmp;
29423 					state = SD_WM_WAIT_MAP;
29424 				} else {
29425 					state = SD_WM_LOCK_RANGE;
29426 				}
29427 
29428 			}
29429 			break;
29430 
29431 		case SD_WM_LOCK_RANGE:
29432 			ASSERT(un->un_wm_cache);
29433 			/*
29434 			 * The range need to be locked, try to get a wmap.
29435 			 * First attempt it with NO_SLEEP, want to avoid a sleep
29436 			 * if possible as we will have to release the sd mutex
29437 			 * if we have to sleep.
29438 			 */
29439 			if (wmp == NULL)
29440 				wmp = kmem_cache_alloc(un->un_wm_cache,
29441 				    KM_NOSLEEP);
29442 			if (wmp == NULL) {
29443 				mutex_exit(SD_MUTEX(un));
29444 				_NOTE(DATA_READABLE_WITHOUT_LOCK
29445 				    (sd_lun::un_wm_cache))
29446 				wmp = kmem_cache_alloc(un->un_wm_cache,
29447 				    KM_SLEEP);
29448 				mutex_enter(SD_MUTEX(un));
29449 				/*
29450 				 * we released the mutex so recheck and go to
29451 				 * check list state.
29452 				 */
29453 				state = SD_WM_CHK_LIST;
29454 			} else {
29455 				/*
29456 				 * We exit out of state machine since we
29457 				 * have the wmap. Do the housekeeping first.
29458 				 * place the wmap on the wmap list if it is not
29459 				 * on it already and then set the state to done.
29460 				 */
29461 				wmp->wm_start = startb;
29462 				wmp->wm_end = endb;
29463 				wmp->wm_flags = typ | SD_WM_BUSY;
29464 				if (typ & SD_WTYPE_RMW) {
29465 					un->un_rmw_count++;
29466 				}
29467 				/*
29468 				 * If not already on the list then link
29469 				 */
29470 				if (!ONLIST(un, wmp)) {
29471 					wmp->wm_next = un->un_wm;
29472 					wmp->wm_prev = NULL;
29473 					if (wmp->wm_next)
29474 						wmp->wm_next->wm_prev = wmp;
29475 					un->un_wm = wmp;
29476 				}
29477 				state = SD_WM_DONE;
29478 			}
29479 			break;
29480 
29481 		case SD_WM_WAIT_MAP:
29482 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
29483 			/*
29484 			 * Wait is done on sl_wmp, which is set in the
29485 			 * check_list state.
29486 			 */
29487 			sl_wmp->wm_wanted_count++;
29488 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
29489 			sl_wmp->wm_wanted_count--;
29490 			/*
29491 			 * We can reuse the memory from the completed sl_wmp
29492 			 * lock range for our new lock, but only if noone is
29493 			 * waiting for it.
29494 			 */
29495 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
29496 			if (sl_wmp->wm_wanted_count == 0) {
29497 				if (wmp != NULL) {
29498 					CHK_N_FREEWMP(un, wmp);
29499 				}
29500 				wmp = sl_wmp;
29501 			}
29502 			sl_wmp = NULL;
29503 			/*
29504 			 * After waking up, need to recheck for availability of
29505 			 * range.
29506 			 */
29507 			state = SD_WM_CHK_LIST;
29508 			break;
29509 
29510 		default:
29511 			panic("sd_range_lock: "
29512 			    "Unknown state %d in sd_range_lock", state);
29513 			/*NOTREACHED*/
29514 		} /* switch(state) */
29515 
29516 	} /* while(state != SD_WM_DONE) */
29517 
29518 	mutex_exit(SD_MUTEX(un));
29519 
29520 	ASSERT(wmp != NULL);
29521 
29522 	return (wmp);
29523 }
29524 
29525 
29526 /*
29527  *    Function: sd_get_range()
29528  *
29529  * Description: Find if there any overlapping I/O to this one
29530  *		Returns the write-map of 1st such I/O, NULL otherwise.
29531  *
29532  *   Arguments: un	- sd_lun structure for the device.
29533  *		startb - The starting block number
29534  *		endb - The end block number
29535  *
29536  * Return Code: wm  - pointer to the wmap structure.
29537  */
29538 
29539 static struct sd_w_map *
29540 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
29541 {
29542 	struct sd_w_map *wmp;
29543 
29544 	ASSERT(un != NULL);
29545 
29546 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
29547 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
29548 			continue;
29549 		}
29550 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
29551 			break;
29552 		}
29553 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
29554 			break;
29555 		}
29556 	}
29557 
29558 	return (wmp);
29559 }
29560 
29561 
29562 /*
29563  *    Function: sd_free_inlist_wmap()
29564  *
29565  * Description: Unlink and free a write map struct.
29566  *
29567  *   Arguments: un      - sd_lun structure for the device.
29568  *		wmp	- sd_w_map which needs to be unlinked.
29569  */
29570 
29571 static void
29572 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
29573 {
29574 	ASSERT(un != NULL);
29575 
29576 	if (un->un_wm == wmp) {
29577 		un->un_wm = wmp->wm_next;
29578 	} else {
29579 		wmp->wm_prev->wm_next = wmp->wm_next;
29580 	}
29581 
29582 	if (wmp->wm_next) {
29583 		wmp->wm_next->wm_prev = wmp->wm_prev;
29584 	}
29585 
29586 	wmp->wm_next = wmp->wm_prev = NULL;
29587 
29588 	kmem_cache_free(un->un_wm_cache, wmp);
29589 }
29590 
29591 
29592 /*
29593  *    Function: sd_range_unlock()
29594  *
29595  * Description: Unlock the range locked by wm.
29596  *		Free write map if nobody else is waiting on it.
29597  *
29598  *   Arguments: un      - sd_lun structure for the device.
29599  *              wmp     - sd_w_map which needs to be unlinked.
29600  */
29601 
29602 static void
29603 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
29604 {
29605 	ASSERT(un != NULL);
29606 	ASSERT(wm != NULL);
29607 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29608 
29609 	mutex_enter(SD_MUTEX(un));
29610 
29611 	if (wm->wm_flags & SD_WTYPE_RMW) {
29612 		un->un_rmw_count--;
29613 	}
29614 
29615 	if (wm->wm_wanted_count) {
29616 		wm->wm_flags = 0;
29617 		/*
29618 		 * Broadcast that the wmap is available now.
29619 		 */
29620 		cv_broadcast(&wm->wm_avail);
29621 	} else {
29622 		/*
29623 		 * If no one is waiting on the map, it should be free'ed.
29624 		 */
29625 		sd_free_inlist_wmap(un, wm);
29626 	}
29627 
29628 	mutex_exit(SD_MUTEX(un));
29629 }
29630 
29631 
29632 /*
29633  *    Function: sd_read_modify_write_task
29634  *
29635  * Description: Called from a taskq thread to initiate the write phase of
29636  *		a read-modify-write request.  This is used for targets where
29637  *		un->un_sys_blocksize != un->un_tgt_blocksize.
29638  *
29639  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
29640  *
29641  *     Context: Called under taskq thread context.
29642  */
29643 
29644 static void
29645 sd_read_modify_write_task(void *arg)
29646 {
29647 	struct sd_mapblocksize_info	*bsp;
29648 	struct buf	*bp;
29649 	struct sd_xbuf	*xp;
29650 	struct sd_lun	*un;
29651 
29652 	bp = arg;	/* The bp is given in arg */
29653 	ASSERT(bp != NULL);
29654 
29655 	/* Get the pointer to the layer-private data struct */
29656 	xp = SD_GET_XBUF(bp);
29657 	ASSERT(xp != NULL);
29658 	bsp = xp->xb_private;
29659 	ASSERT(bsp != NULL);
29660 
29661 	un = SD_GET_UN(bp);
29662 	ASSERT(un != NULL);
29663 	ASSERT(!mutex_owned(SD_MUTEX(un)));
29664 
29665 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29666 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
29667 
29668 	/*
29669 	 * This is the write phase of a read-modify-write request, called
29670 	 * under the context of a taskq thread in response to the completion
29671 	 * of the read portion of the rmw request completing under interrupt
29672 	 * context. The write request must be sent from here down the iostart
29673 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
29674 	 * we use the layer index saved in the layer-private data area.
29675 	 */
29676 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
29677 
29678 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
29679 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
29680 }
29681 
29682 
29683 /*
29684  *    Function: sddump_do_read_of_rmw()
29685  *
29686  * Description: This routine will be called from sddump, If sddump is called
29687  *		with an I/O which not aligned on device blocksize boundary
29688  *		then the write has to be converted to read-modify-write.
29689  *		Do the read part here in order to keep sddump simple.
29690  *		Note - That the sd_mutex is held across the call to this
29691  *		routine.
29692  *
29693  *   Arguments: un	- sd_lun
29694  *		blkno	- block number in terms of media block size.
29695  *		nblk	- number of blocks.
29696  *		bpp	- pointer to pointer to the buf structure. On return
29697  *			from this function, *bpp points to the valid buffer
29698  *			to which the write has to be done.
29699  *
29700  * Return Code: 0 for success or errno-type return code
29701  */
29702 
29703 static int
29704 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
29705     struct buf **bpp)
29706 {
29707 	int err;
29708 	int i;
29709 	int rval;
29710 	struct buf *bp;
29711 	struct scsi_pkt *pkt = NULL;
29712 	uint32_t target_blocksize;
29713 
29714 	ASSERT(un != NULL);
29715 	ASSERT(mutex_owned(SD_MUTEX(un)));
29716 
29717 	target_blocksize = un->un_tgt_blocksize;
29718 
29719 	mutex_exit(SD_MUTEX(un));
29720 
29721 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
29722 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
29723 	if (bp == NULL) {
29724 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29725 		    "no resources for dumping; giving up");
29726 		err = ENOMEM;
29727 		goto done;
29728 	}
29729 
29730 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
29731 	    blkno, nblk);
29732 	if (rval != 0) {
29733 		scsi_free_consistent_buf(bp);
29734 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29735 		    "no resources for dumping; giving up");
29736 		err = ENOMEM;
29737 		goto done;
29738 	}
29739 
29740 	pkt->pkt_flags |= FLAG_NOINTR;
29741 
29742 	err = EIO;
29743 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
29744 
29745 		/*
29746 		 * Scsi_poll returns 0 (success) if the command completes and
29747 		 * the status block is STATUS_GOOD.  We should only check
29748 		 * errors if this condition is not true.  Even then we should
29749 		 * send our own request sense packet only if we have a check
29750 		 * condition and auto request sense has not been performed by
29751 		 * the hba.
29752 		 */
29753 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
29754 
29755 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
29756 			err = 0;
29757 			break;
29758 		}
29759 
29760 		/*
29761 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
29762 		 * no need to read RQS data.
29763 		 */
29764 		if (pkt->pkt_reason == CMD_DEV_GONE) {
29765 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
29766 			    "Error while dumping state with rmw..."
29767 			    "Device is gone\n");
29768 			break;
29769 		}
29770 
29771 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
29772 			SD_INFO(SD_LOG_DUMP, un,
29773 			    "sddump: read failed with CHECK, try # %d\n", i);
29774 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
29775 				(void) sd_send_polled_RQS(un);
29776 			}
29777 
29778 			continue;
29779 		}
29780 
29781 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
29782 			int reset_retval = 0;
29783 
29784 			SD_INFO(SD_LOG_DUMP, un,
29785 			    "sddump: read failed with BUSY, try # %d\n", i);
29786 
29787 			if (un->un_f_lun_reset_enabled == TRUE) {
29788 				reset_retval = scsi_reset(SD_ADDRESS(un),
29789 				    RESET_LUN);
29790 			}
29791 			if (reset_retval == 0) {
29792 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
29793 			}
29794 			(void) sd_send_polled_RQS(un);
29795 
29796 		} else {
29797 			SD_INFO(SD_LOG_DUMP, un,
29798 			    "sddump: read failed with 0x%x, try # %d\n",
29799 			    SD_GET_PKT_STATUS(pkt), i);
29800 			mutex_enter(SD_MUTEX(un));
29801 			sd_reset_target(un, pkt);
29802 			mutex_exit(SD_MUTEX(un));
29803 		}
29804 
29805 		/*
29806 		 * If we are not getting anywhere with lun/target resets,
29807 		 * let's reset the bus.
29808 		 */
29809 		if (i > SD_NDUMP_RETRIES / 2) {
29810 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
29811 			(void) sd_send_polled_RQS(un);
29812 		}
29813 
29814 	}
29815 	scsi_destroy_pkt(pkt);
29816 
29817 	if (err != 0) {
29818 		scsi_free_consistent_buf(bp);
29819 		*bpp = NULL;
29820 	} else {
29821 		*bpp = bp;
29822 	}
29823 
29824 done:
29825 	mutex_enter(SD_MUTEX(un));
29826 	return (err);
29827 }
29828 
29829 
29830 /*
29831  *    Function: sd_failfast_flushq
29832  *
29833  * Description: Take all bp's on the wait queue that have B_FAILFAST set
29834  *		in b_flags and move them onto the failfast queue, then kick
29835  *		off a thread to return all bp's on the failfast queue to
29836  *		their owners with an error set.
29837  *
29838  *   Arguments: un - pointer to the soft state struct for the instance.
29839  *
29840  *     Context: may execute in interrupt context.
29841  */
29842 
29843 static void
29844 sd_failfast_flushq(struct sd_lun *un)
29845 {
29846 	struct buf *bp;
29847 	struct buf *next_waitq_bp;
29848 	struct buf *prev_waitq_bp = NULL;
29849 
29850 	ASSERT(un != NULL);
29851 	ASSERT(mutex_owned(SD_MUTEX(un)));
29852 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
29853 	ASSERT(un->un_failfast_bp == NULL);
29854 
29855 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
29856 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
29857 
29858 	/*
29859 	 * Check if we should flush all bufs when entering failfast state, or
29860 	 * just those with B_FAILFAST set.
29861 	 */
29862 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
29863 		/*
29864 		 * Move *all* bp's on the wait queue to the failfast flush
29865 		 * queue, including those that do NOT have B_FAILFAST set.
29866 		 */
29867 		if (un->un_failfast_headp == NULL) {
29868 			ASSERT(un->un_failfast_tailp == NULL);
29869 			un->un_failfast_headp = un->un_waitq_headp;
29870 		} else {
29871 			ASSERT(un->un_failfast_tailp != NULL);
29872 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
29873 		}
29874 
29875 		un->un_failfast_tailp = un->un_waitq_tailp;
29876 
29877 		/* update kstat for each bp moved out of the waitq */
29878 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
29879 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
29880 		}
29881 
29882 		/* empty the waitq */
29883 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
29884 
29885 	} else {
29886 		/*
29887 		 * Go thru the wait queue, pick off all entries with
29888 		 * B_FAILFAST set, and move these onto the failfast queue.
29889 		 */
29890 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
29891 			/*
29892 			 * Save the pointer to the next bp on the wait queue,
29893 			 * so we get to it on the next iteration of this loop.
29894 			 */
29895 			next_waitq_bp = bp->av_forw;
29896 
29897 			/*
29898 			 * If this bp from the wait queue does NOT have
29899 			 * B_FAILFAST set, just move on to the next element
29900 			 * in the wait queue. Note, this is the only place
29901 			 * where it is correct to set prev_waitq_bp.
29902 			 */
29903 			if ((bp->b_flags & B_FAILFAST) == 0) {
29904 				prev_waitq_bp = bp;
29905 				continue;
29906 			}
29907 
29908 			/*
29909 			 * Remove the bp from the wait queue.
29910 			 */
29911 			if (bp == un->un_waitq_headp) {
29912 				/* The bp is the first element of the waitq. */
29913 				un->un_waitq_headp = next_waitq_bp;
29914 				if (un->un_waitq_headp == NULL) {
29915 					/* The wait queue is now empty */
29916 					un->un_waitq_tailp = NULL;
29917 				}
29918 			} else {
29919 				/*
29920 				 * The bp is either somewhere in the middle
29921 				 * or at the end of the wait queue.
29922 				 */
29923 				ASSERT(un->un_waitq_headp != NULL);
29924 				ASSERT(prev_waitq_bp != NULL);
29925 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
29926 				    == 0);
29927 				if (bp == un->un_waitq_tailp) {
29928 					/* bp is the last entry on the waitq. */
29929 					ASSERT(next_waitq_bp == NULL);
29930 					un->un_waitq_tailp = prev_waitq_bp;
29931 				}
29932 				prev_waitq_bp->av_forw = next_waitq_bp;
29933 			}
29934 			bp->av_forw = NULL;
29935 
29936 			/*
29937 			 * update kstat since the bp is moved out of
29938 			 * the waitq
29939 			 */
29940 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
29941 
29942 			/*
29943 			 * Now put the bp onto the failfast queue.
29944 			 */
29945 			if (un->un_failfast_headp == NULL) {
29946 				/* failfast queue is currently empty */
29947 				ASSERT(un->un_failfast_tailp == NULL);
29948 				un->un_failfast_headp =
29949 				    un->un_failfast_tailp = bp;
29950 			} else {
29951 				/* Add the bp to the end of the failfast q */
29952 				ASSERT(un->un_failfast_tailp != NULL);
29953 				ASSERT(un->un_failfast_tailp->b_flags &
29954 				    B_FAILFAST);
29955 				un->un_failfast_tailp->av_forw = bp;
29956 				un->un_failfast_tailp = bp;
29957 			}
29958 		}
29959 	}
29960 
29961 	/*
29962 	 * Now return all bp's on the failfast queue to their owners.
29963 	 */
29964 	while ((bp = un->un_failfast_headp) != NULL) {
29965 
29966 		un->un_failfast_headp = bp->av_forw;
29967 		if (un->un_failfast_headp == NULL) {
29968 			un->un_failfast_tailp = NULL;
29969 		}
29970 
29971 		/*
29972 		 * We want to return the bp with a failure error code, but
29973 		 * we do not want a call to sd_start_cmds() to occur here,
29974 		 * so use sd_return_failed_command_no_restart() instead of
29975 		 * sd_return_failed_command().
29976 		 */
29977 		sd_return_failed_command_no_restart(un, bp, EIO);
29978 	}
29979 
29980 	/* Flush the xbuf queues if required. */
29981 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
29982 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
29983 	}
29984 
29985 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
29986 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
29987 }
29988 
29989 
29990 /*
29991  *    Function: sd_failfast_flushq_callback
29992  *
29993  * Description: Return TRUE if the given bp meets the criteria for failfast
29994  *		flushing. Used with ddi_xbuf_flushq(9F).
29995  *
29996  *   Arguments: bp - ptr to buf struct to be examined.
29997  *
29998  *     Context: Any
29999  */
30000 
30001 static int
30002 sd_failfast_flushq_callback(struct buf *bp)
30003 {
30004 	/*
30005 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
30006 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
30007 	 */
30008 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
30009 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
30010 }
30011 
30012 
30013 
30014 /*
30015  * Function: sd_setup_next_xfer
30016  *
30017  * Description: Prepare next I/O operation using DMA_PARTIAL
30018  *
30019  */
30020 
30021 static int
30022 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
30023     struct scsi_pkt *pkt, struct sd_xbuf *xp)
30024 {
30025 	ssize_t	num_blks_not_xfered;
30026 	daddr_t	strt_blk_num;
30027 	ssize_t	bytes_not_xfered;
30028 	int	rval;
30029 
30030 	ASSERT(pkt->pkt_resid == 0);
30031 
30032 	/*
30033 	 * Calculate next block number and amount to be transferred.
30034 	 *
30035 	 * How much data NOT transfered to the HBA yet.
30036 	 */
30037 	bytes_not_xfered = xp->xb_dma_resid;
30038 
30039 	/*
30040 	 * figure how many blocks NOT transfered to the HBA yet.
30041 	 */
30042 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
30043 
30044 	/*
30045 	 * set starting block number to the end of what WAS transfered.
30046 	 */
30047 	strt_blk_num = xp->xb_blkno +
30048 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
30049 
30050 	/*
30051 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
30052 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
30053 	 * the disk mutex here.
30054 	 */
30055 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
30056 	    strt_blk_num, num_blks_not_xfered);
30057 
30058 	if (rval == 0) {
30059 
30060 		/*
30061 		 * Success.
30062 		 *
30063 		 * Adjust things if there are still more blocks to be
30064 		 * transfered.
30065 		 */
30066 		xp->xb_dma_resid = pkt->pkt_resid;
30067 		pkt->pkt_resid = 0;
30068 
30069 		return (1);
30070 	}
30071 
30072 	/*
30073 	 * There's really only one possible return value from
30074 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
30075 	 * returns NULL.
30076 	 */
30077 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
30078 
30079 	bp->b_resid = bp->b_bcount;
30080 	bp->b_flags |= B_ERROR;
30081 
30082 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
30083 	    "Error setting up next portion of DMA transfer\n");
30084 
30085 	return (0);
30086 }
30087 
30088 /*
30089  *    Function: sd_panic_for_res_conflict
30090  *
30091  * Description: Call panic with a string formatted with "Reservation Conflict"
30092  *		and a human readable identifier indicating the SD instance
30093  *		that experienced the reservation conflict.
30094  *
30095  *   Arguments: un - pointer to the soft state struct for the instance.
30096  *
30097  *     Context: may execute in interrupt context.
30098  */
30099 
30100 #define	SD_RESV_CONFLICT_FMT_LEN 40
30101 void
30102 sd_panic_for_res_conflict(struct sd_lun *un)
30103 {
30104 	char panic_str[SD_RESV_CONFLICT_FMT_LEN + MAXPATHLEN];
30105 	char path_str[MAXPATHLEN];
30106 
30107 	(void) snprintf(panic_str, sizeof (panic_str),
30108 	    "Reservation Conflict\nDisk: %s",
30109 	    ddi_pathname(SD_DEVINFO(un), path_str));
30110 
30111 	panic(panic_str);
30112 }
30113 
30114 /*
30115  * Note: The following sd_faultinjection_ioctl( ) routines implement
30116  * driver support for handling fault injection for error analysis
30117  * causing faults in multiple layers of the driver.
30118  *
30119  */
30120 
30121 #ifdef SD_FAULT_INJECTION
30122 static uint_t   sd_fault_injection_on = 0;
30123 
30124 /*
30125  *    Function: sd_faultinjection_ioctl()
30126  *
30127  * Description: This routine is the driver entry point for handling
30128  *              faultinjection ioctls to inject errors into the
30129  *              layer model
30130  *
30131  *   Arguments: cmd	- the ioctl cmd received
30132  *		arg	- the arguments from user and returns
30133  */
30134 
30135 static void
30136 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un)
30137 {
30138 	uint_t i = 0;
30139 	uint_t rval;
30140 
30141 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
30142 
30143 	mutex_enter(SD_MUTEX(un));
30144 
30145 	switch (cmd) {
30146 	case SDIOCRUN:
30147 		/* Allow pushed faults to be injected */
30148 		SD_INFO(SD_LOG_SDTEST, un,
30149 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
30150 
30151 		sd_fault_injection_on = 1;
30152 
30153 		SD_INFO(SD_LOG_IOERR, un,
30154 		    "sd_faultinjection_ioctl: run finished\n");
30155 		break;
30156 
30157 	case SDIOCSTART:
30158 		/* Start Injection Session */
30159 		SD_INFO(SD_LOG_SDTEST, un,
30160 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
30161 
30162 		sd_fault_injection_on = 0;
30163 		un->sd_injection_mask = 0xFFFFFFFF;
30164 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30165 			un->sd_fi_fifo_pkt[i] = NULL;
30166 			un->sd_fi_fifo_xb[i] = NULL;
30167 			un->sd_fi_fifo_un[i] = NULL;
30168 			un->sd_fi_fifo_arq[i] = NULL;
30169 		}
30170 		un->sd_fi_fifo_start = 0;
30171 		un->sd_fi_fifo_end = 0;
30172 
30173 		mutex_enter(&(un->un_fi_mutex));
30174 		un->sd_fi_log[0] = '\0';
30175 		un->sd_fi_buf_len = 0;
30176 		mutex_exit(&(un->un_fi_mutex));
30177 
30178 		SD_INFO(SD_LOG_IOERR, un,
30179 		    "sd_faultinjection_ioctl: start finished\n");
30180 		break;
30181 
30182 	case SDIOCSTOP:
30183 		/* Stop Injection Session */
30184 		SD_INFO(SD_LOG_SDTEST, un,
30185 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
30186 		sd_fault_injection_on = 0;
30187 		un->sd_injection_mask = 0x0;
30188 
30189 		/* Empty stray or unuseds structs from fifo */
30190 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
30191 			if (un->sd_fi_fifo_pkt[i] != NULL) {
30192 				kmem_free(un->sd_fi_fifo_pkt[i],
30193 				    sizeof (struct sd_fi_pkt));
30194 			}
30195 			if (un->sd_fi_fifo_xb[i] != NULL) {
30196 				kmem_free(un->sd_fi_fifo_xb[i],
30197 				    sizeof (struct sd_fi_xb));
30198 			}
30199 			if (un->sd_fi_fifo_un[i] != NULL) {
30200 				kmem_free(un->sd_fi_fifo_un[i],
30201 				    sizeof (struct sd_fi_un));
30202 			}
30203 			if (un->sd_fi_fifo_arq[i] != NULL) {
30204 				kmem_free(un->sd_fi_fifo_arq[i],
30205 				    sizeof (struct sd_fi_arq));
30206 			}
30207 			un->sd_fi_fifo_pkt[i] = NULL;
30208 			un->sd_fi_fifo_un[i] = NULL;
30209 			un->sd_fi_fifo_xb[i] = NULL;
30210 			un->sd_fi_fifo_arq[i] = NULL;
30211 		}
30212 		un->sd_fi_fifo_start = 0;
30213 		un->sd_fi_fifo_end = 0;
30214 
30215 		SD_INFO(SD_LOG_IOERR, un,
30216 		    "sd_faultinjection_ioctl: stop finished\n");
30217 		break;
30218 
30219 	case SDIOCINSERTPKT:
30220 		/* Store a packet struct to be pushed onto fifo */
30221 		SD_INFO(SD_LOG_SDTEST, un,
30222 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
30223 
30224 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30225 
30226 		sd_fault_injection_on = 0;
30227 
30228 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
30229 		if (un->sd_fi_fifo_pkt[i] != NULL) {
30230 			kmem_free(un->sd_fi_fifo_pkt[i],
30231 			    sizeof (struct sd_fi_pkt));
30232 		}
30233 		if (arg != (uintptr_t)NULL) {
30234 			un->sd_fi_fifo_pkt[i] =
30235 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
30236 			if (un->sd_fi_fifo_pkt[i] == NULL) {
30237 				/* Alloc failed don't store anything */
30238 				break;
30239 			}
30240 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
30241 			    sizeof (struct sd_fi_pkt), 0);
30242 			if (rval == -1) {
30243 				kmem_free(un->sd_fi_fifo_pkt[i],
30244 				    sizeof (struct sd_fi_pkt));
30245 				un->sd_fi_fifo_pkt[i] = NULL;
30246 			}
30247 		} else {
30248 			SD_INFO(SD_LOG_IOERR, un,
30249 			    "sd_faultinjection_ioctl: pkt null\n");
30250 		}
30251 		break;
30252 
30253 	case SDIOCINSERTXB:
30254 		/* Store a xb struct to be pushed onto fifo */
30255 		SD_INFO(SD_LOG_SDTEST, un,
30256 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
30257 
30258 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30259 
30260 		sd_fault_injection_on = 0;
30261 
30262 		if (un->sd_fi_fifo_xb[i] != NULL) {
30263 			kmem_free(un->sd_fi_fifo_xb[i],
30264 			    sizeof (struct sd_fi_xb));
30265 			un->sd_fi_fifo_xb[i] = NULL;
30266 		}
30267 		if (arg != (uintptr_t)NULL) {
30268 			un->sd_fi_fifo_xb[i] =
30269 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
30270 			if (un->sd_fi_fifo_xb[i] == NULL) {
30271 				/* Alloc failed don't store anything */
30272 				break;
30273 			}
30274 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
30275 			    sizeof (struct sd_fi_xb), 0);
30276 
30277 			if (rval == -1) {
30278 				kmem_free(un->sd_fi_fifo_xb[i],
30279 				    sizeof (struct sd_fi_xb));
30280 				un->sd_fi_fifo_xb[i] = NULL;
30281 			}
30282 		} else {
30283 			SD_INFO(SD_LOG_IOERR, un,
30284 			    "sd_faultinjection_ioctl: xb null\n");
30285 		}
30286 		break;
30287 
30288 	case SDIOCINSERTUN:
30289 		/* Store a un struct to be pushed onto fifo */
30290 		SD_INFO(SD_LOG_SDTEST, un,
30291 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
30292 
30293 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30294 
30295 		sd_fault_injection_on = 0;
30296 
30297 		if (un->sd_fi_fifo_un[i] != NULL) {
30298 			kmem_free(un->sd_fi_fifo_un[i],
30299 			    sizeof (struct sd_fi_un));
30300 			un->sd_fi_fifo_un[i] = NULL;
30301 		}
30302 		if (arg != (uintptr_t)NULL) {
30303 			un->sd_fi_fifo_un[i] =
30304 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
30305 			if (un->sd_fi_fifo_un[i] == NULL) {
30306 				/* Alloc failed don't store anything */
30307 				break;
30308 			}
30309 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
30310 			    sizeof (struct sd_fi_un), 0);
30311 			if (rval == -1) {
30312 				kmem_free(un->sd_fi_fifo_un[i],
30313 				    sizeof (struct sd_fi_un));
30314 				un->sd_fi_fifo_un[i] = NULL;
30315 			}
30316 
30317 		} else {
30318 			SD_INFO(SD_LOG_IOERR, un,
30319 			    "sd_faultinjection_ioctl: un null\n");
30320 		}
30321 
30322 		break;
30323 
30324 	case SDIOCINSERTARQ:
30325 		/* Store a arq struct to be pushed onto fifo */
30326 		SD_INFO(SD_LOG_SDTEST, un,
30327 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
30328 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
30329 
30330 		sd_fault_injection_on = 0;
30331 
30332 		if (un->sd_fi_fifo_arq[i] != NULL) {
30333 			kmem_free(un->sd_fi_fifo_arq[i],
30334 			    sizeof (struct sd_fi_arq));
30335 			un->sd_fi_fifo_arq[i] = NULL;
30336 		}
30337 		if (arg != (uintptr_t)NULL) {
30338 			un->sd_fi_fifo_arq[i] =
30339 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
30340 			if (un->sd_fi_fifo_arq[i] == NULL) {
30341 				/* Alloc failed don't store anything */
30342 				break;
30343 			}
30344 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
30345 			    sizeof (struct sd_fi_arq), 0);
30346 			if (rval == -1) {
30347 				kmem_free(un->sd_fi_fifo_arq[i],
30348 				    sizeof (struct sd_fi_arq));
30349 				un->sd_fi_fifo_arq[i] = NULL;
30350 			}
30351 
30352 		} else {
30353 			SD_INFO(SD_LOG_IOERR, un,
30354 			    "sd_faultinjection_ioctl: arq null\n");
30355 		}
30356 
30357 		break;
30358 
30359 	case SDIOCPUSH:
30360 		/* Push stored xb, pkt, un, and arq onto fifo */
30361 		sd_fault_injection_on = 0;
30362 
30363 		if (arg != (uintptr_t)NULL) {
30364 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
30365 			if (rval != -1 &&
30366 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30367 				un->sd_fi_fifo_end += i;
30368 			}
30369 		} else {
30370 			SD_INFO(SD_LOG_IOERR, un,
30371 			    "sd_faultinjection_ioctl: push arg null\n");
30372 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
30373 				un->sd_fi_fifo_end++;
30374 			}
30375 		}
30376 		SD_INFO(SD_LOG_IOERR, un,
30377 		    "sd_faultinjection_ioctl: push to end=%d\n",
30378 		    un->sd_fi_fifo_end);
30379 		break;
30380 
30381 	case SDIOCRETRIEVE:
30382 		/* Return buffer of log from Injection session */
30383 		SD_INFO(SD_LOG_SDTEST, un,
30384 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
30385 
30386 		sd_fault_injection_on = 0;
30387 
30388 		mutex_enter(&(un->un_fi_mutex));
30389 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
30390 		    un->sd_fi_buf_len+1, 0);
30391 		mutex_exit(&(un->un_fi_mutex));
30392 
30393 		if (rval == -1) {
30394 			/*
30395 			 * arg is possibly invalid setting
30396 			 * it to NULL for return
30397 			 */
30398 			arg = (uintptr_t)NULL;
30399 		}
30400 		break;
30401 	}
30402 
30403 	mutex_exit(SD_MUTEX(un));
30404 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: exit\n");
30405 }
30406 
30407 
30408 /*
30409  *    Function: sd_injection_log()
30410  *
30411  * Description: This routine adds buff to the already existing injection log
30412  *              for retrieval via faultinjection_ioctl for use in fault
30413  *              detection and recovery
30414  *
30415  *   Arguments: buf - the string to add to the log
30416  */
30417 
30418 static void
30419 sd_injection_log(char *buf, struct sd_lun *un)
30420 {
30421 	uint_t len;
30422 
30423 	ASSERT(un != NULL);
30424 	ASSERT(buf != NULL);
30425 
30426 	mutex_enter(&(un->un_fi_mutex));
30427 
30428 	len = min(strlen(buf), 255);
30429 	/* Add logged value to Injection log to be returned later */
30430 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
30431 		uint_t	offset = strlen((char *)un->sd_fi_log);
30432 		char *destp = (char *)un->sd_fi_log + offset;
30433 		int i;
30434 		for (i = 0; i < len; i++) {
30435 			*destp++ = *buf++;
30436 		}
30437 		un->sd_fi_buf_len += len;
30438 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
30439 	}
30440 
30441 	mutex_exit(&(un->un_fi_mutex));
30442 }
30443 
30444 
30445 /*
30446  *    Function: sd_faultinjection()
30447  *
30448  * Description: This routine takes the pkt and changes its
30449  *		content based on error injection scenerio.
30450  *
30451  *   Arguments: pktp	- packet to be changed
30452  */
30453 
30454 static void
30455 sd_faultinjection(struct scsi_pkt *pktp)
30456 {
30457 	uint_t i;
30458 	struct sd_fi_pkt *fi_pkt;
30459 	struct sd_fi_xb *fi_xb;
30460 	struct sd_fi_un *fi_un;
30461 	struct sd_fi_arq *fi_arq;
30462 	struct buf *bp;
30463 	struct sd_xbuf *xb;
30464 	struct sd_lun *un;
30465 
30466 	ASSERT(pktp != NULL);
30467 
30468 	/* pull bp xb and un from pktp */
30469 	bp = (struct buf *)pktp->pkt_private;
30470 	xb = SD_GET_XBUF(bp);
30471 	un = SD_GET_UN(bp);
30472 
30473 	ASSERT(un != NULL);
30474 
30475 	mutex_enter(SD_MUTEX(un));
30476 
30477 	SD_TRACE(SD_LOG_SDTEST, un,
30478 	    "sd_faultinjection: entry Injection from sdintr\n");
30479 
30480 	/* if injection is off return */
30481 	if (sd_fault_injection_on == 0 ||
30482 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
30483 		mutex_exit(SD_MUTEX(un));
30484 		return;
30485 	}
30486 
30487 	SD_INFO(SD_LOG_SDTEST, un,
30488 	    "sd_faultinjection: is working for copying\n");
30489 
30490 	/* take next set off fifo */
30491 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
30492 
30493 	fi_pkt = un->sd_fi_fifo_pkt[i];
30494 	fi_xb = un->sd_fi_fifo_xb[i];
30495 	fi_un = un->sd_fi_fifo_un[i];
30496 	fi_arq = un->sd_fi_fifo_arq[i];
30497 
30498 
30499 	/* set variables accordingly */
30500 	/* set pkt if it was on fifo */
30501 	if (fi_pkt != NULL) {
30502 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
30503 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
30504 		if (fi_pkt->pkt_cdbp != 0xff)
30505 			SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
30506 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
30507 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
30508 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
30509 
30510 	}
30511 	/* set xb if it was on fifo */
30512 	if (fi_xb != NULL) {
30513 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
30514 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
30515 		if (fi_xb->xb_retry_count != 0)
30516 			SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
30517 		SD_CONDSET(xb, xb, xb_victim_retry_count,
30518 		    "xb_victim_retry_count");
30519 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
30520 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
30521 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
30522 
30523 		/* copy in block data from sense */
30524 		/*
30525 		 * if (fi_xb->xb_sense_data[0] != -1) {
30526 		 *	bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
30527 		 *	SENSE_LENGTH);
30528 		 * }
30529 		 */
30530 		bcopy(fi_xb->xb_sense_data, xb->xb_sense_data, SENSE_LENGTH);
30531 
30532 		/* copy in extended sense codes */
30533 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30534 		    xb, es_code, "es_code");
30535 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30536 		    xb, es_key, "es_key");
30537 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30538 		    xb, es_add_code, "es_add_code");
30539 		SD_CONDSET(((struct scsi_extended_sense *)xb->xb_sense_data),
30540 		    xb, es_qual_code, "es_qual_code");
30541 		struct scsi_extended_sense *esp;
30542 		esp = (struct scsi_extended_sense *)xb->xb_sense_data;
30543 		esp->es_class = CLASS_EXTENDED_SENSE;
30544 	}
30545 
30546 	/* set un if it was on fifo */
30547 	if (fi_un != NULL) {
30548 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
30549 		SD_CONDSET(un, un, un_ctype, "un_ctype");
30550 		SD_CONDSET(un, un, un_reset_retry_count,
30551 		    "un_reset_retry_count");
30552 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
30553 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
30554 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
30555 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
30556 		    "un_f_allow_bus_device_reset");
30557 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
30558 
30559 	}
30560 
30561 	/* copy in auto request sense if it was on fifo */
30562 	if (fi_arq != NULL) {
30563 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
30564 	}
30565 
30566 	/* free structs */
30567 	if (un->sd_fi_fifo_pkt[i] != NULL) {
30568 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
30569 	}
30570 	if (un->sd_fi_fifo_xb[i] != NULL) {
30571 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
30572 	}
30573 	if (un->sd_fi_fifo_un[i] != NULL) {
30574 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
30575 	}
30576 	if (un->sd_fi_fifo_arq[i] != NULL) {
30577 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
30578 	}
30579 
30580 	/*
30581 	 * kmem_free does not gurantee to set to NULL
30582 	 * since we uses these to determine if we set
30583 	 * values or not lets confirm they are always
30584 	 * NULL after free
30585 	 */
30586 	un->sd_fi_fifo_pkt[i] = NULL;
30587 	un->sd_fi_fifo_un[i] = NULL;
30588 	un->sd_fi_fifo_xb[i] = NULL;
30589 	un->sd_fi_fifo_arq[i] = NULL;
30590 
30591 	un->sd_fi_fifo_start++;
30592 
30593 	mutex_exit(SD_MUTEX(un));
30594 
30595 	SD_INFO(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
30596 }
30597 
30598 #endif /* SD_FAULT_INJECTION */
30599 
30600 /*
30601  * This routine is invoked in sd_unit_attach(). Before calling it, the
30602  * properties in conf file should be processed already, and "hotpluggable"
30603  * property was processed also.
30604  *
30605  * The sd driver distinguishes 3 different type of devices: removable media,
30606  * non-removable media, and hotpluggable. Below the differences are defined:
30607  *
30608  * 1. Device ID
30609  *
30610  *     The device ID of a device is used to identify this device. Refer to
30611  *     ddi_devid_register(9F).
30612  *
30613  *     For a non-removable media disk device which can provide 0x80 or 0x83
30614  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
30615  *     device ID is created to identify this device. For other non-removable
30616  *     media devices, a default device ID is created only if this device has
30617  *     at least 2 alter cylinders. Otherwise, this device has no devid.
30618  *
30619  *     -------------------------------------------------------
30620  *     removable media   hotpluggable  | Can Have Device ID
30621  *     -------------------------------------------------------
30622  *         false             false     |     Yes
30623  *         false             true      |     Yes
30624  *         true                x       |     No
30625  *     ------------------------------------------------------
30626  *
30627  *
30628  * 2. SCSI group 4 commands
30629  *
30630  *     In SCSI specs, only some commands in group 4 command set can use
30631  *     8-byte addresses that can be used to access >2TB storage spaces.
30632  *     Other commands have no such capability. Without supporting group4,
30633  *     it is impossible to make full use of storage spaces of a disk with
30634  *     capacity larger than 2TB.
30635  *
30636  *     -----------------------------------------------
30637  *     removable media   hotpluggable   LP64  |  Group
30638  *     -----------------------------------------------
30639  *           false          false       false |   1
30640  *           false          false       true  |   4
30641  *           false          true        false |   1
30642  *           false          true        true  |   4
30643  *           true             x           x   |   5
30644  *     -----------------------------------------------
30645  *
30646  *
30647  * 3. Check for VTOC Label
30648  *
30649  *     If a direct-access disk has no EFI label, sd will check if it has a
30650  *     valid VTOC label. Now, sd also does that check for removable media
30651  *     and hotpluggable devices.
30652  *
30653  *     --------------------------------------------------------------
30654  *     Direct-Access   removable media    hotpluggable |  Check Label
30655  *     -------------------------------------------------------------
30656  *         false          false           false        |   No
30657  *         false          false           true         |   No
30658  *         false          true            false        |   Yes
30659  *         false          true            true         |   Yes
30660  *         true            x                x          |   Yes
30661  *     --------------------------------------------------------------
30662  *
30663  *
30664  * 4. Building default VTOC label
30665  *
30666  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
30667  *     If those devices have no valid VTOC label, sd(4D) will attempt to
30668  *     create default VTOC for them. Currently sd creates default VTOC label
30669  *     for all devices on x86 platform (VTOC_16), but only for removable
30670  *     media devices on SPARC (VTOC_8).
30671  *
30672  *     -----------------------------------------------------------
30673  *       removable media hotpluggable platform   |   Default Label
30674  *     -----------------------------------------------------------
30675  *             false          false    sparc     |     No
30676  *             false          true      x86      |     Yes
30677  *             false          true     sparc     |     Yes
30678  *             true             x        x       |     Yes
30679  *     ----------------------------------------------------------
30680  *
30681  *
30682  * 5. Supported blocksizes of target devices
30683  *
30684  *     Sd supports non-512-byte blocksize for removable media devices only.
30685  *     For other devices, only 512-byte blocksize is supported. This may be
30686  *     changed in near future because some RAID devices require non-512-byte
30687  *     blocksize
30688  *
30689  *     -----------------------------------------------------------
30690  *     removable media    hotpluggable    | non-512-byte blocksize
30691  *     -----------------------------------------------------------
30692  *           false          false         |   No
30693  *           false          true          |   No
30694  *           true             x           |   Yes
30695  *     -----------------------------------------------------------
30696  *
30697  *
30698  * 6. Automatic mount & unmount
30699  *
30700  *     sd(4D) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
30701  *     if a device is removable media device. It return 1 for removable media
30702  *     devices, and 0 for others.
30703  *
30704  *     The automatic mounting subsystem should distinguish between the types
30705  *     of devices and apply automounting policies to each.
30706  *
30707  *
30708  * 7. fdisk partition management
30709  *
30710  *     Fdisk is traditional partition method on x86 platform. sd(4D) driver
30711  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
30712  *     doesn't support fdisk partitions at all. Note: pcfs(4FS) can recognize
30713  *     fdisk partitions on both x86 and SPARC platform.
30714  *
30715  *     -----------------------------------------------------------
30716  *       platform   removable media  USB/1394  |  fdisk supported
30717  *     -----------------------------------------------------------
30718  *        x86         X               X        |       true
30719  *     ------------------------------------------------------------
30720  *        sparc       X               X        |       false
30721  *     ------------------------------------------------------------
30722  *
30723  *
30724  * 8. MBOOT/MBR
30725  *
30726  *     Although sd(4D) doesn't support fdisk on SPARC platform, it does support
30727  *     read/write mboot for removable media devices on sparc platform.
30728  *
30729  *     -----------------------------------------------------------
30730  *       platform   removable media  USB/1394  |  mboot supported
30731  *     -----------------------------------------------------------
30732  *        x86         X               X        |       true
30733  *     ------------------------------------------------------------
30734  *        sparc      false           false     |       false
30735  *        sparc      false           true      |       true
30736  *        sparc      true            false     |       true
30737  *        sparc      true            true      |       true
30738  *     ------------------------------------------------------------
30739  *
30740  *
30741  * 9.  error handling during opening device
30742  *
30743  *     If failed to open a disk device, an errno is returned. For some kinds
30744  *     of errors, different errno is returned depending on if this device is
30745  *     a removable media device. This brings USB/1394 hard disks in line with
30746  *     expected hard disk behavior. It is not expected that this breaks any
30747  *     application.
30748  *
30749  *     ------------------------------------------------------
30750  *       removable media    hotpluggable   |  errno
30751  *     ------------------------------------------------------
30752  *             false          false        |   EIO
30753  *             false          true         |   EIO
30754  *             true             x          |   ENXIO
30755  *     ------------------------------------------------------
30756  *
30757  *
30758  * 11. ioctls: DKIOCEJECT, CDROMEJECT
30759  *
30760  *     These IOCTLs are applicable only to removable media devices.
30761  *
30762  *     -----------------------------------------------------------
30763  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
30764  *     -----------------------------------------------------------
30765  *             false          false        |     No
30766  *             false          true         |     No
30767  *             true            x           |     Yes
30768  *     -----------------------------------------------------------
30769  *
30770  *
30771  * 12. Kstats for partitions
30772  *
30773  *     sd creates partition kstat for non-removable media devices. USB and
30774  *     Firewire hard disks now have partition kstats
30775  *
30776  *      ------------------------------------------------------
30777  *       removable media    hotpluggable   |   kstat
30778  *      ------------------------------------------------------
30779  *             false          false        |    Yes
30780  *             false          true         |    Yes
30781  *             true             x          |    No
30782  *       ------------------------------------------------------
30783  *
30784  *
30785  * 13. Removable media & hotpluggable properties
30786  *
30787  *     Sd driver creates a "removable-media" property for removable media
30788  *     devices. Parent nexus drivers create a "hotpluggable" property if
30789  *     it supports hotplugging.
30790  *
30791  *     ---------------------------------------------------------------------
30792  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
30793  *     ---------------------------------------------------------------------
30794  *       false            false       |    No                   No
30795  *       false            true        |    No                   Yes
30796  *       true             false       |    Yes                  No
30797  *       true             true        |    Yes                  Yes
30798  *     ---------------------------------------------------------------------
30799  *
30800  *
30801  * 14. Power Management
30802  *
30803  *     sd only power manages removable media devices or devices that support
30804  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
30805  *
30806  *     A parent nexus that supports hotplugging can also set "pm-capable"
30807  *     if the disk can be power managed.
30808  *
30809  *     ------------------------------------------------------------
30810  *       removable media hotpluggable pm-capable  |   power manage
30811  *     ------------------------------------------------------------
30812  *             false          false     false     |     No
30813  *             false          false     true      |     Yes
30814  *             false          true      false     |     No
30815  *             false          true      true      |     Yes
30816  *             true             x        x        |     Yes
30817  *     ------------------------------------------------------------
30818  *
30819  *      USB and firewire hard disks can now be power managed independently
30820  *      of the framebuffer
30821  *
30822  *
30823  * 15. Support for USB disks with capacity larger than 1TB
30824  *
30825  *     Currently, sd doesn't permit a fixed disk device with capacity
30826  *     larger than 1TB to be used in a 32-bit operating system environment.
30827  *     However, sd doesn't do that for removable media devices. Instead, it
30828  *     assumes that removable media devices cannot have a capacity larger
30829  *     than 1TB. Therefore, using those devices on 32-bit system is partially
30830  *     supported, which can cause some unexpected results.
30831  *
30832  *     ---------------------------------------------------------------------
30833  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
30834  *     ---------------------------------------------------------------------
30835  *             false          false  |   true         |     no
30836  *             false          true   |   true         |     no
30837  *             true           false  |   true         |     Yes
30838  *             true           true   |   true         |     Yes
30839  *     ---------------------------------------------------------------------
30840  *
30841  *
30842  * 16. Check write-protection at open time
30843  *
30844  *     When a removable media device is being opened for writing without NDELAY
30845  *     flag, sd will check if this device is writable. If attempting to open
30846  *     without NDELAY flag a write-protected device, this operation will abort.
30847  *
30848  *     ------------------------------------------------------------
30849  *       removable media    USB/1394   |   WP Check
30850  *     ------------------------------------------------------------
30851  *             false          false    |     No
30852  *             false          true     |     No
30853  *             true           false    |     Yes
30854  *             true           true     |     Yes
30855  *     ------------------------------------------------------------
30856  *
30857  *
30858  * 17. syslog when corrupted VTOC is encountered
30859  *
30860  *      Currently, if an invalid VTOC is encountered, sd only print syslog
30861  *      for fixed SCSI disks.
30862  *     ------------------------------------------------------------
30863  *       removable media    USB/1394   |   print syslog
30864  *     ------------------------------------------------------------
30865  *             false          false    |     Yes
30866  *             false          true     |     No
30867  *             true           false    |     No
30868  *             true           true     |     No
30869  *     ------------------------------------------------------------
30870  */
30871 static void
30872 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
30873 {
30874 	int	pm_cap;
30875 
30876 	ASSERT(un->un_sd);
30877 	ASSERT(un->un_sd->sd_inq);
30878 
30879 	/*
30880 	 * Enable SYNC CACHE support for all devices.
30881 	 */
30882 	un->un_f_sync_cache_supported = TRUE;
30883 
30884 	/*
30885 	 * Set the sync cache required flag to false.
30886 	 * This would ensure that there is no SYNC CACHE
30887 	 * sent when there are no writes
30888 	 */
30889 	un->un_f_sync_cache_required = FALSE;
30890 
30891 	if (un->un_sd->sd_inq->inq_rmb) {
30892 		/*
30893 		 * The media of this device is removable. And for this kind
30894 		 * of devices, it is possible to change medium after opening
30895 		 * devices. Thus we should support this operation.
30896 		 */
30897 		un->un_f_has_removable_media = TRUE;
30898 
30899 		/*
30900 		 * support non-512-byte blocksize of removable media devices
30901 		 */
30902 		un->un_f_non_devbsize_supported = TRUE;
30903 
30904 		/*
30905 		 * Assume that all removable media devices support DOOR_LOCK
30906 		 */
30907 		un->un_f_doorlock_supported = TRUE;
30908 
30909 		/*
30910 		 * For a removable media device, it is possible to be opened
30911 		 * with NDELAY flag when there is no media in drive, in this
30912 		 * case we don't care if device is writable. But if without
30913 		 * NDELAY flag, we need to check if media is write-protected.
30914 		 */
30915 		un->un_f_chk_wp_open = TRUE;
30916 
30917 		/*
30918 		 * need to start a SCSI watch thread to monitor media state,
30919 		 * when media is being inserted or ejected, notify syseventd.
30920 		 */
30921 		un->un_f_monitor_media_state = TRUE;
30922 
30923 		/*
30924 		 * Some devices don't support START_STOP_UNIT command.
30925 		 * Therefore, we'd better check if a device supports it
30926 		 * before sending it.
30927 		 */
30928 		un->un_f_check_start_stop = TRUE;
30929 
30930 		/*
30931 		 * support eject media ioctl:
30932 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
30933 		 */
30934 		un->un_f_eject_media_supported = TRUE;
30935 
30936 		/*
30937 		 * Because many removable-media devices don't support
30938 		 * LOG_SENSE, we couldn't use this command to check if
30939 		 * a removable media device support power-management.
30940 		 * We assume that they support power-management via
30941 		 * START_STOP_UNIT command and can be spun up and down
30942 		 * without limitations.
30943 		 */
30944 		un->un_f_pm_supported = TRUE;
30945 
30946 		/*
30947 		 * Need to create a zero length (Boolean) property
30948 		 * removable-media for the removable media devices.
30949 		 * Note that the return value of the property is not being
30950 		 * checked, since if unable to create the property
30951 		 * then do not want the attach to fail altogether. Consistent
30952 		 * with other property creation in attach.
30953 		 */
30954 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
30955 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
30956 
30957 	} else {
30958 		/*
30959 		 * create device ID for device
30960 		 */
30961 		un->un_f_devid_supported = TRUE;
30962 
30963 		/*
30964 		 * Spin up non-removable-media devices once it is attached
30965 		 */
30966 		un->un_f_attach_spinup = TRUE;
30967 
30968 		/*
30969 		 * According to SCSI specification, Sense data has two kinds of
30970 		 * format: fixed format, and descriptor format. At present, we
30971 		 * don't support descriptor format sense data for removable
30972 		 * media.
30973 		 */
30974 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
30975 			un->un_f_descr_format_supported = TRUE;
30976 		}
30977 
30978 		/*
30979 		 * kstats are created only for non-removable media devices.
30980 		 *
30981 		 * Set this in sd.conf to 0 in order to disable kstats.  The
30982 		 * default is 1, so they are enabled by default.
30983 		 */
30984 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
30985 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
30986 		    "enable-partition-kstats", 1));
30987 
30988 		/*
30989 		 * Check if HBA has set the "pm-capable" property.
30990 		 * If "pm-capable" exists and is non-zero then we can
30991 		 * power manage the device without checking the start/stop
30992 		 * cycle count log sense page.
30993 		 *
30994 		 * If "pm-capable" exists and is set to be false (0),
30995 		 * then we should not power manage the device.
30996 		 *
30997 		 * If "pm-capable" doesn't exist then pm_cap will
30998 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
30999 		 * sd will check the start/stop cycle count log sense page
31000 		 * and power manage the device if the cycle count limit has
31001 		 * not been exceeded.
31002 		 */
31003 		pm_cap = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
31004 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
31005 		if (SD_PM_CAPABLE_IS_UNDEFINED(pm_cap)) {
31006 			un->un_f_log_sense_supported = TRUE;
31007 			if (!un->un_f_power_condition_disabled &&
31008 			    SD_INQUIRY(un)->inq_ansi == 6) {
31009 				un->un_f_power_condition_supported = TRUE;
31010 			}
31011 		} else {
31012 			/*
31013 			 * pm-capable property exists.
31014 			 *
31015 			 * Convert "TRUE" values for pm_cap to
31016 			 * SD_PM_CAPABLE_IS_TRUE to make it easier to check
31017 			 * later. "TRUE" values are any values defined in
31018 			 * inquiry.h.
31019 			 */
31020 			if (SD_PM_CAPABLE_IS_FALSE(pm_cap)) {
31021 				un->un_f_log_sense_supported = FALSE;
31022 			} else {
31023 				/* SD_PM_CAPABLE_IS_TRUE case */
31024 				un->un_f_pm_supported = TRUE;
31025 				if (!un->un_f_power_condition_disabled &&
31026 				    SD_PM_CAPABLE_IS_SPC_4(pm_cap)) {
31027 					un->un_f_power_condition_supported =
31028 					    TRUE;
31029 				}
31030 				if (SD_PM_CAP_LOG_SUPPORTED(pm_cap)) {
31031 					un->un_f_log_sense_supported = TRUE;
31032 					un->un_f_pm_log_sense_smart =
31033 					    SD_PM_CAP_SMART_LOG(pm_cap);
31034 				}
31035 			}
31036 
31037 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
31038 			    "sd_unit_attach: un:0x%p pm-capable "
31039 			    "property set to %d.\n", un, un->un_f_pm_supported);
31040 		}
31041 	}
31042 
31043 	if (un->un_f_is_hotpluggable) {
31044 
31045 		/*
31046 		 * Have to watch hotpluggable devices as well, since
31047 		 * that's the only way for userland applications to
31048 		 * detect hot removal while device is busy/mounted.
31049 		 */
31050 		un->un_f_monitor_media_state = TRUE;
31051 
31052 		un->un_f_check_start_stop = TRUE;
31053 
31054 	}
31055 }
31056 
31057 /*
31058  * sd_tg_rdwr:
31059  * Provides rdwr access for cmlb via sd_tgops. The start_block is
31060  * in sys block size, req_length in bytes.
31061  *
31062  */
31063 static int
31064 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
31065     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
31066 {
31067 	struct sd_lun *un;
31068 	int path_flag = (int)(uintptr_t)tg_cookie;
31069 	char *dkl = NULL;
31070 	diskaddr_t real_addr = start_block;
31071 	diskaddr_t first_byte, end_block;
31072 
31073 	size_t	buffer_size = reqlength;
31074 	int rval = 0;
31075 	diskaddr_t	cap;
31076 	uint32_t	lbasize;
31077 	sd_ssc_t	*ssc;
31078 
31079 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
31080 	if (un == NULL)
31081 		return (ENXIO);
31082 
31083 	if (cmd != TG_READ && cmd != TG_WRITE)
31084 		return (EINVAL);
31085 
31086 	ssc = sd_ssc_init(un);
31087 	mutex_enter(SD_MUTEX(un));
31088 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
31089 		mutex_exit(SD_MUTEX(un));
31090 		rval = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
31091 		    &lbasize, path_flag);
31092 		if (rval != 0)
31093 			goto done1;
31094 		mutex_enter(SD_MUTEX(un));
31095 		sd_update_block_info(un, lbasize, cap);
31096 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
31097 			mutex_exit(SD_MUTEX(un));
31098 			rval = EIO;
31099 			goto done;
31100 		}
31101 	}
31102 
31103 	if (NOT_DEVBSIZE(un)) {
31104 		/*
31105 		 * sys_blocksize != tgt_blocksize, need to re-adjust
31106 		 * blkno and save the index to beginning of dk_label
31107 		 */
31108 		first_byte  = SD_SYSBLOCKS2BYTES(start_block);
31109 		real_addr = first_byte / un->un_tgt_blocksize;
31110 
31111 		end_block = (first_byte + reqlength +
31112 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
31113 
31114 		/* round up buffer size to multiple of target block size */
31115 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
31116 
31117 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
31118 		    "label_addr: 0x%x allocation size: 0x%x\n",
31119 		    real_addr, buffer_size);
31120 
31121 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
31122 		    (reqlength % un->un_tgt_blocksize) != 0)
31123 			/* the request is not aligned */
31124 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
31125 	}
31126 
31127 	/*
31128 	 * The MMC standard allows READ CAPACITY to be
31129 	 * inaccurate by a bounded amount (in the interest of
31130 	 * response latency).  As a result, failed READs are
31131 	 * commonplace (due to the reading of metadata and not
31132 	 * data). Depending on the per-Vendor/drive Sense data,
31133 	 * the failed READ can cause many (unnecessary) retries.
31134 	 */
31135 
31136 	if (ISCD(un) && (cmd == TG_READ) &&
31137 	    (un->un_f_blockcount_is_valid == TRUE) &&
31138 	    ((start_block == (un->un_blockcount - 1)) ||
31139 	    (start_block == (un->un_blockcount - 2)))) {
31140 			path_flag = SD_PATH_DIRECT_PRIORITY;
31141 	}
31142 
31143 	mutex_exit(SD_MUTEX(un));
31144 	if (cmd == TG_READ) {
31145 		rval = sd_send_scsi_READ(ssc, (dkl != NULL) ? dkl : bufaddr,
31146 		    buffer_size, real_addr, path_flag);
31147 		if (dkl != NULL)
31148 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
31149 			    real_addr), bufaddr, reqlength);
31150 	} else {
31151 		if (dkl) {
31152 			rval = sd_send_scsi_READ(ssc, dkl, buffer_size,
31153 			    real_addr, path_flag);
31154 			if (rval) {
31155 				goto done1;
31156 			}
31157 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
31158 			    real_addr), reqlength);
31159 		}
31160 		rval = sd_send_scsi_WRITE(ssc, (dkl != NULL) ? dkl : bufaddr,
31161 		    buffer_size, real_addr, path_flag);
31162 	}
31163 
31164 done1:
31165 	if (dkl != NULL)
31166 		kmem_free(dkl, buffer_size);
31167 
31168 	if (rval != 0) {
31169 		if (rval == EIO)
31170 			sd_ssc_assessment(ssc, SD_FMT_STATUS_CHECK);
31171 		else
31172 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
31173 	}
31174 done:
31175 	sd_ssc_fini(ssc);
31176 	return (rval);
31177 }
31178 
31179 
31180 static int
31181 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
31182 {
31183 
31184 	struct sd_lun *un;
31185 	diskaddr_t	cap;
31186 	uint32_t	lbasize;
31187 	int		path_flag = (int)(uintptr_t)tg_cookie;
31188 	int		ret = 0;
31189 
31190 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
31191 	if (un == NULL)
31192 		return (ENXIO);
31193 
31194 	switch (cmd) {
31195 	case TG_GETPHYGEOM:
31196 	case TG_GETVIRTGEOM:
31197 	case TG_GETCAPACITY:
31198 	case TG_GETBLOCKSIZE:
31199 		mutex_enter(SD_MUTEX(un));
31200 
31201 		if ((un->un_f_blockcount_is_valid == TRUE) &&
31202 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
31203 			cap = un->un_blockcount;
31204 			lbasize = un->un_tgt_blocksize;
31205 			mutex_exit(SD_MUTEX(un));
31206 		} else {
31207 			sd_ssc_t	*ssc;
31208 			mutex_exit(SD_MUTEX(un));
31209 			ssc = sd_ssc_init(un);
31210 			ret = sd_send_scsi_READ_CAPACITY(ssc, (uint64_t *)&cap,
31211 			    &lbasize, path_flag);
31212 			if (ret != 0) {
31213 				if (ret == EIO)
31214 					sd_ssc_assessment(ssc,
31215 					    SD_FMT_STATUS_CHECK);
31216 				else
31217 					sd_ssc_assessment(ssc,
31218 					    SD_FMT_IGNORE);
31219 				sd_ssc_fini(ssc);
31220 				return (ret);
31221 			}
31222 			sd_ssc_fini(ssc);
31223 			mutex_enter(SD_MUTEX(un));
31224 			sd_update_block_info(un, lbasize, cap);
31225 			if ((un->un_f_blockcount_is_valid == FALSE) ||
31226 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
31227 				mutex_exit(SD_MUTEX(un));
31228 				return (EIO);
31229 			}
31230 			mutex_exit(SD_MUTEX(un));
31231 		}
31232 
31233 		if (cmd == TG_GETCAPACITY) {
31234 			*(diskaddr_t *)arg = cap;
31235 			return (0);
31236 		}
31237 
31238 		if (cmd == TG_GETBLOCKSIZE) {
31239 			*(uint32_t *)arg = lbasize;
31240 			return (0);
31241 		}
31242 
31243 		if (cmd == TG_GETPHYGEOM)
31244 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
31245 			    cap, lbasize, path_flag);
31246 		else
31247 			/* TG_GETVIRTGEOM */
31248 			ret = sd_get_virtual_geometry(un,
31249 			    (cmlb_geom_t *)arg, cap, lbasize);
31250 
31251 		return (ret);
31252 
31253 	case TG_GETATTR:
31254 		mutex_enter(SD_MUTEX(un));
31255 		((tg_attribute_t *)arg)->media_is_writable =
31256 		    un->un_f_mmc_writable_media;
31257 		((tg_attribute_t *)arg)->media_is_solid_state =
31258 		    un->un_f_is_solid_state;
31259 		((tg_attribute_t *)arg)->media_is_rotational =
31260 		    un->un_f_is_rotational;
31261 		mutex_exit(SD_MUTEX(un));
31262 		return (0);
31263 	default:
31264 		return (ENOTTY);
31265 
31266 	}
31267 }
31268 
31269 /*
31270  *    Function: sd_ssc_ereport_post
31271  *
31272  * Description: Will be called when SD driver need to post an ereport.
31273  *
31274  *    Context: Kernel thread or interrupt context.
31275  */
31276 
31277 #define	DEVID_IF_KNOWN(d) "devid", DATA_TYPE_STRING, (d) ? (d) : "unknown"
31278 
31279 static void
31280 sd_ssc_ereport_post(sd_ssc_t *ssc, enum sd_driver_assessment drv_assess)
31281 {
31282 	int uscsi_path_instance = 0;
31283 	uchar_t	uscsi_pkt_reason;
31284 	uint32_t uscsi_pkt_state;
31285 	uint32_t uscsi_pkt_statistics;
31286 	uint64_t uscsi_ena;
31287 	uchar_t op_code;
31288 	uint8_t *sensep;
31289 	union scsi_cdb *cdbp;
31290 	uint_t cdblen = 0;
31291 	uint_t senlen = 0;
31292 	struct sd_lun *un;
31293 	dev_info_t *dip;
31294 	char *devid;
31295 	int ssc_invalid_flags = SSC_FLAGS_INVALID_PKT_REASON |
31296 	    SSC_FLAGS_INVALID_STATUS |
31297 	    SSC_FLAGS_INVALID_SENSE |
31298 	    SSC_FLAGS_INVALID_DATA;
31299 	char assessment[16];
31300 
31301 	ASSERT(ssc != NULL);
31302 	ASSERT(ssc->ssc_uscsi_cmd != NULL);
31303 	ASSERT(ssc->ssc_uscsi_info != NULL);
31304 
31305 	un = ssc->ssc_un;
31306 	ASSERT(un != NULL);
31307 
31308 	dip = un->un_sd->sd_dev;
31309 
31310 	/*
31311 	 * Get the devid:
31312 	 *	devid will only be passed to non-transport error reports.
31313 	 */
31314 	devid = DEVI(dip)->devi_devid_str;
31315 
31316 	/*
31317 	 * If we are syncing or dumping, the command will not be executed
31318 	 * so we bypass this situation.
31319 	 */
31320 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
31321 	    (un->un_state == SD_STATE_DUMPING))
31322 		return;
31323 
31324 	uscsi_pkt_reason = ssc->ssc_uscsi_info->ui_pkt_reason;
31325 	uscsi_path_instance = ssc->ssc_uscsi_cmd->uscsi_path_instance;
31326 	uscsi_pkt_state = ssc->ssc_uscsi_info->ui_pkt_state;
31327 	uscsi_pkt_statistics = ssc->ssc_uscsi_info->ui_pkt_statistics;
31328 	uscsi_ena = ssc->ssc_uscsi_info->ui_ena;
31329 
31330 	sensep = (uint8_t *)ssc->ssc_uscsi_cmd->uscsi_rqbuf;
31331 	cdbp = (union scsi_cdb *)ssc->ssc_uscsi_cmd->uscsi_cdb;
31332 
31333 	/* In rare cases, EG:DOORLOCK, the cdb could be NULL */
31334 	if (cdbp == NULL) {
31335 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
31336 		    "sd_ssc_ereport_post meet empty cdb\n");
31337 		return;
31338 	}
31339 
31340 	op_code = cdbp->scc_cmd;
31341 
31342 	cdblen = (int)ssc->ssc_uscsi_cmd->uscsi_cdblen;
31343 	senlen = (int)(ssc->ssc_uscsi_cmd->uscsi_rqlen -
31344 	    ssc->ssc_uscsi_cmd->uscsi_rqresid);
31345 
31346 	if (senlen > 0)
31347 		ASSERT(sensep != NULL);
31348 
31349 	/*
31350 	 * Initialize drv_assess to corresponding values.
31351 	 * SD_FM_DRV_FATAL will be mapped to "fail" or "fatal" depending
31352 	 * on the sense-key returned back.
31353 	 */
31354 	switch (drv_assess) {
31355 		case SD_FM_DRV_RECOVERY:
31356 			(void) sprintf(assessment, "%s", "recovered");
31357 			break;
31358 		case SD_FM_DRV_RETRY:
31359 			(void) sprintf(assessment, "%s", "retry");
31360 			break;
31361 		case SD_FM_DRV_NOTICE:
31362 			(void) sprintf(assessment, "%s", "info");
31363 			break;
31364 		case SD_FM_DRV_FATAL:
31365 		default:
31366 			(void) sprintf(assessment, "%s", "unknown");
31367 	}
31368 	/*
31369 	 * If drv_assess == SD_FM_DRV_RECOVERY, this should be a recovered
31370 	 * command, we will post ereport.io.scsi.cmd.disk.recovered.
31371 	 * driver-assessment will always be "recovered" here.
31372 	 */
31373 	if (drv_assess == SD_FM_DRV_RECOVERY) {
31374 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance, NULL,
31375 		    "cmd.disk.recovered", uscsi_ena, devid, NULL,
31376 		    DDI_NOSLEEP, NULL,
31377 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31378 		    DEVID_IF_KNOWN(devid),
31379 		    "driver-assessment", DATA_TYPE_STRING, assessment,
31380 		    "op-code", DATA_TYPE_UINT8, op_code,
31381 		    "cdb", DATA_TYPE_UINT8_ARRAY,
31382 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31383 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31384 		    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31385 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
31386 		    NULL);
31387 		return;
31388 	}
31389 
31390 	/*
31391 	 * If there is un-expected/un-decodable data, we should post
31392 	 * ereport.io.scsi.cmd.disk.dev.uderr.
31393 	 * driver-assessment will be set based on parameter drv_assess.
31394 	 * SSC_FLAGS_INVALID_SENSE - invalid sense data sent back.
31395 	 * SSC_FLAGS_INVALID_PKT_REASON - invalid pkt-reason encountered.
31396 	 * SSC_FLAGS_INVALID_STATUS - invalid stat-code encountered.
31397 	 * SSC_FLAGS_INVALID_DATA - invalid data sent back.
31398 	 */
31399 	if (ssc->ssc_flags & ssc_invalid_flags) {
31400 		if (ssc->ssc_flags & SSC_FLAGS_INVALID_SENSE) {
31401 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31402 			    NULL, "cmd.disk.dev.uderr", uscsi_ena, devid,
31403 			    NULL, DDI_NOSLEEP, NULL,
31404 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31405 			    DEVID_IF_KNOWN(devid),
31406 			    "driver-assessment", DATA_TYPE_STRING,
31407 			    drv_assess == SD_FM_DRV_FATAL ?
31408 			    "fail" : assessment,
31409 			    "op-code", DATA_TYPE_UINT8, op_code,
31410 			    "cdb", DATA_TYPE_UINT8_ARRAY,
31411 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31412 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31413 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31414 			    "pkt-stats", DATA_TYPE_UINT32,
31415 			    uscsi_pkt_statistics,
31416 			    "stat-code", DATA_TYPE_UINT8,
31417 			    ssc->ssc_uscsi_cmd->uscsi_status,
31418 			    "un-decode-info", DATA_TYPE_STRING,
31419 			    ssc->ssc_info,
31420 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
31421 			    senlen, sensep,
31422 			    NULL);
31423 		} else {
31424 			/*
31425 			 * For other type of invalid data, the
31426 			 * un-decode-value field would be empty because the
31427 			 * un-decodable content could be seen from upper
31428 			 * level payload or inside un-decode-info.
31429 			 */
31430 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31431 			    NULL,
31432 			    "cmd.disk.dev.uderr", uscsi_ena, devid,
31433 			    NULL, DDI_NOSLEEP, NULL,
31434 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31435 			    DEVID_IF_KNOWN(devid),
31436 			    "driver-assessment", DATA_TYPE_STRING,
31437 			    drv_assess == SD_FM_DRV_FATAL ?
31438 			    "fail" : assessment,
31439 			    "op-code", DATA_TYPE_UINT8, op_code,
31440 			    "cdb", DATA_TYPE_UINT8_ARRAY,
31441 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31442 			    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31443 			    "pkt-state", DATA_TYPE_UINT32, uscsi_pkt_state,
31444 			    "pkt-stats", DATA_TYPE_UINT32,
31445 			    uscsi_pkt_statistics,
31446 			    "stat-code", DATA_TYPE_UINT8,
31447 			    ssc->ssc_uscsi_cmd->uscsi_status,
31448 			    "un-decode-info", DATA_TYPE_STRING,
31449 			    ssc->ssc_info,
31450 			    "un-decode-value", DATA_TYPE_UINT8_ARRAY,
31451 			    0, NULL,
31452 			    NULL);
31453 		}
31454 		ssc->ssc_flags &= ~ssc_invalid_flags;
31455 		return;
31456 	}
31457 
31458 	if (uscsi_pkt_reason != CMD_CMPLT ||
31459 	    (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)) {
31460 		/*
31461 		 * pkt-reason != CMD_CMPLT or SSC_FLAGS_TRAN_ABORT was
31462 		 * set inside sd_start_cmds due to errors(bad packet or
31463 		 * fatal transport error), we should take it as a
31464 		 * transport error, so we post ereport.io.scsi.cmd.disk.tran.
31465 		 * driver-assessment will be set based on drv_assess.
31466 		 * We will set devid to NULL because it is a transport
31467 		 * error.
31468 		 */
31469 		if (ssc->ssc_flags & SSC_FLAGS_TRAN_ABORT)
31470 			ssc->ssc_flags &= ~SSC_FLAGS_TRAN_ABORT;
31471 
31472 		scsi_fm_ereport_post(un->un_sd, uscsi_path_instance, NULL,
31473 		    "cmd.disk.tran", uscsi_ena, NULL, NULL, DDI_NOSLEEP, NULL,
31474 		    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31475 		    DEVID_IF_KNOWN(devid),
31476 		    "driver-assessment", DATA_TYPE_STRING,
31477 		    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31478 		    "op-code", DATA_TYPE_UINT8, op_code,
31479 		    "cdb", DATA_TYPE_UINT8_ARRAY,
31480 		    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31481 		    "pkt-reason", DATA_TYPE_UINT8, uscsi_pkt_reason,
31482 		    "pkt-state", DATA_TYPE_UINT8, uscsi_pkt_state,
31483 		    "pkt-stats", DATA_TYPE_UINT32, uscsi_pkt_statistics,
31484 		    NULL);
31485 	} else {
31486 		/*
31487 		 * If we got here, we have a completed command, and we need
31488 		 * to further investigate the sense data to see what kind
31489 		 * of ereport we should post.
31490 		 * No ereport is needed if sense-key is KEY_RECOVERABLE_ERROR
31491 		 * and asc/ascq is "ATA PASS-THROUGH INFORMATION AVAILABLE".
31492 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.merr if sense-key is
31493 		 * KEY_MEDIUM_ERROR.
31494 		 * Post ereport.io.scsi.cmd.disk.dev.rqs.derr otherwise.
31495 		 * driver-assessment will be set based on the parameter
31496 		 * drv_assess.
31497 		 */
31498 		if (senlen > 0) {
31499 			/*
31500 			 * Here we have sense data available.
31501 			 */
31502 			uint8_t sense_key = scsi_sense_key(sensep);
31503 			uint8_t sense_asc = scsi_sense_asc(sensep);
31504 			uint8_t sense_ascq = scsi_sense_ascq(sensep);
31505 
31506 			if (sense_key == KEY_RECOVERABLE_ERROR &&
31507 			    sense_asc == 0x00 && sense_ascq == 0x1d)
31508 				return;
31509 
31510 			if (sense_key == KEY_MEDIUM_ERROR) {
31511 				/*
31512 				 * driver-assessment should be "fatal" if
31513 				 * drv_assess is SD_FM_DRV_FATAL.
31514 				 */
31515 				scsi_fm_ereport_post(un->un_sd,
31516 				    uscsi_path_instance, NULL,
31517 				    "cmd.disk.dev.rqs.merr",
31518 				    uscsi_ena, devid, NULL, DDI_NOSLEEP, NULL,
31519 				    FM_VERSION, DATA_TYPE_UINT8,
31520 				    FM_EREPORT_VERS0,
31521 				    DEVID_IF_KNOWN(devid),
31522 				    "driver-assessment",
31523 				    DATA_TYPE_STRING,
31524 				    drv_assess == SD_FM_DRV_FATAL ?
31525 				    "fatal" : assessment,
31526 				    "op-code",
31527 				    DATA_TYPE_UINT8, op_code,
31528 				    "cdb",
31529 				    DATA_TYPE_UINT8_ARRAY, cdblen,
31530 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
31531 				    "pkt-reason",
31532 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
31533 				    "pkt-state",
31534 				    DATA_TYPE_UINT8, uscsi_pkt_state,
31535 				    "pkt-stats",
31536 				    DATA_TYPE_UINT32,
31537 				    uscsi_pkt_statistics,
31538 				    "stat-code",
31539 				    DATA_TYPE_UINT8,
31540 				    ssc->ssc_uscsi_cmd->uscsi_status,
31541 				    "key",
31542 				    DATA_TYPE_UINT8,
31543 				    scsi_sense_key(sensep),
31544 				    "asc",
31545 				    DATA_TYPE_UINT8,
31546 				    scsi_sense_asc(sensep),
31547 				    "ascq",
31548 				    DATA_TYPE_UINT8,
31549 				    scsi_sense_ascq(sensep),
31550 				    "sense-data",
31551 				    DATA_TYPE_UINT8_ARRAY,
31552 				    senlen, sensep,
31553 				    "lba",
31554 				    DATA_TYPE_UINT64,
31555 				    ssc->ssc_uscsi_info->ui_lba,
31556 				    NULL);
31557 			} else {
31558 				/*
31559 				 * if sense-key == 0x4(hardware
31560 				 * error), driver-assessment should
31561 				 * be "fatal" if drv_assess is
31562 				 * SD_FM_DRV_FATAL.
31563 				 */
31564 				scsi_fm_ereport_post(un->un_sd,
31565 				    uscsi_path_instance, NULL,
31566 				    "cmd.disk.dev.rqs.derr",
31567 				    uscsi_ena, devid,
31568 				    NULL, DDI_NOSLEEP, NULL,
31569 				    FM_VERSION,
31570 				    DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31571 				    DEVID_IF_KNOWN(devid),
31572 				    "driver-assessment",
31573 				    DATA_TYPE_STRING,
31574 				    drv_assess == SD_FM_DRV_FATAL ?
31575 				    (sense_key == 0x4 ?
31576 				    "fatal" : "fail") : assessment,
31577 				    "op-code",
31578 				    DATA_TYPE_UINT8, op_code,
31579 				    "cdb",
31580 				    DATA_TYPE_UINT8_ARRAY, cdblen,
31581 				    ssc->ssc_uscsi_cmd->uscsi_cdb,
31582 				    "pkt-reason",
31583 				    DATA_TYPE_UINT8, uscsi_pkt_reason,
31584 				    "pkt-state",
31585 				    DATA_TYPE_UINT8, uscsi_pkt_state,
31586 				    "pkt-stats",
31587 				    DATA_TYPE_UINT32,
31588 				    uscsi_pkt_statistics,
31589 				    "stat-code",
31590 				    DATA_TYPE_UINT8,
31591 				    ssc->ssc_uscsi_cmd->uscsi_status,
31592 				    "key",
31593 				    DATA_TYPE_UINT8,
31594 				    scsi_sense_key(sensep),
31595 				    "asc",
31596 				    DATA_TYPE_UINT8,
31597 				    scsi_sense_asc(sensep),
31598 				    "ascq",
31599 				    DATA_TYPE_UINT8,
31600 				    scsi_sense_ascq(sensep),
31601 				    "sense-data",
31602 				    DATA_TYPE_UINT8_ARRAY,
31603 				    senlen, sensep,
31604 				    NULL);
31605 			}
31606 		} else {
31607 			/*
31608 			 * For stat_code == STATUS_GOOD, this is not a
31609 			 * hardware error.
31610 			 */
31611 			if (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD)
31612 				return;
31613 
31614 			/*
31615 			 * Post ereport.io.scsi.cmd.disk.dev.serr if we got the
31616 			 * stat-code but with sense data unavailable.
31617 			 * driver-assessment will be set based on parameter
31618 			 * drv_assess.
31619 			 */
31620 			scsi_fm_ereport_post(un->un_sd, uscsi_path_instance,
31621 			    NULL,
31622 			    "cmd.disk.dev.serr", uscsi_ena,
31623 			    devid, NULL, DDI_NOSLEEP, NULL,
31624 			    FM_VERSION, DATA_TYPE_UINT8, FM_EREPORT_VERS0,
31625 			    DEVID_IF_KNOWN(devid),
31626 			    "driver-assessment", DATA_TYPE_STRING,
31627 			    drv_assess == SD_FM_DRV_FATAL ? "fail" : assessment,
31628 			    "op-code", DATA_TYPE_UINT8, op_code,
31629 			    "cdb",
31630 			    DATA_TYPE_UINT8_ARRAY,
31631 			    cdblen, ssc->ssc_uscsi_cmd->uscsi_cdb,
31632 			    "pkt-reason",
31633 			    DATA_TYPE_UINT8, uscsi_pkt_reason,
31634 			    "pkt-state",
31635 			    DATA_TYPE_UINT8, uscsi_pkt_state,
31636 			    "pkt-stats",
31637 			    DATA_TYPE_UINT32, uscsi_pkt_statistics,
31638 			    "stat-code",
31639 			    DATA_TYPE_UINT8,
31640 			    ssc->ssc_uscsi_cmd->uscsi_status,
31641 			    NULL);
31642 		}
31643 	}
31644 }
31645 
31646 /*
31647  *     Function: sd_ssc_extract_info
31648  *
31649  * Description: Extract information available to help generate ereport.
31650  *
31651  *     Context: Kernel thread or interrupt context.
31652  */
31653 static void
31654 sd_ssc_extract_info(sd_ssc_t *ssc, struct sd_lun *un, struct scsi_pkt *pktp,
31655     struct buf *bp, struct sd_xbuf *xp)
31656 {
31657 	size_t senlen = 0;
31658 	union scsi_cdb *cdbp;
31659 	int path_instance;
31660 	/*
31661 	 * Need scsi_cdb_size array to determine the cdb length.
31662 	 */
31663 	extern uchar_t	scsi_cdb_size[];
31664 
31665 	ASSERT(un != NULL);
31666 	ASSERT(pktp != NULL);
31667 	ASSERT(bp != NULL);
31668 	ASSERT(xp != NULL);
31669 	ASSERT(ssc != NULL);
31670 	ASSERT(mutex_owned(SD_MUTEX(un)));
31671 
31672 	/*
31673 	 * Transfer the cdb buffer pointer here.
31674 	 */
31675 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
31676 
31677 	ssc->ssc_uscsi_cmd->uscsi_cdblen = scsi_cdb_size[GETGROUP(cdbp)];
31678 	ssc->ssc_uscsi_cmd->uscsi_cdb = (caddr_t)cdbp;
31679 
31680 	/*
31681 	 * Transfer the sense data buffer pointer if sense data is available,
31682 	 * calculate the sense data length first.
31683 	 */
31684 	if ((xp->xb_sense_state & STATE_XARQ_DONE) ||
31685 	    (xp->xb_sense_state & STATE_ARQ_DONE)) {
31686 		/*
31687 		 * For arq case, we will enter here.
31688 		 */
31689 		if (xp->xb_sense_state & STATE_XARQ_DONE) {
31690 			senlen = MAX_SENSE_LENGTH - xp->xb_sense_resid;
31691 		} else {
31692 			senlen = SENSE_LENGTH;
31693 		}
31694 	} else {
31695 		/*
31696 		 * For non-arq case, we will enter this branch.
31697 		 */
31698 		if (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK &&
31699 		    (xp->xb_sense_state & STATE_XFERRED_DATA)) {
31700 			senlen = SENSE_LENGTH - xp->xb_sense_resid;
31701 		}
31702 
31703 	}
31704 
31705 	ssc->ssc_uscsi_cmd->uscsi_rqlen = (senlen & 0xff);
31706 	ssc->ssc_uscsi_cmd->uscsi_rqresid = 0;
31707 	ssc->ssc_uscsi_cmd->uscsi_rqbuf = (caddr_t)xp->xb_sense_data;
31708 
31709 	ssc->ssc_uscsi_cmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
31710 
31711 	/*
31712 	 * Only transfer path_instance when scsi_pkt was properly allocated.
31713 	 */
31714 	path_instance = pktp->pkt_path_instance;
31715 	if (scsi_pkt_allocated_correctly(pktp) && path_instance)
31716 		ssc->ssc_uscsi_cmd->uscsi_path_instance = path_instance;
31717 	else
31718 		ssc->ssc_uscsi_cmd->uscsi_path_instance = 0;
31719 
31720 	/*
31721 	 * Copy in the other fields we may need when posting ereport.
31722 	 */
31723 	ssc->ssc_uscsi_info->ui_pkt_reason = pktp->pkt_reason;
31724 	ssc->ssc_uscsi_info->ui_pkt_state = pktp->pkt_state;
31725 	ssc->ssc_uscsi_info->ui_pkt_statistics = pktp->pkt_statistics;
31726 	ssc->ssc_uscsi_info->ui_lba = (uint64_t)SD_GET_BLKNO(bp);
31727 
31728 	/*
31729 	 * For partially read/write command, we will not create ena
31730 	 * in case of a successful command be reconized as recovered.
31731 	 */
31732 	if ((pktp->pkt_reason == CMD_CMPLT) &&
31733 	    (ssc->ssc_uscsi_cmd->uscsi_status == STATUS_GOOD) &&
31734 	    (senlen == 0)) {
31735 		return;
31736 	}
31737 
31738 	/*
31739 	 * To associate ereports of a single command execution flow, we
31740 	 * need a shared ena for a specific command.
31741 	 */
31742 	if (xp->xb_ena == 0)
31743 		xp->xb_ena = fm_ena_generate(0, FM_ENA_FMT1);
31744 	ssc->ssc_uscsi_info->ui_ena = xp->xb_ena;
31745 }
31746 
31747 
31748 /*
31749  *     Function: sd_check_bdc_vpd
31750  *
31751  * Description: Query the optional INQUIRY VPD page 0xb1. If the device
31752  *              supports VPD page 0xb1, sd examines the MEDIUM ROTATION
31753  *              RATE.
31754  *
31755  *		Set the following based on RPM value:
31756  *		= 0	device is not solid state, non-rotational
31757  *		= 1	device is solid state, non-rotational
31758  *		> 1	device is not solid state, rotational
31759  *
31760  *     Context: Kernel thread or interrupt context.
31761  */
31762 
31763 static void
31764 sd_check_bdc_vpd(sd_ssc_t *ssc)
31765 {
31766 	int		rval		= 0;
31767 	uchar_t		*inqb1		= NULL;
31768 	size_t		inqb1_len	= MAX_INQUIRY_SIZE;
31769 	size_t		inqb1_resid	= 0;
31770 	struct sd_lun	*un;
31771 
31772 	ASSERT(ssc != NULL);
31773 	un = ssc->ssc_un;
31774 	ASSERT(un != NULL);
31775 	ASSERT(!mutex_owned(SD_MUTEX(un)));
31776 
31777 	mutex_enter(SD_MUTEX(un));
31778 	un->un_f_is_rotational = TRUE;
31779 	un->un_f_is_solid_state = FALSE;
31780 
31781 	if (ISCD(un)) {
31782 		mutex_exit(SD_MUTEX(un));
31783 		return;
31784 	}
31785 
31786 	if (sd_check_vpd_page_support(ssc) == 0 &&
31787 	    un->un_vpd_page_mask & SD_VPD_DEV_CHARACTER_PG) {
31788 		mutex_exit(SD_MUTEX(un));
31789 		/* collect page b1 data */
31790 		inqb1 = kmem_zalloc(inqb1_len, KM_SLEEP);
31791 
31792 		rval = sd_send_scsi_INQUIRY(ssc, inqb1, inqb1_len,
31793 		    0x01, 0xB1, &inqb1_resid);
31794 
31795 		if (rval == 0 && (inqb1_len - inqb1_resid > 5)) {
31796 			SD_TRACE(SD_LOG_COMMON, un,
31797 			    "sd_check_bdc_vpd: \
31798 			    successfully get VPD page: %x \
31799 			    PAGE LENGTH: %x BYTE 4: %x \
31800 			    BYTE 5: %x", inqb1[1], inqb1[3], inqb1[4],
31801 			    inqb1[5]);
31802 
31803 			mutex_enter(SD_MUTEX(un));
31804 			/*
31805 			 * Check the MEDIUM ROTATION RATE.
31806 			 */
31807 			if (inqb1[4] == 0) {
31808 				if (inqb1[5] == 0) {
31809 					un->un_f_is_rotational = FALSE;
31810 				} else if (inqb1[5] == 1) {
31811 					un->un_f_is_rotational = FALSE;
31812 					un->un_f_is_solid_state = TRUE;
31813 					/*
31814 					 * Solid state drives don't need
31815 					 * disksort.
31816 					 */
31817 					un->un_f_disksort_disabled = TRUE;
31818 				}
31819 			}
31820 			mutex_exit(SD_MUTEX(un));
31821 		} else if (rval != 0) {
31822 			sd_ssc_assessment(ssc, SD_FMT_IGNORE);
31823 		}
31824 
31825 		kmem_free(inqb1, inqb1_len);
31826 	} else {
31827 		mutex_exit(SD_MUTEX(un));
31828 	}
31829 }
31830 
31831 /*
31832  *	Function: sd_check_emulation_mode
31833  *
31834  *   Description: Check whether the SSD is at emulation mode
31835  *		  by issuing READ_CAPACITY_16 to see whether
31836  *		  we can get physical block size of the drive.
31837  *
31838  *	 Context: Kernel thread or interrupt context.
31839  */
31840 
31841 static void
31842 sd_check_emulation_mode(sd_ssc_t *ssc)
31843 {
31844 	int		rval = 0;
31845 	uint64_t	capacity;
31846 	uint_t		lbasize;
31847 	uint_t		pbsize;
31848 	int		i;
31849 	int		devid_len;
31850 	struct sd_lun	*un;
31851 
31852 	ASSERT(ssc != NULL);
31853 	un = ssc->ssc_un;
31854 	ASSERT(un != NULL);
31855 	ASSERT(!mutex_owned(SD_MUTEX(un)));
31856 
31857 	mutex_enter(SD_MUTEX(un));
31858 	if (ISCD(un)) {
31859 		mutex_exit(SD_MUTEX(un));
31860 		return;
31861 	}
31862 
31863 	if (un->un_f_descr_format_supported) {
31864 		mutex_exit(SD_MUTEX(un));
31865 		rval = sd_send_scsi_READ_CAPACITY_16(ssc, &capacity, &lbasize,
31866 		    &pbsize, SD_PATH_DIRECT);
31867 		mutex_enter(SD_MUTEX(un));
31868 
31869 		if (rval != 0) {
31870 			un->un_phy_blocksize = DEV_BSIZE;
31871 		} else {
31872 			if (!ISP2(pbsize % DEV_BSIZE) || pbsize == 0) {
31873 				un->un_phy_blocksize = DEV_BSIZE;
31874 			} else if (pbsize > un->un_phy_blocksize) {
31875 				/*
31876 				 * Don't reset the physical blocksize
31877 				 * unless we've detected a larger value.
31878 				 */
31879 				un->un_phy_blocksize = pbsize;
31880 			}
31881 		}
31882 	}
31883 
31884 	for (i = 0; i < sd_flash_dev_table_size; i++) {
31885 		devid_len = (int)strlen(sd_flash_dev_table[i]);
31886 		if (sd_sdconf_id_match(un, sd_flash_dev_table[i], devid_len)
31887 		    == SD_SUCCESS) {
31888 			un->un_phy_blocksize = SSD_SECSIZE;
31889 			if (un->un_f_is_solid_state &&
31890 			    un->un_phy_blocksize != un->un_tgt_blocksize)
31891 				un->un_f_enable_rmw = TRUE;
31892 		}
31893 	}
31894 
31895 	mutex_exit(SD_MUTEX(un));
31896 }
31897