xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 2b098703)
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  * Copyright 2007 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 #pragma ident	"%Z%%M%	%I%	%E% SMI"
27 
28 /*
29  * SCSI disk target driver.
30  */
31 #include <sys/scsi/scsi.h>
32 #include <sys/dkbad.h>
33 #include <sys/dklabel.h>
34 #include <sys/dkio.h>
35 #include <sys/fdio.h>
36 #include <sys/cdio.h>
37 #include <sys/mhd.h>
38 #include <sys/vtoc.h>
39 #include <sys/dktp/fdisk.h>
40 #include <sys/kstat.h>
41 #include <sys/vtrace.h>
42 #include <sys/note.h>
43 #include <sys/thread.h>
44 #include <sys/proc.h>
45 #include <sys/efi_partition.h>
46 #include <sys/var.h>
47 #include <sys/aio_req.h>
48 
49 #ifdef __lock_lint
50 #define	_LP64
51 #define	__amd64
52 #endif
53 
54 #if (defined(__fibre))
55 /* Note: is there a leadville version of the following? */
56 #include <sys/fc4/fcal_linkapp.h>
57 #endif
58 #include <sys/taskq.h>
59 #include <sys/uuid.h>
60 #include <sys/byteorder.h>
61 #include <sys/sdt.h>
62 
63 #include "sd_xbuf.h"
64 
65 #include <sys/scsi/targets/sddef.h>
66 #include <sys/cmlb.h>
67 
68 
69 /*
70  * Loadable module info.
71  */
72 #if (defined(__fibre))
73 #define	SD_MODULE_NAME	"SCSI SSA/FCAL Disk Driver %I%"
74 char _depends_on[]	= "misc/scsi misc/cmlb drv/fcp";
75 #else
76 #define	SD_MODULE_NAME	"SCSI Disk Driver %I%"
77 char _depends_on[]	= "misc/scsi misc/cmlb";
78 #endif
79 
80 /*
81  * Define the interconnect type, to allow the driver to distinguish
82  * between parallel SCSI (sd) and fibre channel (ssd) behaviors.
83  *
84  * This is really for backward compatibility. In the future, the driver
85  * should actually check the "interconnect-type" property as reported by
86  * the HBA; however at present this property is not defined by all HBAs,
87  * so we will use this #define (1) to permit the driver to run in
88  * backward-compatibility mode; and (2) to print a notification message
89  * if an FC HBA does not support the "interconnect-type" property.  The
90  * behavior of the driver will be to assume parallel SCSI behaviors unless
91  * the "interconnect-type" property is defined by the HBA **AND** has a
92  * value of either INTERCONNECT_FIBRE, INTERCONNECT_SSA, or
93  * INTERCONNECT_FABRIC, in which case the driver will assume Fibre
94  * Channel behaviors (as per the old ssd).  (Note that the
95  * INTERCONNECT_1394 and INTERCONNECT_USB types are not supported and
96  * will result in the driver assuming parallel SCSI behaviors.)
97  *
98  * (see common/sys/scsi/impl/services.h)
99  *
100  * Note: For ssd semantics, don't use INTERCONNECT_FABRIC as the default
101  * since some FC HBAs may already support that, and there is some code in
102  * the driver that already looks for it.  Using INTERCONNECT_FABRIC as the
103  * default would confuse that code, and besides things should work fine
104  * anyways if the FC HBA already reports INTERCONNECT_FABRIC for the
105  * "interconnect_type" property.
106  *
107  */
108 #if (defined(__fibre))
109 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_FIBRE
110 #else
111 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_PARALLEL
112 #endif
113 
114 /*
115  * The name of the driver, established from the module name in _init.
116  */
117 static	char *sd_label			= NULL;
118 
119 /*
120  * Driver name is unfortunately prefixed on some driver.conf properties.
121  */
122 #if (defined(__fibre))
123 #define	sd_max_xfer_size		ssd_max_xfer_size
124 #define	sd_config_list			ssd_config_list
125 static	char *sd_max_xfer_size		= "ssd_max_xfer_size";
126 static	char *sd_config_list		= "ssd-config-list";
127 #else
128 static	char *sd_max_xfer_size		= "sd_max_xfer_size";
129 static	char *sd_config_list		= "sd-config-list";
130 #endif
131 
132 /*
133  * Driver global variables
134  */
135 
136 #if (defined(__fibre))
137 /*
138  * These #defines are to avoid namespace collisions that occur because this
139  * code is currently used to compile two separate driver modules: sd and ssd.
140  * All global variables need to be treated this way (even if declared static)
141  * in order to allow the debugger to resolve the names properly.
142  * It is anticipated that in the near future the ssd module will be obsoleted,
143  * at which time this namespace issue should go away.
144  */
145 #define	sd_state			ssd_state
146 #define	sd_io_time			ssd_io_time
147 #define	sd_failfast_enable		ssd_failfast_enable
148 #define	sd_ua_retry_count		ssd_ua_retry_count
149 #define	sd_report_pfa			ssd_report_pfa
150 #define	sd_max_throttle			ssd_max_throttle
151 #define	sd_min_throttle			ssd_min_throttle
152 #define	sd_rot_delay			ssd_rot_delay
153 
154 #define	sd_retry_on_reservation_conflict	\
155 					ssd_retry_on_reservation_conflict
156 #define	sd_reinstate_resv_delay		ssd_reinstate_resv_delay
157 #define	sd_resv_conflict_name		ssd_resv_conflict_name
158 
159 #define	sd_component_mask		ssd_component_mask
160 #define	sd_level_mask			ssd_level_mask
161 #define	sd_debug_un			ssd_debug_un
162 #define	sd_error_level			ssd_error_level
163 
164 #define	sd_xbuf_active_limit		ssd_xbuf_active_limit
165 #define	sd_xbuf_reserve_limit		ssd_xbuf_reserve_limit
166 
167 #define	sd_tr				ssd_tr
168 #define	sd_reset_throttle_timeout	ssd_reset_throttle_timeout
169 #define	sd_qfull_throttle_timeout	ssd_qfull_throttle_timeout
170 #define	sd_qfull_throttle_enable	ssd_qfull_throttle_enable
171 #define	sd_check_media_time		ssd_check_media_time
172 #define	sd_wait_cmds_complete		ssd_wait_cmds_complete
173 #define	sd_label_mutex			ssd_label_mutex
174 #define	sd_detach_mutex			ssd_detach_mutex
175 #define	sd_log_buf			ssd_log_buf
176 #define	sd_log_mutex			ssd_log_mutex
177 
178 #define	sd_disk_table			ssd_disk_table
179 #define	sd_disk_table_size		ssd_disk_table_size
180 #define	sd_sense_mutex			ssd_sense_mutex
181 #define	sd_cdbtab			ssd_cdbtab
182 
183 #define	sd_cb_ops			ssd_cb_ops
184 #define	sd_ops				ssd_ops
185 #define	sd_additional_codes		ssd_additional_codes
186 #define	sd_tgops			ssd_tgops
187 
188 #define	sd_minor_data			ssd_minor_data
189 #define	sd_minor_data_efi		ssd_minor_data_efi
190 
191 #define	sd_tq				ssd_tq
192 #define	sd_wmr_tq			ssd_wmr_tq
193 #define	sd_taskq_name			ssd_taskq_name
194 #define	sd_wmr_taskq_name		ssd_wmr_taskq_name
195 #define	sd_taskq_minalloc		ssd_taskq_minalloc
196 #define	sd_taskq_maxalloc		ssd_taskq_maxalloc
197 
198 #define	sd_dump_format_string		ssd_dump_format_string
199 
200 #define	sd_iostart_chain		ssd_iostart_chain
201 #define	sd_iodone_chain			ssd_iodone_chain
202 
203 #define	sd_pm_idletime			ssd_pm_idletime
204 
205 #define	sd_force_pm_supported		ssd_force_pm_supported
206 
207 #define	sd_dtype_optical_bind		ssd_dtype_optical_bind
208 
209 #endif
210 
211 
212 #ifdef	SDDEBUG
213 int	sd_force_pm_supported		= 0;
214 #endif	/* SDDEBUG */
215 
216 void *sd_state				= NULL;
217 int sd_io_time				= SD_IO_TIME;
218 int sd_failfast_enable			= 1;
219 int sd_ua_retry_count			= SD_UA_RETRY_COUNT;
220 int sd_report_pfa			= 1;
221 int sd_max_throttle			= SD_MAX_THROTTLE;
222 int sd_min_throttle			= SD_MIN_THROTTLE;
223 int sd_rot_delay			= 4; /* Default 4ms Rotation delay */
224 int sd_qfull_throttle_enable		= TRUE;
225 
226 int sd_retry_on_reservation_conflict	= 1;
227 int sd_reinstate_resv_delay		= SD_REINSTATE_RESV_DELAY;
228 _NOTE(SCHEME_PROTECTS_DATA("safe sharing", sd_reinstate_resv_delay))
229 
230 static int sd_dtype_optical_bind	= -1;
231 
232 /* Note: the following is not a bug, it really is "sd_" and not "ssd_" */
233 static	char *sd_resv_conflict_name	= "sd_retry_on_reservation_conflict";
234 
235 /*
236  * Global data for debug logging. To enable debug printing, sd_component_mask
237  * and sd_level_mask should be set to the desired bit patterns as outlined in
238  * sddef.h.
239  */
240 uint_t	sd_component_mask		= 0x0;
241 uint_t	sd_level_mask			= 0x0;
242 struct	sd_lun *sd_debug_un		= NULL;
243 uint_t	sd_error_level			= SCSI_ERR_RETRYABLE;
244 
245 /* Note: these may go away in the future... */
246 static uint32_t	sd_xbuf_active_limit	= 512;
247 static uint32_t sd_xbuf_reserve_limit	= 16;
248 
249 static struct sd_resv_reclaim_request	sd_tr = { NULL, NULL, NULL, 0, 0, 0 };
250 
251 /*
252  * Timer value used to reset the throttle after it has been reduced
253  * (typically in response to TRAN_BUSY or STATUS_QFULL)
254  */
255 static int sd_reset_throttle_timeout	= SD_RESET_THROTTLE_TIMEOUT;
256 static int sd_qfull_throttle_timeout	= SD_QFULL_THROTTLE_TIMEOUT;
257 
258 /*
259  * Interval value associated with the media change scsi watch.
260  */
261 static int sd_check_media_time		= 3000000;
262 
263 /*
264  * Wait value used for in progress operations during a DDI_SUSPEND
265  */
266 static int sd_wait_cmds_complete	= SD_WAIT_CMDS_COMPLETE;
267 
268 /*
269  * sd_label_mutex protects a static buffer used in the disk label
270  * component of the driver
271  */
272 static kmutex_t sd_label_mutex;
273 
274 /*
275  * sd_detach_mutex protects un_layer_count, un_detach_count, and
276  * un_opens_in_progress in the sd_lun structure.
277  */
278 static kmutex_t sd_detach_mutex;
279 
280 _NOTE(MUTEX_PROTECTS_DATA(sd_detach_mutex,
281 	sd_lun::{un_layer_count un_detach_count un_opens_in_progress}))
282 
283 /*
284  * Global buffer and mutex for debug logging
285  */
286 static char	sd_log_buf[1024];
287 static kmutex_t	sd_log_mutex;
288 
289 /*
290  * Structs and globals for recording attached lun information.
291  * This maintains a chain. Each node in the chain represents a SCSI controller.
292  * The structure records the number of luns attached to each target connected
293  * with the controller.
294  * For parallel scsi device only.
295  */
296 struct sd_scsi_hba_tgt_lun {
297 	struct sd_scsi_hba_tgt_lun	*next;
298 	dev_info_t			*pdip;
299 	int				nlun[NTARGETS_WIDE];
300 };
301 
302 /*
303  * Flag to indicate the lun is attached or detached
304  */
305 #define	SD_SCSI_LUN_ATTACH	0
306 #define	SD_SCSI_LUN_DETACH	1
307 
308 static kmutex_t	sd_scsi_target_lun_mutex;
309 static struct sd_scsi_hba_tgt_lun	*sd_scsi_target_lun_head = NULL;
310 
311 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
312     sd_scsi_hba_tgt_lun::next sd_scsi_hba_tgt_lun::pdip))
313 
314 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
315     sd_scsi_target_lun_head))
316 
317 /*
318  * "Smart" Probe Caching structs, globals, #defines, etc.
319  * For parallel scsi and non-self-identify device only.
320  */
321 
322 /*
323  * The following resources and routines are implemented to support
324  * "smart" probing, which caches the scsi_probe() results in an array,
325  * in order to help avoid long probe times.
326  */
327 struct sd_scsi_probe_cache {
328 	struct	sd_scsi_probe_cache	*next;
329 	dev_info_t	*pdip;
330 	int		cache[NTARGETS_WIDE];
331 };
332 
333 static kmutex_t	sd_scsi_probe_cache_mutex;
334 static struct	sd_scsi_probe_cache *sd_scsi_probe_cache_head = NULL;
335 
336 /*
337  * Really we only need protection on the head of the linked list, but
338  * better safe than sorry.
339  */
340 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
341     sd_scsi_probe_cache::next sd_scsi_probe_cache::pdip))
342 
343 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
344     sd_scsi_probe_cache_head))
345 
346 
347 /*
348  * Vendor specific data name property declarations
349  */
350 
351 #if defined(__fibre) || defined(__i386) ||defined(__amd64)
352 
353 static sd_tunables seagate_properties = {
354 	SEAGATE_THROTTLE_VALUE,
355 	0,
356 	0,
357 	0,
358 	0,
359 	0,
360 	0,
361 	0,
362 	0
363 };
364 
365 
366 static sd_tunables fujitsu_properties = {
367 	FUJITSU_THROTTLE_VALUE,
368 	0,
369 	0,
370 	0,
371 	0,
372 	0,
373 	0,
374 	0,
375 	0
376 };
377 
378 static sd_tunables ibm_properties = {
379 	IBM_THROTTLE_VALUE,
380 	0,
381 	0,
382 	0,
383 	0,
384 	0,
385 	0,
386 	0,
387 	0
388 };
389 
390 static sd_tunables purple_properties = {
391 	PURPLE_THROTTLE_VALUE,
392 	0,
393 	0,
394 	PURPLE_BUSY_RETRIES,
395 	PURPLE_RESET_RETRY_COUNT,
396 	PURPLE_RESERVE_RELEASE_TIME,
397 	0,
398 	0,
399 	0
400 };
401 
402 static sd_tunables sve_properties = {
403 	SVE_THROTTLE_VALUE,
404 	0,
405 	0,
406 	SVE_BUSY_RETRIES,
407 	SVE_RESET_RETRY_COUNT,
408 	SVE_RESERVE_RELEASE_TIME,
409 	SVE_MIN_THROTTLE_VALUE,
410 	SVE_DISKSORT_DISABLED_FLAG,
411 	0
412 };
413 
414 static sd_tunables maserati_properties = {
415 	0,
416 	0,
417 	0,
418 	0,
419 	0,
420 	0,
421 	0,
422 	MASERATI_DISKSORT_DISABLED_FLAG,
423 	MASERATI_LUN_RESET_ENABLED_FLAG
424 };
425 
426 static sd_tunables pirus_properties = {
427 	PIRUS_THROTTLE_VALUE,
428 	0,
429 	PIRUS_NRR_COUNT,
430 	PIRUS_BUSY_RETRIES,
431 	PIRUS_RESET_RETRY_COUNT,
432 	0,
433 	PIRUS_MIN_THROTTLE_VALUE,
434 	PIRUS_DISKSORT_DISABLED_FLAG,
435 	PIRUS_LUN_RESET_ENABLED_FLAG
436 };
437 
438 #endif
439 
440 #if (defined(__sparc) && !defined(__fibre)) || \
441 	(defined(__i386) || defined(__amd64))
442 
443 
444 static sd_tunables elite_properties = {
445 	ELITE_THROTTLE_VALUE,
446 	0,
447 	0,
448 	0,
449 	0,
450 	0,
451 	0,
452 	0,
453 	0
454 };
455 
456 static sd_tunables st31200n_properties = {
457 	ST31200N_THROTTLE_VALUE,
458 	0,
459 	0,
460 	0,
461 	0,
462 	0,
463 	0,
464 	0,
465 	0
466 };
467 
468 #endif /* Fibre or not */
469 
470 static sd_tunables lsi_properties_scsi = {
471 	LSI_THROTTLE_VALUE,
472 	0,
473 	LSI_NOTREADY_RETRIES,
474 	0,
475 	0,
476 	0,
477 	0,
478 	0,
479 	0
480 };
481 
482 static sd_tunables symbios_properties = {
483 	SYMBIOS_THROTTLE_VALUE,
484 	0,
485 	SYMBIOS_NOTREADY_RETRIES,
486 	0,
487 	0,
488 	0,
489 	0,
490 	0,
491 	0
492 };
493 
494 static sd_tunables lsi_properties = {
495 	0,
496 	0,
497 	LSI_NOTREADY_RETRIES,
498 	0,
499 	0,
500 	0,
501 	0,
502 	0,
503 	0
504 };
505 
506 static sd_tunables lsi_oem_properties = {
507 	0,
508 	0,
509 	LSI_OEM_NOTREADY_RETRIES,
510 	0,
511 	0,
512 	0,
513 	0,
514 	0,
515 	0,
516 	1
517 };
518 
519 
520 
521 #if (defined(SD_PROP_TST))
522 
523 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
524 #define	SD_TST_THROTTLE_VAL	16
525 #define	SD_TST_NOTREADY_VAL	12
526 #define	SD_TST_BUSY_VAL		60
527 #define	SD_TST_RST_RETRY_VAL	36
528 #define	SD_TST_RSV_REL_TIME	60
529 
530 static sd_tunables tst_properties = {
531 	SD_TST_THROTTLE_VAL,
532 	SD_TST_CTYPE_VAL,
533 	SD_TST_NOTREADY_VAL,
534 	SD_TST_BUSY_VAL,
535 	SD_TST_RST_RETRY_VAL,
536 	SD_TST_RSV_REL_TIME,
537 	0,
538 	0,
539 	0
540 };
541 #endif
542 
543 /* This is similar to the ANSI toupper implementation */
544 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
545 
546 /*
547  * Static Driver Configuration Table
548  *
549  * This is the table of disks which need throttle adjustment (or, perhaps
550  * something else as defined by the flags at a future time.)  device_id
551  * is a string consisting of concatenated vid (vendor), pid (product/model)
552  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
553  * the parts of the string are as defined by the sizes in the scsi_inquiry
554  * structure.  Device type is searched as far as the device_id string is
555  * defined.  Flags defines which values are to be set in the driver from the
556  * properties list.
557  *
558  * Entries below which begin and end with a "*" are a special case.
559  * These do not have a specific vendor, and the string which follows
560  * can appear anywhere in the 16 byte PID portion of the inquiry data.
561  *
562  * Entries below which begin and end with a " " (blank) are a special
563  * case. The comparison function will treat multiple consecutive blanks
564  * as equivalent to a single blank. For example, this causes a
565  * sd_disk_table entry of " NEC CDROM " to match a device's id string
566  * of  "NEC       CDROM".
567  *
568  * Note: The MD21 controller type has been obsoleted.
569  *	 ST318202F is a Legacy device
570  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
571  *	 made with an FC connection. The entries here are a legacy.
572  */
573 static sd_disk_config_t sd_disk_table[] = {
574 #if defined(__fibre) || defined(__i386) || defined(__amd64)
575 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
576 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
577 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
578 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
579 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
580 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
581 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
582 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
583 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
584 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
585 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
586 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
587 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
588 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
589 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
590 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
591 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
592 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
593 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
594 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
595 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
596 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
597 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
598 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
599 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
600 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
601 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
602 	{ "IBM     1724-100",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
603 	{ "IBM     1726-2xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
604 	{ "IBM     1726-22x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
605 	{ "IBM     1726-4xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
606 	{ "IBM     1726-42x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
607 	{ "IBM     1726-3xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
608 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
609 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
610 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
611 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
612 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
613 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
614 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
615 	{ "IBM     1814",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
616 	{ "IBM     1814-200",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
617 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
618 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
619 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
620 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
621 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT |
622 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
623 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT |
624 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
625 	{ "Fujitsu SX300",	SD_CONF_BSET_THROTTLE,  &lsi_oem_properties },
626 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
627 	{ "SUN     T3", SD_CONF_BSET_THROTTLE |
628 			SD_CONF_BSET_BSY_RETRY_COUNT|
629 			SD_CONF_BSET_RST_RETRIES|
630 			SD_CONF_BSET_RSV_REL_TIME,
631 		&purple_properties },
632 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
633 		SD_CONF_BSET_BSY_RETRY_COUNT|
634 		SD_CONF_BSET_RST_RETRIES|
635 		SD_CONF_BSET_RSV_REL_TIME|
636 		SD_CONF_BSET_MIN_THROTTLE|
637 		SD_CONF_BSET_DISKSORT_DISABLED,
638 		&sve_properties },
639 	{ "SUN     T4", SD_CONF_BSET_THROTTLE |
640 			SD_CONF_BSET_BSY_RETRY_COUNT|
641 			SD_CONF_BSET_RST_RETRIES|
642 			SD_CONF_BSET_RSV_REL_TIME,
643 		&purple_properties },
644 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
645 		SD_CONF_BSET_LUN_RESET_ENABLED,
646 		&maserati_properties },
647 	{ "SUN     SE6920", SD_CONF_BSET_THROTTLE |
648 		SD_CONF_BSET_NRR_COUNT|
649 		SD_CONF_BSET_BSY_RETRY_COUNT|
650 		SD_CONF_BSET_RST_RETRIES|
651 		SD_CONF_BSET_MIN_THROTTLE|
652 		SD_CONF_BSET_DISKSORT_DISABLED|
653 		SD_CONF_BSET_LUN_RESET_ENABLED,
654 		&pirus_properties },
655 	{ "SUN     SE6940", SD_CONF_BSET_THROTTLE |
656 		SD_CONF_BSET_NRR_COUNT|
657 		SD_CONF_BSET_BSY_RETRY_COUNT|
658 		SD_CONF_BSET_RST_RETRIES|
659 		SD_CONF_BSET_MIN_THROTTLE|
660 		SD_CONF_BSET_DISKSORT_DISABLED|
661 		SD_CONF_BSET_LUN_RESET_ENABLED,
662 		&pirus_properties },
663 	{ "SUN     StorageTek 6920", SD_CONF_BSET_THROTTLE |
664 		SD_CONF_BSET_NRR_COUNT|
665 		SD_CONF_BSET_BSY_RETRY_COUNT|
666 		SD_CONF_BSET_RST_RETRIES|
667 		SD_CONF_BSET_MIN_THROTTLE|
668 		SD_CONF_BSET_DISKSORT_DISABLED|
669 		SD_CONF_BSET_LUN_RESET_ENABLED,
670 		&pirus_properties },
671 	{ "SUN     StorageTek 6940", SD_CONF_BSET_THROTTLE |
672 		SD_CONF_BSET_NRR_COUNT|
673 		SD_CONF_BSET_BSY_RETRY_COUNT|
674 		SD_CONF_BSET_RST_RETRIES|
675 		SD_CONF_BSET_MIN_THROTTLE|
676 		SD_CONF_BSET_DISKSORT_DISABLED|
677 		SD_CONF_BSET_LUN_RESET_ENABLED,
678 		&pirus_properties },
679 	{ "SUN     PSX1000", SD_CONF_BSET_THROTTLE |
680 		SD_CONF_BSET_NRR_COUNT|
681 		SD_CONF_BSET_BSY_RETRY_COUNT|
682 		SD_CONF_BSET_RST_RETRIES|
683 		SD_CONF_BSET_MIN_THROTTLE|
684 		SD_CONF_BSET_DISKSORT_DISABLED|
685 		SD_CONF_BSET_LUN_RESET_ENABLED,
686 		&pirus_properties },
687 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
688 		SD_CONF_BSET_NRR_COUNT|
689 		SD_CONF_BSET_BSY_RETRY_COUNT|
690 		SD_CONF_BSET_RST_RETRIES|
691 		SD_CONF_BSET_MIN_THROTTLE|
692 		SD_CONF_BSET_DISKSORT_DISABLED|
693 		SD_CONF_BSET_LUN_RESET_ENABLED,
694 		&pirus_properties },
695 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
696 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
697 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
698 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
699 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
700 #endif /* fibre or NON-sparc platforms */
701 #if ((defined(__sparc) && !defined(__fibre)) ||\
702 	(defined(__i386) || defined(__amd64)))
703 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
704 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
705 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
706 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
707 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
708 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
709 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
710 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
711 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
712 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
713 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
714 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
715 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
716 	    &symbios_properties },
717 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
718 	    &lsi_properties_scsi },
719 #if defined(__i386) || defined(__amd64)
720 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
721 				    | SD_CONF_BSET_READSUB_BCD
722 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
723 				    | SD_CONF_BSET_NO_READ_HEADER
724 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
725 
726 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
727 				    | SD_CONF_BSET_READSUB_BCD
728 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
729 				    | SD_CONF_BSET_NO_READ_HEADER
730 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
731 #endif /* __i386 || __amd64 */
732 #endif /* sparc NON-fibre or NON-sparc platforms */
733 
734 #if (defined(SD_PROP_TST))
735 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
736 				| SD_CONF_BSET_CTYPE
737 				| SD_CONF_BSET_NRR_COUNT
738 				| SD_CONF_BSET_FAB_DEVID
739 				| SD_CONF_BSET_NOCACHE
740 				| SD_CONF_BSET_BSY_RETRY_COUNT
741 				| SD_CONF_BSET_PLAYMSF_BCD
742 				| SD_CONF_BSET_READSUB_BCD
743 				| SD_CONF_BSET_READ_TOC_TRK_BCD
744 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
745 				| SD_CONF_BSET_NO_READ_HEADER
746 				| SD_CONF_BSET_READ_CD_XD4
747 				| SD_CONF_BSET_RST_RETRIES
748 				| SD_CONF_BSET_RSV_REL_TIME
749 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
750 #endif
751 };
752 
753 static const int sd_disk_table_size =
754 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
755 
756 
757 
758 #define	SD_INTERCONNECT_PARALLEL	0
759 #define	SD_INTERCONNECT_FABRIC		1
760 #define	SD_INTERCONNECT_FIBRE		2
761 #define	SD_INTERCONNECT_SSA		3
762 #define	SD_INTERCONNECT_SATA		4
763 #define	SD_IS_PARALLEL_SCSI(un)		\
764 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
765 #define	SD_IS_SERIAL(un)		\
766 	((un)->un_interconnect_type == SD_INTERCONNECT_SATA)
767 
768 /*
769  * Definitions used by device id registration routines
770  */
771 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
772 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
773 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
774 
775 static kmutex_t sd_sense_mutex = {0};
776 
777 /*
778  * Macros for updates of the driver state
779  */
780 #define	New_state(un, s)        \
781 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
782 #define	Restore_state(un)	\
783 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
784 
785 static struct sd_cdbinfo sd_cdbtab[] = {
786 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
787 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
788 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
789 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
790 };
791 
792 /*
793  * Specifies the number of seconds that must have elapsed since the last
794  * cmd. has completed for a device to be declared idle to the PM framework.
795  */
796 static int sd_pm_idletime = 1;
797 
798 /*
799  * Internal function prototypes
800  */
801 
802 #if (defined(__fibre))
803 /*
804  * These #defines are to avoid namespace collisions that occur because this
805  * code is currently used to compile two separate driver modules: sd and ssd.
806  * All function names need to be treated this way (even if declared static)
807  * in order to allow the debugger to resolve the names properly.
808  * It is anticipated that in the near future the ssd module will be obsoleted,
809  * at which time this ugliness should go away.
810  */
811 #define	sd_log_trace			ssd_log_trace
812 #define	sd_log_info			ssd_log_info
813 #define	sd_log_err			ssd_log_err
814 #define	sdprobe				ssdprobe
815 #define	sdinfo				ssdinfo
816 #define	sd_prop_op			ssd_prop_op
817 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
818 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
819 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
820 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
821 #define	sd_scsi_target_lun_init		ssd_scsi_target_lun_init
822 #define	sd_scsi_target_lun_fini		ssd_scsi_target_lun_fini
823 #define	sd_scsi_get_target_lun_count	ssd_scsi_get_target_lun_count
824 #define	sd_scsi_update_lun_on_target	ssd_scsi_update_lun_on_target
825 #define	sd_spin_up_unit			ssd_spin_up_unit
826 #define	sd_enable_descr_sense		ssd_enable_descr_sense
827 #define	sd_reenable_dsense_task		ssd_reenable_dsense_task
828 #define	sd_set_mmc_caps			ssd_set_mmc_caps
829 #define	sd_read_unit_properties		ssd_read_unit_properties
830 #define	sd_process_sdconf_file		ssd_process_sdconf_file
831 #define	sd_process_sdconf_table		ssd_process_sdconf_table
832 #define	sd_sdconf_id_match		ssd_sdconf_id_match
833 #define	sd_blank_cmp			ssd_blank_cmp
834 #define	sd_chk_vers1_data		ssd_chk_vers1_data
835 #define	sd_set_vers1_properties		ssd_set_vers1_properties
836 
837 #define	sd_get_physical_geometry	ssd_get_physical_geometry
838 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
839 #define	sd_update_block_info		ssd_update_block_info
840 #define	sd_register_devid		ssd_register_devid
841 #define	sd_get_devid			ssd_get_devid
842 #define	sd_create_devid			ssd_create_devid
843 #define	sd_write_deviceid		ssd_write_deviceid
844 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
845 #define	sd_setup_pm			ssd_setup_pm
846 #define	sd_create_pm_components		ssd_create_pm_components
847 #define	sd_ddi_suspend			ssd_ddi_suspend
848 #define	sd_ddi_pm_suspend		ssd_ddi_pm_suspend
849 #define	sd_ddi_resume			ssd_ddi_resume
850 #define	sd_ddi_pm_resume		ssd_ddi_pm_resume
851 #define	sdpower				ssdpower
852 #define	sdattach			ssdattach
853 #define	sddetach			ssddetach
854 #define	sd_unit_attach			ssd_unit_attach
855 #define	sd_unit_detach			ssd_unit_detach
856 #define	sd_set_unit_attributes		ssd_set_unit_attributes
857 #define	sd_create_errstats		ssd_create_errstats
858 #define	sd_set_errstats			ssd_set_errstats
859 #define	sd_set_pstats			ssd_set_pstats
860 #define	sddump				ssddump
861 #define	sd_scsi_poll			ssd_scsi_poll
862 #define	sd_send_polled_RQS		ssd_send_polled_RQS
863 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
864 #define	sd_init_event_callbacks		ssd_init_event_callbacks
865 #define	sd_event_callback		ssd_event_callback
866 #define	sd_cache_control		ssd_cache_control
867 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
868 #define	sd_get_nv_sup			ssd_get_nv_sup
869 #define	sd_make_device			ssd_make_device
870 #define	sdopen				ssdopen
871 #define	sdclose				ssdclose
872 #define	sd_ready_and_valid		ssd_ready_and_valid
873 #define	sdmin				ssdmin
874 #define	sdread				ssdread
875 #define	sdwrite				ssdwrite
876 #define	sdaread				ssdaread
877 #define	sdawrite			ssdawrite
878 #define	sdstrategy			ssdstrategy
879 #define	sdioctl				ssdioctl
880 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
881 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
882 #define	sd_checksum_iostart		ssd_checksum_iostart
883 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
884 #define	sd_pm_iostart			ssd_pm_iostart
885 #define	sd_core_iostart			ssd_core_iostart
886 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
887 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
888 #define	sd_checksum_iodone		ssd_checksum_iodone
889 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
890 #define	sd_pm_iodone			ssd_pm_iodone
891 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
892 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
893 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
894 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
895 #define	sd_buf_iodone			ssd_buf_iodone
896 #define	sd_uscsi_strategy		ssd_uscsi_strategy
897 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
898 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
899 #define	sd_uscsi_iodone			ssd_uscsi_iodone
900 #define	sd_xbuf_strategy		ssd_xbuf_strategy
901 #define	sd_xbuf_init			ssd_xbuf_init
902 #define	sd_pm_entry			ssd_pm_entry
903 #define	sd_pm_exit			ssd_pm_exit
904 
905 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
906 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
907 
908 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
909 #define	sdintr				ssdintr
910 #define	sd_start_cmds			ssd_start_cmds
911 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
912 #define	sd_bioclone_alloc		ssd_bioclone_alloc
913 #define	sd_bioclone_free		ssd_bioclone_free
914 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
915 #define	sd_shadow_buf_free		ssd_shadow_buf_free
916 #define	sd_print_transport_rejected_message	\
917 					ssd_print_transport_rejected_message
918 #define	sd_retry_command		ssd_retry_command
919 #define	sd_set_retry_bp			ssd_set_retry_bp
920 #define	sd_send_request_sense_command	ssd_send_request_sense_command
921 #define	sd_start_retry_command		ssd_start_retry_command
922 #define	sd_start_direct_priority_command	\
923 					ssd_start_direct_priority_command
924 #define	sd_return_failed_command	ssd_return_failed_command
925 #define	sd_return_failed_command_no_restart	\
926 					ssd_return_failed_command_no_restart
927 #define	sd_return_command		ssd_return_command
928 #define	sd_sync_with_callback		ssd_sync_with_callback
929 #define	sdrunout			ssdrunout
930 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
931 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
932 #define	sd_reduce_throttle		ssd_reduce_throttle
933 #define	sd_restore_throttle		ssd_restore_throttle
934 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
935 #define	sd_init_cdb_limits		ssd_init_cdb_limits
936 #define	sd_pkt_status_good		ssd_pkt_status_good
937 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
938 #define	sd_pkt_status_busy		ssd_pkt_status_busy
939 #define	sd_pkt_status_reservation_conflict	\
940 					ssd_pkt_status_reservation_conflict
941 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
942 #define	sd_handle_request_sense		ssd_handle_request_sense
943 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
944 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
945 #define	sd_validate_sense_data		ssd_validate_sense_data
946 #define	sd_decode_sense			ssd_decode_sense
947 #define	sd_print_sense_msg		ssd_print_sense_msg
948 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
949 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
950 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
951 #define	sd_sense_key_medium_or_hardware_error	\
952 					ssd_sense_key_medium_or_hardware_error
953 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
954 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
955 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
956 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
957 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
958 #define	sd_sense_key_default		ssd_sense_key_default
959 #define	sd_print_retry_msg		ssd_print_retry_msg
960 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
961 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
962 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
963 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
964 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
965 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
966 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
967 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
968 #define	sd_pkt_reason_default		ssd_pkt_reason_default
969 #define	sd_reset_target			ssd_reset_target
970 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
971 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
972 #define	sd_taskq_create			ssd_taskq_create
973 #define	sd_taskq_delete			ssd_taskq_delete
974 #define	sd_media_change_task		ssd_media_change_task
975 #define	sd_handle_mchange		ssd_handle_mchange
976 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
977 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
978 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
979 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
980 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
981 					sd_send_scsi_feature_GET_CONFIGURATION
982 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
983 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
984 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
985 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
986 					ssd_send_scsi_PERSISTENT_RESERVE_IN
987 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
988 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
989 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
990 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
991 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
992 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
993 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
994 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
995 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
996 #define	sd_alloc_rqs			ssd_alloc_rqs
997 #define	sd_free_rqs			ssd_free_rqs
998 #define	sd_dump_memory			ssd_dump_memory
999 #define	sd_get_media_info		ssd_get_media_info
1000 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
1001 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
1002 #define	sd_setup_next_xfer		ssd_setup_next_xfer
1003 #define	sd_dkio_get_temp		ssd_dkio_get_temp
1004 #define	sd_check_mhd			ssd_check_mhd
1005 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1006 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1007 #define	sd_sname			ssd_sname
1008 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1009 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1010 #define	sd_take_ownership		ssd_take_ownership
1011 #define	sd_reserve_release		ssd_reserve_release
1012 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1013 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1014 #define	sd_persistent_reservation_in_read_keys	\
1015 					ssd_persistent_reservation_in_read_keys
1016 #define	sd_persistent_reservation_in_read_resv	\
1017 					ssd_persistent_reservation_in_read_resv
1018 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1019 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1020 #define	sd_mhdioc_release		ssd_mhdioc_release
1021 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1022 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1023 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1024 #define	sr_change_blkmode		ssr_change_blkmode
1025 #define	sr_change_speed			ssr_change_speed
1026 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1027 #define	sr_pause_resume			ssr_pause_resume
1028 #define	sr_play_msf			ssr_play_msf
1029 #define	sr_play_trkind			ssr_play_trkind
1030 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1031 #define	sr_read_subchannel		ssr_read_subchannel
1032 #define	sr_read_tocentry		ssr_read_tocentry
1033 #define	sr_read_tochdr			ssr_read_tochdr
1034 #define	sr_read_cdda			ssr_read_cdda
1035 #define	sr_read_cdxa			ssr_read_cdxa
1036 #define	sr_read_mode1			ssr_read_mode1
1037 #define	sr_read_mode2			ssr_read_mode2
1038 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1039 #define	sr_sector_mode			ssr_sector_mode
1040 #define	sr_eject			ssr_eject
1041 #define	sr_ejected			ssr_ejected
1042 #define	sr_check_wp			ssr_check_wp
1043 #define	sd_check_media			ssd_check_media
1044 #define	sd_media_watch_cb		ssd_media_watch_cb
1045 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1046 #define	sr_volume_ctrl			ssr_volume_ctrl
1047 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1048 #define	sd_log_page_supported		ssd_log_page_supported
1049 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1050 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1051 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1052 #define	sd_range_lock			ssd_range_lock
1053 #define	sd_get_range			ssd_get_range
1054 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1055 #define	sd_range_unlock			ssd_range_unlock
1056 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1057 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1058 
1059 #define	sd_iostart_chain		ssd_iostart_chain
1060 #define	sd_iodone_chain			ssd_iodone_chain
1061 #define	sd_initpkt_map			ssd_initpkt_map
1062 #define	sd_destroypkt_map		ssd_destroypkt_map
1063 #define	sd_chain_type_map		ssd_chain_type_map
1064 #define	sd_chain_index_map		ssd_chain_index_map
1065 
1066 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1067 #define	sd_failfast_flushq		ssd_failfast_flushq
1068 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1069 
1070 #define	sd_is_lsi			ssd_is_lsi
1071 #define	sd_tg_rdwr			ssd_tg_rdwr
1072 #define	sd_tg_getinfo			ssd_tg_getinfo
1073 
1074 #endif	/* #if (defined(__fibre)) */
1075 
1076 
1077 int _init(void);
1078 int _fini(void);
1079 int _info(struct modinfo *modinfop);
1080 
1081 /*PRINTFLIKE3*/
1082 static void sd_log_trace(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1083 /*PRINTFLIKE3*/
1084 static void sd_log_info(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1085 /*PRINTFLIKE3*/
1086 static void sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1087 
1088 static int sdprobe(dev_info_t *devi);
1089 static int sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
1090     void **result);
1091 static int sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
1092     int mod_flags, char *name, caddr_t valuep, int *lengthp);
1093 
1094 /*
1095  * Smart probe for parallel scsi
1096  */
1097 static void sd_scsi_probe_cache_init(void);
1098 static void sd_scsi_probe_cache_fini(void);
1099 static void sd_scsi_clear_probe_cache(void);
1100 static int  sd_scsi_probe_with_cache(struct scsi_device *devp, int (*fn)());
1101 
1102 /*
1103  * Attached luns on target for parallel scsi
1104  */
1105 static void sd_scsi_target_lun_init(void);
1106 static void sd_scsi_target_lun_fini(void);
1107 static int  sd_scsi_get_target_lun_count(dev_info_t *dip, int target);
1108 static void sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag);
1109 
1110 static int	sd_spin_up_unit(struct sd_lun *un);
1111 #ifdef _LP64
1112 static void	sd_enable_descr_sense(struct sd_lun *un);
1113 static void	sd_reenable_dsense_task(void *arg);
1114 #endif /* _LP64 */
1115 
1116 static void	sd_set_mmc_caps(struct sd_lun *un);
1117 
1118 static void sd_read_unit_properties(struct sd_lun *un);
1119 static int  sd_process_sdconf_file(struct sd_lun *un);
1120 static void sd_get_tunables_from_conf(struct sd_lun *un, int flags,
1121     int *data_list, sd_tunables *values);
1122 static void sd_process_sdconf_table(struct sd_lun *un);
1123 static int  sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen);
1124 static int  sd_blank_cmp(struct sd_lun *un, char *id, int idlen);
1125 static int  sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
1126 	int list_len, char *dataname_ptr);
1127 static void sd_set_vers1_properties(struct sd_lun *un, int flags,
1128     sd_tunables *prop_list);
1129 
1130 static void sd_register_devid(struct sd_lun *un, dev_info_t *devi,
1131     int reservation_flag);
1132 static int  sd_get_devid(struct sd_lun *un);
1133 static ddi_devid_t sd_create_devid(struct sd_lun *un);
1134 static int  sd_write_deviceid(struct sd_lun *un);
1135 static int  sd_get_devid_page(struct sd_lun *un, uchar_t *wwn, int *len);
1136 static int  sd_check_vpd_page_support(struct sd_lun *un);
1137 
1138 static void sd_setup_pm(struct sd_lun *un, dev_info_t *devi);
1139 static void sd_create_pm_components(dev_info_t *devi, struct sd_lun *un);
1140 
1141 static int  sd_ddi_suspend(dev_info_t *devi);
1142 static int  sd_ddi_pm_suspend(struct sd_lun *un);
1143 static int  sd_ddi_resume(dev_info_t *devi);
1144 static int  sd_ddi_pm_resume(struct sd_lun *un);
1145 static int  sdpower(dev_info_t *devi, int component, int level);
1146 
1147 static int  sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd);
1148 static int  sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd);
1149 static int  sd_unit_attach(dev_info_t *devi);
1150 static int  sd_unit_detach(dev_info_t *devi);
1151 
1152 static void sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi);
1153 static void sd_create_errstats(struct sd_lun *un, int instance);
1154 static void sd_set_errstats(struct sd_lun *un);
1155 static void sd_set_pstats(struct sd_lun *un);
1156 
1157 static int  sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
1158 static int  sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pkt);
1159 static int  sd_send_polled_RQS(struct sd_lun *un);
1160 static int  sd_ddi_scsi_poll(struct scsi_pkt *pkt);
1161 
1162 #if (defined(__fibre))
1163 /*
1164  * Event callbacks (photon)
1165  */
1166 static void sd_init_event_callbacks(struct sd_lun *un);
1167 static void  sd_event_callback(dev_info_t *, ddi_eventcookie_t, void *, void *);
1168 #endif
1169 
1170 /*
1171  * Defines for sd_cache_control
1172  */
1173 
1174 #define	SD_CACHE_ENABLE		1
1175 #define	SD_CACHE_DISABLE	0
1176 #define	SD_CACHE_NOCHANGE	-1
1177 
1178 static int   sd_cache_control(struct sd_lun *un, int rcd_flag, int wce_flag);
1179 static int   sd_get_write_cache_enabled(struct sd_lun *un, int *is_enabled);
1180 static void  sd_get_nv_sup(struct sd_lun *un);
1181 static dev_t sd_make_device(dev_info_t *devi);
1182 
1183 static void  sd_update_block_info(struct sd_lun *un, uint32_t lbasize,
1184 	uint64_t capacity);
1185 
1186 /*
1187  * Driver entry point functions.
1188  */
1189 static int  sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p);
1190 static int  sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p);
1191 static int  sd_ready_and_valid(struct sd_lun *un);
1192 
1193 static void sdmin(struct buf *bp);
1194 static int sdread(dev_t dev, struct uio *uio, cred_t *cred_p);
1195 static int sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p);
1196 static int sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1197 static int sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1198 
1199 static int sdstrategy(struct buf *bp);
1200 static int sdioctl(dev_t, int, intptr_t, int, cred_t *, int *);
1201 
1202 /*
1203  * Function prototypes for layering functions in the iostart chain.
1204  */
1205 static void sd_mapblockaddr_iostart(int index, struct sd_lun *un,
1206 	struct buf *bp);
1207 static void sd_mapblocksize_iostart(int index, struct sd_lun *un,
1208 	struct buf *bp);
1209 static void sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp);
1210 static void sd_checksum_uscsi_iostart(int index, struct sd_lun *un,
1211 	struct buf *bp);
1212 static void sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp);
1213 static void sd_core_iostart(int index, struct sd_lun *un, struct buf *bp);
1214 
1215 /*
1216  * Function prototypes for layering functions in the iodone chain.
1217  */
1218 static void sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp);
1219 static void sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp);
1220 static void sd_mapblockaddr_iodone(int index, struct sd_lun *un,
1221 	struct buf *bp);
1222 static void sd_mapblocksize_iodone(int index, struct sd_lun *un,
1223 	struct buf *bp);
1224 static void sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp);
1225 static void sd_checksum_uscsi_iodone(int index, struct sd_lun *un,
1226 	struct buf *bp);
1227 static void sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp);
1228 
1229 /*
1230  * Prototypes for functions to support buf(9S) based IO.
1231  */
1232 static void sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg);
1233 static int sd_initpkt_for_buf(struct buf *, struct scsi_pkt **);
1234 static void sd_destroypkt_for_buf(struct buf *);
1235 static int sd_setup_rw_pkt(struct sd_lun *un, struct scsi_pkt **pktpp,
1236 	struct buf *bp, int flags,
1237 	int (*callback)(caddr_t), caddr_t callback_arg,
1238 	diskaddr_t lba, uint32_t blockcount);
1239 #if defined(__i386) || defined(__amd64)
1240 static int sd_setup_next_rw_pkt(struct sd_lun *un, struct scsi_pkt *pktp,
1241 	struct buf *bp, diskaddr_t lba, uint32_t blockcount);
1242 #endif /* defined(__i386) || defined(__amd64) */
1243 
1244 /*
1245  * Prototypes for functions to support USCSI IO.
1246  */
1247 static int sd_uscsi_strategy(struct buf *bp);
1248 static int sd_initpkt_for_uscsi(struct buf *, struct scsi_pkt **);
1249 static void sd_destroypkt_for_uscsi(struct buf *);
1250 
1251 static void sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
1252 	uchar_t chain_type, void *pktinfop);
1253 
1254 static int  sd_pm_entry(struct sd_lun *un);
1255 static void sd_pm_exit(struct sd_lun *un);
1256 
1257 static void sd_pm_idletimeout_handler(void *arg);
1258 
1259 /*
1260  * sd_core internal functions (used at the sd_core_io layer).
1261  */
1262 static void sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp);
1263 static void sdintr(struct scsi_pkt *pktp);
1264 static void sd_start_cmds(struct sd_lun *un, struct buf *immed_bp);
1265 
1266 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1267 	enum uio_seg dataspace, int path_flag);
1268 
1269 static struct buf *sd_bioclone_alloc(struct buf *bp, size_t datalen,
1270 	daddr_t blkno, int (*func)(struct buf *));
1271 static struct buf *sd_shadow_buf_alloc(struct buf *bp, size_t datalen,
1272 	uint_t bflags, daddr_t blkno, int (*func)(struct buf *));
1273 static void sd_bioclone_free(struct buf *bp);
1274 static void sd_shadow_buf_free(struct buf *bp);
1275 
1276 static void sd_print_transport_rejected_message(struct sd_lun *un,
1277 	struct sd_xbuf *xp, int code);
1278 static void sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp,
1279     void *arg, int code);
1280 static void sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp,
1281     void *arg, int code);
1282 static void sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp,
1283     void *arg, int code);
1284 
1285 static void sd_retry_command(struct sd_lun *un, struct buf *bp,
1286 	int retry_check_flag,
1287 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp,
1288 		int c),
1289 	void *user_arg, int failure_code,  clock_t retry_delay,
1290 	void (*statp)(kstat_io_t *));
1291 
1292 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1293 	clock_t retry_delay, void (*statp)(kstat_io_t *));
1294 
1295 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1296 	struct scsi_pkt *pktp);
1297 static void sd_start_retry_command(void *arg);
1298 static void sd_start_direct_priority_command(void *arg);
1299 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1300 	int errcode);
1301 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1302 	struct buf *bp, int errcode);
1303 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1304 static void sd_sync_with_callback(struct sd_lun *un);
1305 static int sdrunout(caddr_t arg);
1306 
1307 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1308 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1309 
1310 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1311 static void sd_restore_throttle(void *arg);
1312 
1313 static void sd_init_cdb_limits(struct sd_lun *un);
1314 
1315 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1316 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1317 
1318 /*
1319  * Error handling functions
1320  */
1321 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1322 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1323 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1324 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1325 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1326 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1327 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1328 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1329 
1330 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1331 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1332 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1333 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1334 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1335 	struct sd_xbuf *xp, size_t actual_len);
1336 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1337 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1338 
1339 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1340 	void *arg, int code);
1341 
1342 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1343 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1344 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1345 	uint8_t *sense_datap,
1346 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1347 static void sd_sense_key_not_ready(struct sd_lun *un,
1348 	uint8_t *sense_datap,
1349 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1350 static void sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
1351 	uint8_t *sense_datap,
1352 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1353 static void sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
1354 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1355 static void sd_sense_key_unit_attention(struct sd_lun *un,
1356 	uint8_t *sense_datap,
1357 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1358 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1359 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1360 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1361 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1362 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1363 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1364 static void sd_sense_key_default(struct sd_lun *un,
1365 	uint8_t *sense_datap,
1366 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1367 
1368 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1369 	void *arg, int flag);
1370 
1371 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1372 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1373 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1374 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1375 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1376 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1377 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1378 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1379 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1380 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1381 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1382 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1383 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1384 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1385 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1386 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1387 
1388 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1389 
1390 static void sd_start_stop_unit_callback(void *arg);
1391 static void sd_start_stop_unit_task(void *arg);
1392 
1393 static void sd_taskq_create(void);
1394 static void sd_taskq_delete(void);
1395 static void sd_media_change_task(void *arg);
1396 
1397 static int sd_handle_mchange(struct sd_lun *un);
1398 static int sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag);
1399 static int sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp,
1400 	uint32_t *lbap, int path_flag);
1401 static int sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
1402 	uint32_t *lbap, int path_flag);
1403 static int sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag,
1404 	int path_flag);
1405 static int sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr,
1406 	size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1407 static int sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag);
1408 static int sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un,
1409 	uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1410 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un,
1411 	uchar_t usr_cmd, uchar_t *usr_bufp);
1412 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1413 	struct dk_callback *dkc);
1414 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1415 static int sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un,
1416 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1417 	uchar_t *bufaddr, uint_t buflen, int path_flag);
1418 static int sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
1419 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1420 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag);
1421 static int sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize,
1422 	uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1423 static int sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize,
1424 	uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1425 static int sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
1426 	size_t buflen, daddr_t start_block, int path_flag);
1427 #define	sd_send_scsi_READ(un, bufaddr, buflen, start_block, path_flag)	\
1428 	sd_send_scsi_RDWR(un, SCMD_READ, bufaddr, buflen, start_block, \
1429 	path_flag)
1430 #define	sd_send_scsi_WRITE(un, bufaddr, buflen, start_block, path_flag)	\
1431 	sd_send_scsi_RDWR(un, SCMD_WRITE, bufaddr, buflen, start_block,\
1432 	path_flag)
1433 
1434 static int sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr,
1435 	uint16_t buflen, uchar_t page_code, uchar_t page_control,
1436 	uint16_t param_ptr, int path_flag);
1437 
1438 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1439 static void sd_free_rqs(struct sd_lun *un);
1440 
1441 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1442 	uchar_t *data, int len, int fmt);
1443 static void sd_panic_for_res_conflict(struct sd_lun *un);
1444 
1445 /*
1446  * Disk Ioctl Function Prototypes
1447  */
1448 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1449 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1450 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1451 
1452 /*
1453  * Multi-host Ioctl Prototypes
1454  */
1455 static int sd_check_mhd(dev_t dev, int interval);
1456 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1457 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1458 static char *sd_sname(uchar_t status);
1459 static void sd_mhd_resvd_recover(void *arg);
1460 static void sd_resv_reclaim_thread();
1461 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1462 static int sd_reserve_release(dev_t dev, int cmd);
1463 static void sd_rmv_resv_reclaim_req(dev_t dev);
1464 static void sd_mhd_reset_notify_cb(caddr_t arg);
1465 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1466 	mhioc_inkeys_t *usrp, int flag);
1467 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1468 	mhioc_inresvs_t *usrp, int flag);
1469 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1470 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1471 static int sd_mhdioc_release(dev_t dev);
1472 static int sd_mhdioc_register_devid(dev_t dev);
1473 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1474 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1475 
1476 /*
1477  * SCSI removable prototypes
1478  */
1479 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1480 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1481 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1482 static int sr_pause_resume(dev_t dev, int mode);
1483 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1484 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1485 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1486 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1487 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1488 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1489 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1490 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1491 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1492 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1493 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1494 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1495 static int sr_eject(dev_t dev);
1496 static void sr_ejected(register struct sd_lun *un);
1497 static int sr_check_wp(dev_t dev);
1498 static int sd_check_media(dev_t dev, enum dkio_state state);
1499 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1500 static void sd_delayed_cv_broadcast(void *arg);
1501 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1502 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1503 
1504 static int sd_log_page_supported(struct sd_lun *un, int log_page);
1505 
1506 /*
1507  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1508  */
1509 static void sd_check_for_writable_cd(struct sd_lun *un, int path_flag);
1510 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1511 static void sd_wm_cache_destructor(void *wm, void *un);
1512 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1513 	daddr_t endb, ushort_t typ);
1514 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1515 	daddr_t endb);
1516 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1517 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1518 static void sd_read_modify_write_task(void * arg);
1519 static int
1520 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1521 	struct buf **bpp);
1522 
1523 
1524 /*
1525  * Function prototypes for failfast support.
1526  */
1527 static void sd_failfast_flushq(struct sd_lun *un);
1528 static int sd_failfast_flushq_callback(struct buf *bp);
1529 
1530 /*
1531  * Function prototypes to check for lsi devices
1532  */
1533 static void sd_is_lsi(struct sd_lun *un);
1534 
1535 /*
1536  * Function prototypes for x86 support
1537  */
1538 #if defined(__i386) || defined(__amd64)
1539 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1540 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1541 #endif
1542 
1543 
1544 /* Function prototypes for cmlb */
1545 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1546     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1547 
1548 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1549 
1550 /*
1551  * Constants for failfast support:
1552  *
1553  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1554  * failfast processing being performed.
1555  *
1556  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1557  * failfast processing on all bufs with B_FAILFAST set.
1558  */
1559 
1560 #define	SD_FAILFAST_INACTIVE		0
1561 #define	SD_FAILFAST_ACTIVE		1
1562 
1563 /*
1564  * Bitmask to control behavior of buf(9S) flushes when a transition to
1565  * the failfast state occurs. Optional bits include:
1566  *
1567  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1568  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1569  * be flushed.
1570  *
1571  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1572  * driver, in addition to the regular wait queue. This includes the xbuf
1573  * queues. When clear, only the driver's wait queue will be flushed.
1574  */
1575 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1576 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1577 
1578 /*
1579  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1580  * to flush all queues within the driver.
1581  */
1582 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1583 
1584 
1585 /*
1586  * SD Testing Fault Injection
1587  */
1588 #ifdef SD_FAULT_INJECTION
1589 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1590 static void sd_faultinjection(struct scsi_pkt *pktp);
1591 static void sd_injection_log(char *buf, struct sd_lun *un);
1592 #endif
1593 
1594 /*
1595  * Device driver ops vector
1596  */
1597 static struct cb_ops sd_cb_ops = {
1598 	sdopen,			/* open */
1599 	sdclose,		/* close */
1600 	sdstrategy,		/* strategy */
1601 	nodev,			/* print */
1602 	sddump,			/* dump */
1603 	sdread,			/* read */
1604 	sdwrite,		/* write */
1605 	sdioctl,		/* ioctl */
1606 	nodev,			/* devmap */
1607 	nodev,			/* mmap */
1608 	nodev,			/* segmap */
1609 	nochpoll,		/* poll */
1610 	sd_prop_op,		/* cb_prop_op */
1611 	0,			/* streamtab  */
1612 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1613 	CB_REV,			/* cb_rev */
1614 	sdaread, 		/* async I/O read entry point */
1615 	sdawrite		/* async I/O write entry point */
1616 };
1617 
1618 static struct dev_ops sd_ops = {
1619 	DEVO_REV,		/* devo_rev, */
1620 	0,			/* refcnt  */
1621 	sdinfo,			/* info */
1622 	nulldev,		/* identify */
1623 	sdprobe,		/* probe */
1624 	sdattach,		/* attach */
1625 	sddetach,		/* detach */
1626 	nodev,			/* reset */
1627 	&sd_cb_ops,		/* driver operations */
1628 	NULL,			/* bus operations */
1629 	sdpower			/* power */
1630 };
1631 
1632 
1633 /*
1634  * This is the loadable module wrapper.
1635  */
1636 #include <sys/modctl.h>
1637 
1638 static struct modldrv modldrv = {
1639 	&mod_driverops,		/* Type of module. This one is a driver */
1640 	SD_MODULE_NAME,		/* Module name. */
1641 	&sd_ops			/* driver ops */
1642 };
1643 
1644 
1645 static struct modlinkage modlinkage = {
1646 	MODREV_1,
1647 	&modldrv,
1648 	NULL
1649 };
1650 
1651 static cmlb_tg_ops_t sd_tgops = {
1652 	TG_DK_OPS_VERSION_1,
1653 	sd_tg_rdwr,
1654 	sd_tg_getinfo
1655 	};
1656 
1657 static struct scsi_asq_key_strings sd_additional_codes[] = {
1658 	0x81, 0, "Logical Unit is Reserved",
1659 	0x85, 0, "Audio Address Not Valid",
1660 	0xb6, 0, "Media Load Mechanism Failed",
1661 	0xB9, 0, "Audio Play Operation Aborted",
1662 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1663 	0x53, 2, "Medium removal prevented",
1664 	0x6f, 0, "Authentication failed during key exchange",
1665 	0x6f, 1, "Key not present",
1666 	0x6f, 2, "Key not established",
1667 	0x6f, 3, "Read without proper authentication",
1668 	0x6f, 4, "Mismatched region to this logical unit",
1669 	0x6f, 5, "Region reset count error",
1670 	0xffff, 0x0, NULL
1671 };
1672 
1673 
1674 /*
1675  * Struct for passing printing information for sense data messages
1676  */
1677 struct sd_sense_info {
1678 	int	ssi_severity;
1679 	int	ssi_pfa_flag;
1680 };
1681 
1682 /*
1683  * Table of function pointers for iostart-side routines. Separate "chains"
1684  * of layered function calls are formed by placing the function pointers
1685  * sequentially in the desired order. Functions are called according to an
1686  * incrementing table index ordering. The last function in each chain must
1687  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1688  * in the sd_iodone_chain[] array.
1689  *
1690  * Note: It may seem more natural to organize both the iostart and iodone
1691  * functions together, into an array of structures (or some similar
1692  * organization) with a common index, rather than two separate arrays which
1693  * must be maintained in synchronization. The purpose of this division is
1694  * to achieve improved performance: individual arrays allows for more
1695  * effective cache line utilization on certain platforms.
1696  */
1697 
1698 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1699 
1700 
1701 static sd_chain_t sd_iostart_chain[] = {
1702 
1703 	/* Chain for buf IO for disk drive targets (PM enabled) */
1704 	sd_mapblockaddr_iostart,	/* Index: 0 */
1705 	sd_pm_iostart,			/* Index: 1 */
1706 	sd_core_iostart,		/* Index: 2 */
1707 
1708 	/* Chain for buf IO for disk drive targets (PM disabled) */
1709 	sd_mapblockaddr_iostart,	/* Index: 3 */
1710 	sd_core_iostart,		/* Index: 4 */
1711 
1712 	/* Chain for buf IO for removable-media targets (PM enabled) */
1713 	sd_mapblockaddr_iostart,	/* Index: 5 */
1714 	sd_mapblocksize_iostart,	/* Index: 6 */
1715 	sd_pm_iostart,			/* Index: 7 */
1716 	sd_core_iostart,		/* Index: 8 */
1717 
1718 	/* Chain for buf IO for removable-media targets (PM disabled) */
1719 	sd_mapblockaddr_iostart,	/* Index: 9 */
1720 	sd_mapblocksize_iostart,	/* Index: 10 */
1721 	sd_core_iostart,		/* Index: 11 */
1722 
1723 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1724 	sd_mapblockaddr_iostart,	/* Index: 12 */
1725 	sd_checksum_iostart,		/* Index: 13 */
1726 	sd_pm_iostart,			/* Index: 14 */
1727 	sd_core_iostart,		/* Index: 15 */
1728 
1729 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1730 	sd_mapblockaddr_iostart,	/* Index: 16 */
1731 	sd_checksum_iostart,		/* Index: 17 */
1732 	sd_core_iostart,		/* Index: 18 */
1733 
1734 	/* Chain for USCSI commands (all targets) */
1735 	sd_pm_iostart,			/* Index: 19 */
1736 	sd_core_iostart,		/* Index: 20 */
1737 
1738 	/* Chain for checksumming USCSI commands (all targets) */
1739 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1740 	sd_pm_iostart,			/* Index: 22 */
1741 	sd_core_iostart,		/* Index: 23 */
1742 
1743 	/* Chain for "direct" USCSI commands (all targets) */
1744 	sd_core_iostart,		/* Index: 24 */
1745 
1746 	/* Chain for "direct priority" USCSI commands (all targets) */
1747 	sd_core_iostart,		/* Index: 25 */
1748 };
1749 
1750 /*
1751  * Macros to locate the first function of each iostart chain in the
1752  * sd_iostart_chain[] array. These are located by the index in the array.
1753  */
1754 #define	SD_CHAIN_DISK_IOSTART			0
1755 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1756 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1757 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1758 #define	SD_CHAIN_CHKSUM_IOSTART			12
1759 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1760 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1761 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1762 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1763 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1764 
1765 
1766 /*
1767  * Table of function pointers for the iodone-side routines for the driver-
1768  * internal layering mechanism.  The calling sequence for iodone routines
1769  * uses a decrementing table index, so the last routine called in a chain
1770  * must be at the lowest array index location for that chain.  The last
1771  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1772  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1773  * of the functions in an iodone side chain must correspond to the ordering
1774  * of the iostart routines for that chain.  Note that there is no iodone
1775  * side routine that corresponds to sd_core_iostart(), so there is no
1776  * entry in the table for this.
1777  */
1778 
1779 static sd_chain_t sd_iodone_chain[] = {
1780 
1781 	/* Chain for buf IO for disk drive targets (PM enabled) */
1782 	sd_buf_iodone,			/* Index: 0 */
1783 	sd_mapblockaddr_iodone,		/* Index: 1 */
1784 	sd_pm_iodone,			/* Index: 2 */
1785 
1786 	/* Chain for buf IO for disk drive targets (PM disabled) */
1787 	sd_buf_iodone,			/* Index: 3 */
1788 	sd_mapblockaddr_iodone,		/* Index: 4 */
1789 
1790 	/* Chain for buf IO for removable-media targets (PM enabled) */
1791 	sd_buf_iodone,			/* Index: 5 */
1792 	sd_mapblockaddr_iodone,		/* Index: 6 */
1793 	sd_mapblocksize_iodone,		/* Index: 7 */
1794 	sd_pm_iodone,			/* Index: 8 */
1795 
1796 	/* Chain for buf IO for removable-media targets (PM disabled) */
1797 	sd_buf_iodone,			/* Index: 9 */
1798 	sd_mapblockaddr_iodone,		/* Index: 10 */
1799 	sd_mapblocksize_iodone,		/* Index: 11 */
1800 
1801 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1802 	sd_buf_iodone,			/* Index: 12 */
1803 	sd_mapblockaddr_iodone,		/* Index: 13 */
1804 	sd_checksum_iodone,		/* Index: 14 */
1805 	sd_pm_iodone,			/* Index: 15 */
1806 
1807 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1808 	sd_buf_iodone,			/* Index: 16 */
1809 	sd_mapblockaddr_iodone,		/* Index: 17 */
1810 	sd_checksum_iodone,		/* Index: 18 */
1811 
1812 	/* Chain for USCSI commands (non-checksum targets) */
1813 	sd_uscsi_iodone,		/* Index: 19 */
1814 	sd_pm_iodone,			/* Index: 20 */
1815 
1816 	/* Chain for USCSI commands (checksum targets) */
1817 	sd_uscsi_iodone,		/* Index: 21 */
1818 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1819 	sd_pm_iodone,			/* Index: 22 */
1820 
1821 	/* Chain for "direct" USCSI commands (all targets) */
1822 	sd_uscsi_iodone,		/* Index: 24 */
1823 
1824 	/* Chain for "direct priority" USCSI commands (all targets) */
1825 	sd_uscsi_iodone,		/* Index: 25 */
1826 };
1827 
1828 
1829 /*
1830  * Macros to locate the "first" function in the sd_iodone_chain[] array for
1831  * each iodone-side chain. These are located by the array index, but as the
1832  * iodone side functions are called in a decrementing-index order, the
1833  * highest index number in each chain must be specified (as these correspond
1834  * to the first function in the iodone chain that will be called by the core
1835  * at IO completion time).
1836  */
1837 
1838 #define	SD_CHAIN_DISK_IODONE			2
1839 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
1840 #define	SD_CHAIN_RMMEDIA_IODONE			8
1841 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
1842 #define	SD_CHAIN_CHKSUM_IODONE			15
1843 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
1844 #define	SD_CHAIN_USCSI_CMD_IODONE		20
1845 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
1846 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
1847 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
1848 
1849 
1850 
1851 
1852 /*
1853  * Array to map a layering chain index to the appropriate initpkt routine.
1854  * The redundant entries are present so that the index used for accessing
1855  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1856  * with this table as well.
1857  */
1858 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
1859 
1860 static sd_initpkt_t	sd_initpkt_map[] = {
1861 
1862 	/* Chain for buf IO for disk drive targets (PM enabled) */
1863 	sd_initpkt_for_buf,		/* Index: 0 */
1864 	sd_initpkt_for_buf,		/* Index: 1 */
1865 	sd_initpkt_for_buf,		/* Index: 2 */
1866 
1867 	/* Chain for buf IO for disk drive targets (PM disabled) */
1868 	sd_initpkt_for_buf,		/* Index: 3 */
1869 	sd_initpkt_for_buf,		/* Index: 4 */
1870 
1871 	/* Chain for buf IO for removable-media targets (PM enabled) */
1872 	sd_initpkt_for_buf,		/* Index: 5 */
1873 	sd_initpkt_for_buf,		/* Index: 6 */
1874 	sd_initpkt_for_buf,		/* Index: 7 */
1875 	sd_initpkt_for_buf,		/* Index: 8 */
1876 
1877 	/* Chain for buf IO for removable-media targets (PM disabled) */
1878 	sd_initpkt_for_buf,		/* Index: 9 */
1879 	sd_initpkt_for_buf,		/* Index: 10 */
1880 	sd_initpkt_for_buf,		/* Index: 11 */
1881 
1882 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1883 	sd_initpkt_for_buf,		/* Index: 12 */
1884 	sd_initpkt_for_buf,		/* Index: 13 */
1885 	sd_initpkt_for_buf,		/* Index: 14 */
1886 	sd_initpkt_for_buf,		/* Index: 15 */
1887 
1888 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1889 	sd_initpkt_for_buf,		/* Index: 16 */
1890 	sd_initpkt_for_buf,		/* Index: 17 */
1891 	sd_initpkt_for_buf,		/* Index: 18 */
1892 
1893 	/* Chain for USCSI commands (non-checksum targets) */
1894 	sd_initpkt_for_uscsi,		/* Index: 19 */
1895 	sd_initpkt_for_uscsi,		/* Index: 20 */
1896 
1897 	/* Chain for USCSI commands (checksum targets) */
1898 	sd_initpkt_for_uscsi,		/* Index: 21 */
1899 	sd_initpkt_for_uscsi,		/* Index: 22 */
1900 	sd_initpkt_for_uscsi,		/* Index: 22 */
1901 
1902 	/* Chain for "direct" USCSI commands (all targets) */
1903 	sd_initpkt_for_uscsi,		/* Index: 24 */
1904 
1905 	/* Chain for "direct priority" USCSI commands (all targets) */
1906 	sd_initpkt_for_uscsi,		/* Index: 25 */
1907 
1908 };
1909 
1910 
1911 /*
1912  * Array to map a layering chain index to the appropriate destroypktpkt routine.
1913  * The redundant entries are present so that the index used for accessing
1914  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1915  * with this table as well.
1916  */
1917 typedef void (*sd_destroypkt_t)(struct buf *);
1918 
1919 static sd_destroypkt_t	sd_destroypkt_map[] = {
1920 
1921 	/* Chain for buf IO for disk drive targets (PM enabled) */
1922 	sd_destroypkt_for_buf,		/* Index: 0 */
1923 	sd_destroypkt_for_buf,		/* Index: 1 */
1924 	sd_destroypkt_for_buf,		/* Index: 2 */
1925 
1926 	/* Chain for buf IO for disk drive targets (PM disabled) */
1927 	sd_destroypkt_for_buf,		/* Index: 3 */
1928 	sd_destroypkt_for_buf,		/* Index: 4 */
1929 
1930 	/* Chain for buf IO for removable-media targets (PM enabled) */
1931 	sd_destroypkt_for_buf,		/* Index: 5 */
1932 	sd_destroypkt_for_buf,		/* Index: 6 */
1933 	sd_destroypkt_for_buf,		/* Index: 7 */
1934 	sd_destroypkt_for_buf,		/* Index: 8 */
1935 
1936 	/* Chain for buf IO for removable-media targets (PM disabled) */
1937 	sd_destroypkt_for_buf,		/* Index: 9 */
1938 	sd_destroypkt_for_buf,		/* Index: 10 */
1939 	sd_destroypkt_for_buf,		/* Index: 11 */
1940 
1941 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1942 	sd_destroypkt_for_buf,		/* Index: 12 */
1943 	sd_destroypkt_for_buf,		/* Index: 13 */
1944 	sd_destroypkt_for_buf,		/* Index: 14 */
1945 	sd_destroypkt_for_buf,		/* Index: 15 */
1946 
1947 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1948 	sd_destroypkt_for_buf,		/* Index: 16 */
1949 	sd_destroypkt_for_buf,		/* Index: 17 */
1950 	sd_destroypkt_for_buf,		/* Index: 18 */
1951 
1952 	/* Chain for USCSI commands (non-checksum targets) */
1953 	sd_destroypkt_for_uscsi,	/* Index: 19 */
1954 	sd_destroypkt_for_uscsi,	/* Index: 20 */
1955 
1956 	/* Chain for USCSI commands (checksum targets) */
1957 	sd_destroypkt_for_uscsi,	/* Index: 21 */
1958 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1959 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1960 
1961 	/* Chain for "direct" USCSI commands (all targets) */
1962 	sd_destroypkt_for_uscsi,	/* Index: 24 */
1963 
1964 	/* Chain for "direct priority" USCSI commands (all targets) */
1965 	sd_destroypkt_for_uscsi,	/* Index: 25 */
1966 
1967 };
1968 
1969 
1970 
1971 /*
1972  * Array to map a layering chain index to the appropriate chain "type".
1973  * The chain type indicates a specific property/usage of the chain.
1974  * The redundant entries are present so that the index used for accessing
1975  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1976  * with this table as well.
1977  */
1978 
1979 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
1980 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
1981 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
1982 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
1983 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
1984 						/* (for error recovery) */
1985 
1986 static int sd_chain_type_map[] = {
1987 
1988 	/* Chain for buf IO for disk drive targets (PM enabled) */
1989 	SD_CHAIN_BUFIO,			/* Index: 0 */
1990 	SD_CHAIN_BUFIO,			/* Index: 1 */
1991 	SD_CHAIN_BUFIO,			/* Index: 2 */
1992 
1993 	/* Chain for buf IO for disk drive targets (PM disabled) */
1994 	SD_CHAIN_BUFIO,			/* Index: 3 */
1995 	SD_CHAIN_BUFIO,			/* Index: 4 */
1996 
1997 	/* Chain for buf IO for removable-media targets (PM enabled) */
1998 	SD_CHAIN_BUFIO,			/* Index: 5 */
1999 	SD_CHAIN_BUFIO,			/* Index: 6 */
2000 	SD_CHAIN_BUFIO,			/* Index: 7 */
2001 	SD_CHAIN_BUFIO,			/* Index: 8 */
2002 
2003 	/* Chain for buf IO for removable-media targets (PM disabled) */
2004 	SD_CHAIN_BUFIO,			/* Index: 9 */
2005 	SD_CHAIN_BUFIO,			/* Index: 10 */
2006 	SD_CHAIN_BUFIO,			/* Index: 11 */
2007 
2008 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2009 	SD_CHAIN_BUFIO,			/* Index: 12 */
2010 	SD_CHAIN_BUFIO,			/* Index: 13 */
2011 	SD_CHAIN_BUFIO,			/* Index: 14 */
2012 	SD_CHAIN_BUFIO,			/* Index: 15 */
2013 
2014 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2015 	SD_CHAIN_BUFIO,			/* Index: 16 */
2016 	SD_CHAIN_BUFIO,			/* Index: 17 */
2017 	SD_CHAIN_BUFIO,			/* Index: 18 */
2018 
2019 	/* Chain for USCSI commands (non-checksum targets) */
2020 	SD_CHAIN_USCSI,			/* Index: 19 */
2021 	SD_CHAIN_USCSI,			/* Index: 20 */
2022 
2023 	/* Chain for USCSI commands (checksum targets) */
2024 	SD_CHAIN_USCSI,			/* Index: 21 */
2025 	SD_CHAIN_USCSI,			/* Index: 22 */
2026 	SD_CHAIN_USCSI,			/* Index: 22 */
2027 
2028 	/* Chain for "direct" USCSI commands (all targets) */
2029 	SD_CHAIN_DIRECT,		/* Index: 24 */
2030 
2031 	/* Chain for "direct priority" USCSI commands (all targets) */
2032 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2033 };
2034 
2035 
2036 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2037 #define	SD_IS_BUFIO(xp)			\
2038 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2039 
2040 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2041 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2042 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2043 
2044 
2045 
2046 /*
2047  * Struct, array, and macros to map a specific chain to the appropriate
2048  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2049  *
2050  * The sd_chain_index_map[] array is used at attach time to set the various
2051  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2052  * chain to be used with the instance. This allows different instances to use
2053  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2054  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2055  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2056  * dynamically & without the use of locking; and (2) a layer may update the
2057  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2058  * to allow for deferred processing of an IO within the same chain from a
2059  * different execution context.
2060  */
2061 
2062 struct sd_chain_index {
2063 	int	sci_iostart_index;
2064 	int	sci_iodone_index;
2065 };
2066 
2067 static struct sd_chain_index	sd_chain_index_map[] = {
2068 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2069 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2070 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2071 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2072 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2073 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2074 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2075 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2076 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2077 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2078 };
2079 
2080 
2081 /*
2082  * The following are indexes into the sd_chain_index_map[] array.
2083  */
2084 
2085 /* un->un_buf_chain_type must be set to one of these */
2086 #define	SD_CHAIN_INFO_DISK		0
2087 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2088 #define	SD_CHAIN_INFO_RMMEDIA		2
2089 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2090 #define	SD_CHAIN_INFO_CHKSUM		4
2091 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2092 
2093 /* un->un_uscsi_chain_type must be set to one of these */
2094 #define	SD_CHAIN_INFO_USCSI_CMD		6
2095 /* USCSI with PM disabled is the same as DIRECT */
2096 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2097 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2098 
2099 /* un->un_direct_chain_type must be set to one of these */
2100 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2101 
2102 /* un->un_priority_chain_type must be set to one of these */
2103 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2104 
2105 /* size for devid inquiries */
2106 #define	MAX_INQUIRY_SIZE		0xF0
2107 
2108 /*
2109  * Macros used by functions to pass a given buf(9S) struct along to the
2110  * next function in the layering chain for further processing.
2111  *
2112  * In the following macros, passing more than three arguments to the called
2113  * routines causes the optimizer for the SPARC compiler to stop doing tail
2114  * call elimination which results in significant performance degradation.
2115  */
2116 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2117 	((*(sd_iostart_chain[index]))(index, un, bp))
2118 
2119 #define	SD_BEGIN_IODONE(index, un, bp)	\
2120 	((*(sd_iodone_chain[index]))(index, un, bp))
2121 
2122 #define	SD_NEXT_IOSTART(index, un, bp)				\
2123 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2124 
2125 #define	SD_NEXT_IODONE(index, un, bp)				\
2126 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2127 
2128 /*
2129  *    Function: _init
2130  *
2131  * Description: This is the driver _init(9E) entry point.
2132  *
2133  * Return Code: Returns the value from mod_install(9F) or
2134  *		ddi_soft_state_init(9F) as appropriate.
2135  *
2136  *     Context: Called when driver module loaded.
2137  */
2138 
2139 int
2140 _init(void)
2141 {
2142 	int	err;
2143 
2144 	/* establish driver name from module name */
2145 	sd_label = mod_modname(&modlinkage);
2146 
2147 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2148 	    SD_MAXUNIT);
2149 
2150 	if (err != 0) {
2151 		return (err);
2152 	}
2153 
2154 	mutex_init(&sd_detach_mutex, NULL, MUTEX_DRIVER, NULL);
2155 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2156 	mutex_init(&sd_label_mutex,  NULL, MUTEX_DRIVER, NULL);
2157 
2158 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2159 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2160 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2161 
2162 	/*
2163 	 * it's ok to init here even for fibre device
2164 	 */
2165 	sd_scsi_probe_cache_init();
2166 
2167 	sd_scsi_target_lun_init();
2168 
2169 	/*
2170 	 * Creating taskq before mod_install ensures that all callers (threads)
2171 	 * that enter the module after a successfull mod_install encounter
2172 	 * a valid taskq.
2173 	 */
2174 	sd_taskq_create();
2175 
2176 	err = mod_install(&modlinkage);
2177 	if (err != 0) {
2178 		/* delete taskq if install fails */
2179 		sd_taskq_delete();
2180 
2181 		mutex_destroy(&sd_detach_mutex);
2182 		mutex_destroy(&sd_log_mutex);
2183 		mutex_destroy(&sd_label_mutex);
2184 
2185 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2186 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2187 		cv_destroy(&sd_tr.srq_inprocess_cv);
2188 
2189 		sd_scsi_probe_cache_fini();
2190 
2191 		sd_scsi_target_lun_fini();
2192 
2193 		ddi_soft_state_fini(&sd_state);
2194 		return (err);
2195 	}
2196 
2197 	return (err);
2198 }
2199 
2200 
2201 /*
2202  *    Function: _fini
2203  *
2204  * Description: This is the driver _fini(9E) entry point.
2205  *
2206  * Return Code: Returns the value from mod_remove(9F)
2207  *
2208  *     Context: Called when driver module is unloaded.
2209  */
2210 
2211 int
2212 _fini(void)
2213 {
2214 	int err;
2215 
2216 	if ((err = mod_remove(&modlinkage)) != 0) {
2217 		return (err);
2218 	}
2219 
2220 	sd_taskq_delete();
2221 
2222 	mutex_destroy(&sd_detach_mutex);
2223 	mutex_destroy(&sd_log_mutex);
2224 	mutex_destroy(&sd_label_mutex);
2225 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2226 
2227 	sd_scsi_probe_cache_fini();
2228 
2229 	sd_scsi_target_lun_fini();
2230 
2231 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2232 	cv_destroy(&sd_tr.srq_inprocess_cv);
2233 
2234 	ddi_soft_state_fini(&sd_state);
2235 
2236 	return (err);
2237 }
2238 
2239 
2240 /*
2241  *    Function: _info
2242  *
2243  * Description: This is the driver _info(9E) entry point.
2244  *
2245  *   Arguments: modinfop - pointer to the driver modinfo structure
2246  *
2247  * Return Code: Returns the value from mod_info(9F).
2248  *
2249  *     Context: Kernel thread context
2250  */
2251 
2252 int
2253 _info(struct modinfo *modinfop)
2254 {
2255 	return (mod_info(&modlinkage, modinfop));
2256 }
2257 
2258 
2259 /*
2260  * The following routines implement the driver message logging facility.
2261  * They provide component- and level- based debug output filtering.
2262  * Output may also be restricted to messages for a single instance by
2263  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2264  * to NULL, then messages for all instances are printed.
2265  *
2266  * These routines have been cloned from each other due to the language
2267  * constraints of macros and variable argument list processing.
2268  */
2269 
2270 
2271 /*
2272  *    Function: sd_log_err
2273  *
2274  * Description: This routine is called by the SD_ERROR macro for debug
2275  *		logging of error conditions.
2276  *
2277  *   Arguments: comp - driver component being logged
2278  *		dev  - pointer to driver info structure
2279  *		fmt  - error string and format to be logged
2280  */
2281 
2282 static void
2283 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2284 {
2285 	va_list		ap;
2286 	dev_info_t	*dev;
2287 
2288 	ASSERT(un != NULL);
2289 	dev = SD_DEVINFO(un);
2290 	ASSERT(dev != NULL);
2291 
2292 	/*
2293 	 * Filter messages based on the global component and level masks.
2294 	 * Also print if un matches the value of sd_debug_un, or if
2295 	 * sd_debug_un is set to NULL.
2296 	 */
2297 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2298 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2299 		mutex_enter(&sd_log_mutex);
2300 		va_start(ap, fmt);
2301 		(void) vsprintf(sd_log_buf, fmt, ap);
2302 		va_end(ap);
2303 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2304 		mutex_exit(&sd_log_mutex);
2305 	}
2306 #ifdef SD_FAULT_INJECTION
2307 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2308 	if (un->sd_injection_mask & comp) {
2309 		mutex_enter(&sd_log_mutex);
2310 		va_start(ap, fmt);
2311 		(void) vsprintf(sd_log_buf, fmt, ap);
2312 		va_end(ap);
2313 		sd_injection_log(sd_log_buf, un);
2314 		mutex_exit(&sd_log_mutex);
2315 	}
2316 #endif
2317 }
2318 
2319 
2320 /*
2321  *    Function: sd_log_info
2322  *
2323  * Description: This routine is called by the SD_INFO macro for debug
2324  *		logging of general purpose informational conditions.
2325  *
2326  *   Arguments: comp - driver component being logged
2327  *		dev  - pointer to driver info structure
2328  *		fmt  - info string and format to be logged
2329  */
2330 
2331 static void
2332 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2333 {
2334 	va_list		ap;
2335 	dev_info_t	*dev;
2336 
2337 	ASSERT(un != NULL);
2338 	dev = SD_DEVINFO(un);
2339 	ASSERT(dev != NULL);
2340 
2341 	/*
2342 	 * Filter messages based on the global component and level masks.
2343 	 * Also print if un matches the value of sd_debug_un, or if
2344 	 * sd_debug_un is set to NULL.
2345 	 */
2346 	if ((sd_component_mask & component) &&
2347 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2348 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2349 		mutex_enter(&sd_log_mutex);
2350 		va_start(ap, fmt);
2351 		(void) vsprintf(sd_log_buf, fmt, ap);
2352 		va_end(ap);
2353 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2354 		mutex_exit(&sd_log_mutex);
2355 	}
2356 #ifdef SD_FAULT_INJECTION
2357 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2358 	if (un->sd_injection_mask & component) {
2359 		mutex_enter(&sd_log_mutex);
2360 		va_start(ap, fmt);
2361 		(void) vsprintf(sd_log_buf, fmt, ap);
2362 		va_end(ap);
2363 		sd_injection_log(sd_log_buf, un);
2364 		mutex_exit(&sd_log_mutex);
2365 	}
2366 #endif
2367 }
2368 
2369 
2370 /*
2371  *    Function: sd_log_trace
2372  *
2373  * Description: This routine is called by the SD_TRACE macro for debug
2374  *		logging of trace conditions (i.e. function entry/exit).
2375  *
2376  *   Arguments: comp - driver component being logged
2377  *		dev  - pointer to driver info structure
2378  *		fmt  - trace string and format to be logged
2379  */
2380 
2381 static void
2382 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2383 {
2384 	va_list		ap;
2385 	dev_info_t	*dev;
2386 
2387 	ASSERT(un != NULL);
2388 	dev = SD_DEVINFO(un);
2389 	ASSERT(dev != NULL);
2390 
2391 	/*
2392 	 * Filter messages based on the global component and level masks.
2393 	 * Also print if un matches the value of sd_debug_un, or if
2394 	 * sd_debug_un is set to NULL.
2395 	 */
2396 	if ((sd_component_mask & component) &&
2397 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2398 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2399 		mutex_enter(&sd_log_mutex);
2400 		va_start(ap, fmt);
2401 		(void) vsprintf(sd_log_buf, fmt, ap);
2402 		va_end(ap);
2403 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2404 		mutex_exit(&sd_log_mutex);
2405 	}
2406 #ifdef SD_FAULT_INJECTION
2407 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2408 	if (un->sd_injection_mask & component) {
2409 		mutex_enter(&sd_log_mutex);
2410 		va_start(ap, fmt);
2411 		(void) vsprintf(sd_log_buf, fmt, ap);
2412 		va_end(ap);
2413 		sd_injection_log(sd_log_buf, un);
2414 		mutex_exit(&sd_log_mutex);
2415 	}
2416 #endif
2417 }
2418 
2419 
2420 /*
2421  *    Function: sdprobe
2422  *
2423  * Description: This is the driver probe(9e) entry point function.
2424  *
2425  *   Arguments: devi - opaque device info handle
2426  *
2427  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2428  *              DDI_PROBE_FAILURE: If the probe failed.
2429  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2430  *				   but may be present in the future.
2431  */
2432 
2433 static int
2434 sdprobe(dev_info_t *devi)
2435 {
2436 	struct scsi_device	*devp;
2437 	int			rval;
2438 	int			instance;
2439 
2440 	/*
2441 	 * if it wasn't for pln, sdprobe could actually be nulldev
2442 	 * in the "__fibre" case.
2443 	 */
2444 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2445 		return (DDI_PROBE_DONTCARE);
2446 	}
2447 
2448 	devp = ddi_get_driver_private(devi);
2449 
2450 	if (devp == NULL) {
2451 		/* Ooops... nexus driver is mis-configured... */
2452 		return (DDI_PROBE_FAILURE);
2453 	}
2454 
2455 	instance = ddi_get_instance(devi);
2456 
2457 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2458 		return (DDI_PROBE_PARTIAL);
2459 	}
2460 
2461 	/*
2462 	 * Call the SCSA utility probe routine to see if we actually
2463 	 * have a target at this SCSI nexus.
2464 	 */
2465 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2466 	case SCSIPROBE_EXISTS:
2467 		switch (devp->sd_inq->inq_dtype) {
2468 		case DTYPE_DIRECT:
2469 			rval = DDI_PROBE_SUCCESS;
2470 			break;
2471 		case DTYPE_RODIRECT:
2472 			/* CDs etc. Can be removable media */
2473 			rval = DDI_PROBE_SUCCESS;
2474 			break;
2475 		case DTYPE_OPTICAL:
2476 			/*
2477 			 * Rewritable optical driver HP115AA
2478 			 * Can also be removable media
2479 			 */
2480 
2481 			/*
2482 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2483 			 * pre solaris 9 sparc sd behavior is required
2484 			 *
2485 			 * If first time through and sd_dtype_optical_bind
2486 			 * has not been set in /etc/system check properties
2487 			 */
2488 
2489 			if (sd_dtype_optical_bind  < 0) {
2490 				sd_dtype_optical_bind = ddi_prop_get_int
2491 				    (DDI_DEV_T_ANY, devi, 0,
2492 				    "optical-device-bind", 1);
2493 			}
2494 
2495 			if (sd_dtype_optical_bind == 0) {
2496 				rval = DDI_PROBE_FAILURE;
2497 			} else {
2498 				rval = DDI_PROBE_SUCCESS;
2499 			}
2500 			break;
2501 
2502 		case DTYPE_NOTPRESENT:
2503 		default:
2504 			rval = DDI_PROBE_FAILURE;
2505 			break;
2506 		}
2507 		break;
2508 	default:
2509 		rval = DDI_PROBE_PARTIAL;
2510 		break;
2511 	}
2512 
2513 	/*
2514 	 * This routine checks for resource allocation prior to freeing,
2515 	 * so it will take care of the "smart probing" case where a
2516 	 * scsi_probe() may or may not have been issued and will *not*
2517 	 * free previously-freed resources.
2518 	 */
2519 	scsi_unprobe(devp);
2520 	return (rval);
2521 }
2522 
2523 
2524 /*
2525  *    Function: sdinfo
2526  *
2527  * Description: This is the driver getinfo(9e) entry point function.
2528  * 		Given the device number, return the devinfo pointer from
2529  *		the scsi_device structure or the instance number
2530  *		associated with the dev_t.
2531  *
2532  *   Arguments: dip     - pointer to device info structure
2533  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2534  *			  DDI_INFO_DEVT2INSTANCE)
2535  *		arg     - driver dev_t
2536  *		resultp - user buffer for request response
2537  *
2538  * Return Code: DDI_SUCCESS
2539  *              DDI_FAILURE
2540  */
2541 /* ARGSUSED */
2542 static int
2543 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2544 {
2545 	struct sd_lun	*un;
2546 	dev_t		dev;
2547 	int		instance;
2548 	int		error;
2549 
2550 	switch (infocmd) {
2551 	case DDI_INFO_DEVT2DEVINFO:
2552 		dev = (dev_t)arg;
2553 		instance = SDUNIT(dev);
2554 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2555 			return (DDI_FAILURE);
2556 		}
2557 		*result = (void *) SD_DEVINFO(un);
2558 		error = DDI_SUCCESS;
2559 		break;
2560 	case DDI_INFO_DEVT2INSTANCE:
2561 		dev = (dev_t)arg;
2562 		instance = SDUNIT(dev);
2563 		*result = (void *)(uintptr_t)instance;
2564 		error = DDI_SUCCESS;
2565 		break;
2566 	default:
2567 		error = DDI_FAILURE;
2568 	}
2569 	return (error);
2570 }
2571 
2572 /*
2573  *    Function: sd_prop_op
2574  *
2575  * Description: This is the driver prop_op(9e) entry point function.
2576  *		Return the number of blocks for the partition in question
2577  *		or forward the request to the property facilities.
2578  *
2579  *   Arguments: dev       - device number
2580  *		dip       - pointer to device info structure
2581  *		prop_op   - property operator
2582  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2583  *		name      - pointer to property name
2584  *		valuep    - pointer or address of the user buffer
2585  *		lengthp   - property length
2586  *
2587  * Return Code: DDI_PROP_SUCCESS
2588  *              DDI_PROP_NOT_FOUND
2589  *              DDI_PROP_UNDEFINED
2590  *              DDI_PROP_NO_MEMORY
2591  *              DDI_PROP_BUF_TOO_SMALL
2592  */
2593 
2594 static int
2595 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2596 	char *name, caddr_t valuep, int *lengthp)
2597 {
2598 	int		instance = ddi_get_instance(dip);
2599 	struct sd_lun	*un;
2600 	uint64_t	nblocks64;
2601 	uint_t		dblk;
2602 
2603 	/*
2604 	 * Our dynamic properties are all device specific and size oriented.
2605 	 * Requests issued under conditions where size is valid are passed
2606 	 * to ddi_prop_op_nblocks with the size information, otherwise the
2607 	 * request is passed to ddi_prop_op. Size depends on valid geometry.
2608 	 */
2609 	un = ddi_get_soft_state(sd_state, instance);
2610 	if ((dev == DDI_DEV_T_ANY) || (un == NULL)) {
2611 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2612 		    name, valuep, lengthp));
2613 	} else if (!SD_IS_VALID_LABEL(un)) {
2614 		return (ddi_prop_op(dev, dip, prop_op, mod_flags, name,
2615 		    valuep, lengthp));
2616 	}
2617 
2618 	/* get nblocks value */
2619 	ASSERT(!mutex_owned(SD_MUTEX(un)));
2620 
2621 	(void) cmlb_partinfo(un->un_cmlbhandle, SDPART(dev),
2622 	    (diskaddr_t *)&nblocks64, NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
2623 
2624 	/* report size in target size blocks */
2625 	dblk = un->un_tgt_blocksize / un->un_sys_blocksize;
2626 	return (ddi_prop_op_nblocks_blksize(dev, dip, prop_op, mod_flags,
2627 	    name, valuep, lengthp, nblocks64 / dblk, un->un_tgt_blocksize));
2628 }
2629 
2630 /*
2631  * The following functions are for smart probing:
2632  * sd_scsi_probe_cache_init()
2633  * sd_scsi_probe_cache_fini()
2634  * sd_scsi_clear_probe_cache()
2635  * sd_scsi_probe_with_cache()
2636  */
2637 
2638 /*
2639  *    Function: sd_scsi_probe_cache_init
2640  *
2641  * Description: Initializes the probe response cache mutex and head pointer.
2642  *
2643  *     Context: Kernel thread context
2644  */
2645 
2646 static void
2647 sd_scsi_probe_cache_init(void)
2648 {
2649 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2650 	sd_scsi_probe_cache_head = NULL;
2651 }
2652 
2653 
2654 /*
2655  *    Function: sd_scsi_probe_cache_fini
2656  *
2657  * Description: Frees all resources associated with the probe response cache.
2658  *
2659  *     Context: Kernel thread context
2660  */
2661 
2662 static void
2663 sd_scsi_probe_cache_fini(void)
2664 {
2665 	struct sd_scsi_probe_cache *cp;
2666 	struct sd_scsi_probe_cache *ncp;
2667 
2668 	/* Clean up our smart probing linked list */
2669 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2670 		ncp = cp->next;
2671 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2672 	}
2673 	sd_scsi_probe_cache_head = NULL;
2674 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2675 }
2676 
2677 
2678 /*
2679  *    Function: sd_scsi_clear_probe_cache
2680  *
2681  * Description: This routine clears the probe response cache. This is
2682  *		done when open() returns ENXIO so that when deferred
2683  *		attach is attempted (possibly after a device has been
2684  *		turned on) we will retry the probe. Since we don't know
2685  *		which target we failed to open, we just clear the
2686  *		entire cache.
2687  *
2688  *     Context: Kernel thread context
2689  */
2690 
2691 static void
2692 sd_scsi_clear_probe_cache(void)
2693 {
2694 	struct sd_scsi_probe_cache	*cp;
2695 	int				i;
2696 
2697 	mutex_enter(&sd_scsi_probe_cache_mutex);
2698 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2699 		/*
2700 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2701 		 * force probing to be performed the next time
2702 		 * sd_scsi_probe_with_cache is called.
2703 		 */
2704 		for (i = 0; i < NTARGETS_WIDE; i++) {
2705 			cp->cache[i] = SCSIPROBE_EXISTS;
2706 		}
2707 	}
2708 	mutex_exit(&sd_scsi_probe_cache_mutex);
2709 }
2710 
2711 
2712 /*
2713  *    Function: sd_scsi_probe_with_cache
2714  *
2715  * Description: This routine implements support for a scsi device probe
2716  *		with cache. The driver maintains a cache of the target
2717  *		responses to scsi probes. If we get no response from a
2718  *		target during a probe inquiry, we remember that, and we
2719  *		avoid additional calls to scsi_probe on non-zero LUNs
2720  *		on the same target until the cache is cleared. By doing
2721  *		so we avoid the 1/4 sec selection timeout for nonzero
2722  *		LUNs. lun0 of a target is always probed.
2723  *
2724  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2725  *              waitfunc - indicates what the allocator routines should
2726  *			   do when resources are not available. This value
2727  *			   is passed on to scsi_probe() when that routine
2728  *			   is called.
2729  *
2730  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2731  *		otherwise the value returned by scsi_probe(9F).
2732  *
2733  *     Context: Kernel thread context
2734  */
2735 
2736 static int
2737 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2738 {
2739 	struct sd_scsi_probe_cache	*cp;
2740 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2741 	int		lun, tgt;
2742 
2743 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2744 	    SCSI_ADDR_PROP_LUN, 0);
2745 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2746 	    SCSI_ADDR_PROP_TARGET, -1);
2747 
2748 	/* Make sure caching enabled and target in range */
2749 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2750 		/* do it the old way (no cache) */
2751 		return (scsi_probe(devp, waitfn));
2752 	}
2753 
2754 	mutex_enter(&sd_scsi_probe_cache_mutex);
2755 
2756 	/* Find the cache for this scsi bus instance */
2757 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2758 		if (cp->pdip == pdip) {
2759 			break;
2760 		}
2761 	}
2762 
2763 	/* If we can't find a cache for this pdip, create one */
2764 	if (cp == NULL) {
2765 		int i;
2766 
2767 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
2768 		    KM_SLEEP);
2769 		cp->pdip = pdip;
2770 		cp->next = sd_scsi_probe_cache_head;
2771 		sd_scsi_probe_cache_head = cp;
2772 		for (i = 0; i < NTARGETS_WIDE; i++) {
2773 			cp->cache[i] = SCSIPROBE_EXISTS;
2774 		}
2775 	}
2776 
2777 	mutex_exit(&sd_scsi_probe_cache_mutex);
2778 
2779 	/* Recompute the cache for this target if LUN zero */
2780 	if (lun == 0) {
2781 		cp->cache[tgt] = SCSIPROBE_EXISTS;
2782 	}
2783 
2784 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
2785 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
2786 		return (SCSIPROBE_NORESP);
2787 	}
2788 
2789 	/* Do the actual probe; save & return the result */
2790 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
2791 }
2792 
2793 
2794 /*
2795  *    Function: sd_scsi_target_lun_init
2796  *
2797  * Description: Initializes the attached lun chain mutex and head pointer.
2798  *
2799  *     Context: Kernel thread context
2800  */
2801 
2802 static void
2803 sd_scsi_target_lun_init(void)
2804 {
2805 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
2806 	sd_scsi_target_lun_head = NULL;
2807 }
2808 
2809 
2810 /*
2811  *    Function: sd_scsi_target_lun_fini
2812  *
2813  * Description: Frees all resources associated with the attached lun
2814  *              chain
2815  *
2816  *     Context: Kernel thread context
2817  */
2818 
2819 static void
2820 sd_scsi_target_lun_fini(void)
2821 {
2822 	struct sd_scsi_hba_tgt_lun	*cp;
2823 	struct sd_scsi_hba_tgt_lun	*ncp;
2824 
2825 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
2826 		ncp = cp->next;
2827 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
2828 	}
2829 	sd_scsi_target_lun_head = NULL;
2830 	mutex_destroy(&sd_scsi_target_lun_mutex);
2831 }
2832 
2833 
2834 /*
2835  *    Function: sd_scsi_get_target_lun_count
2836  *
2837  * Description: This routine will check in the attached lun chain to see
2838  * 		how many luns are attached on the required SCSI controller
2839  * 		and target. Currently, some capabilities like tagged queue
2840  *		are supported per target based by HBA. So all luns in a
2841  *		target have the same capabilities. Based on this assumption,
2842  * 		sd should only set these capabilities once per target. This
2843  *		function is called when sd needs to decide how many luns
2844  *		already attached on a target.
2845  *
2846  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
2847  *			  controller device.
2848  *              target	- The target ID on the controller's SCSI bus.
2849  *
2850  * Return Code: The number of luns attached on the required target and
2851  *		controller.
2852  *		-1 if target ID is not in parallel SCSI scope or the given
2853  * 		dip is not in the chain.
2854  *
2855  *     Context: Kernel thread context
2856  */
2857 
2858 static int
2859 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
2860 {
2861 	struct sd_scsi_hba_tgt_lun	*cp;
2862 
2863 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
2864 		return (-1);
2865 	}
2866 
2867 	mutex_enter(&sd_scsi_target_lun_mutex);
2868 
2869 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2870 		if (cp->pdip == dip) {
2871 			break;
2872 		}
2873 	}
2874 
2875 	mutex_exit(&sd_scsi_target_lun_mutex);
2876 
2877 	if (cp == NULL) {
2878 		return (-1);
2879 	}
2880 
2881 	return (cp->nlun[target]);
2882 }
2883 
2884 
2885 /*
2886  *    Function: sd_scsi_update_lun_on_target
2887  *
2888  * Description: This routine is used to update the attached lun chain when a
2889  *		lun is attached or detached on a target.
2890  *
2891  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
2892  *                        controller device.
2893  *              target  - The target ID on the controller's SCSI bus.
2894  *		flag	- Indicate the lun is attached or detached.
2895  *
2896  *     Context: Kernel thread context
2897  */
2898 
2899 static void
2900 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
2901 {
2902 	struct sd_scsi_hba_tgt_lun	*cp;
2903 
2904 	mutex_enter(&sd_scsi_target_lun_mutex);
2905 
2906 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2907 		if (cp->pdip == dip) {
2908 			break;
2909 		}
2910 	}
2911 
2912 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
2913 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
2914 		    KM_SLEEP);
2915 		cp->pdip = dip;
2916 		cp->next = sd_scsi_target_lun_head;
2917 		sd_scsi_target_lun_head = cp;
2918 	}
2919 
2920 	mutex_exit(&sd_scsi_target_lun_mutex);
2921 
2922 	if (cp != NULL) {
2923 		if (flag == SD_SCSI_LUN_ATTACH) {
2924 			cp->nlun[target] ++;
2925 		} else {
2926 			cp->nlun[target] --;
2927 		}
2928 	}
2929 }
2930 
2931 
2932 /*
2933  *    Function: sd_spin_up_unit
2934  *
2935  * Description: Issues the following commands to spin-up the device:
2936  *		START STOP UNIT, and INQUIRY.
2937  *
2938  *   Arguments: un - driver soft state (unit) structure
2939  *
2940  * Return Code: 0 - success
2941  *		EIO - failure
2942  *		EACCES - reservation conflict
2943  *
2944  *     Context: Kernel thread context
2945  */
2946 
2947 static int
2948 sd_spin_up_unit(struct sd_lun *un)
2949 {
2950 	size_t	resid		= 0;
2951 	int	has_conflict	= FALSE;
2952 	uchar_t *bufaddr;
2953 
2954 	ASSERT(un != NULL);
2955 
2956 	/*
2957 	 * Send a throwaway START UNIT command.
2958 	 *
2959 	 * If we fail on this, we don't care presently what precisely
2960 	 * is wrong.  EMC's arrays will also fail this with a check
2961 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
2962 	 * we don't want to fail the attach because it may become
2963 	 * "active" later.
2964 	 */
2965 	if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START, SD_PATH_DIRECT)
2966 	    == EACCES)
2967 		has_conflict = TRUE;
2968 
2969 	/*
2970 	 * Send another INQUIRY command to the target. This is necessary for
2971 	 * non-removable media direct access devices because their INQUIRY data
2972 	 * may not be fully qualified until they are spun up (perhaps via the
2973 	 * START command above).  Note: This seems to be needed for some
2974 	 * legacy devices only.) The INQUIRY command should succeed even if a
2975 	 * Reservation Conflict is present.
2976 	 */
2977 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
2978 	if (sd_send_scsi_INQUIRY(un, bufaddr, SUN_INQSIZE, 0, 0, &resid) != 0) {
2979 		kmem_free(bufaddr, SUN_INQSIZE);
2980 		return (EIO);
2981 	}
2982 
2983 	/*
2984 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
2985 	 * Note that this routine does not return a failure here even if the
2986 	 * INQUIRY command did not return any data.  This is a legacy behavior.
2987 	 */
2988 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
2989 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
2990 	}
2991 
2992 	kmem_free(bufaddr, SUN_INQSIZE);
2993 
2994 	/* If we hit a reservation conflict above, tell the caller. */
2995 	if (has_conflict == TRUE) {
2996 		return (EACCES);
2997 	}
2998 
2999 	return (0);
3000 }
3001 
3002 #ifdef _LP64
3003 /*
3004  *    Function: sd_enable_descr_sense
3005  *
3006  * Description: This routine attempts to select descriptor sense format
3007  *		using the Control mode page.  Devices that support 64 bit
3008  *		LBAs (for >2TB luns) should also implement descriptor
3009  *		sense data so we will call this function whenever we see
3010  *		a lun larger than 2TB.  If for some reason the device
3011  *		supports 64 bit LBAs but doesn't support descriptor sense
3012  *		presumably the mode select will fail.  Everything will
3013  *		continue to work normally except that we will not get
3014  *		complete sense data for commands that fail with an LBA
3015  *		larger than 32 bits.
3016  *
3017  *   Arguments: un - driver soft state (unit) structure
3018  *
3019  *     Context: Kernel thread context only
3020  */
3021 
3022 static void
3023 sd_enable_descr_sense(struct sd_lun *un)
3024 {
3025 	uchar_t			*header;
3026 	struct mode_control_scsi3 *ctrl_bufp;
3027 	size_t			buflen;
3028 	size_t			bd_len;
3029 
3030 	/*
3031 	 * Read MODE SENSE page 0xA, Control Mode Page
3032 	 */
3033 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3034 	    sizeof (struct mode_control_scsi3);
3035 	header = kmem_zalloc(buflen, KM_SLEEP);
3036 	if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
3037 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT) != 0) {
3038 		SD_ERROR(SD_LOG_COMMON, un,
3039 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3040 		goto eds_exit;
3041 	}
3042 
3043 	/*
3044 	 * Determine size of Block Descriptors in order to locate
3045 	 * the mode page data. ATAPI devices return 0, SCSI devices
3046 	 * should return MODE_BLK_DESC_LENGTH.
3047 	 */
3048 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3049 
3050 	/* Clear the mode data length field for MODE SELECT */
3051 	((struct mode_header *)header)->length = 0;
3052 
3053 	ctrl_bufp = (struct mode_control_scsi3 *)
3054 	    (header + MODE_HEADER_LENGTH + bd_len);
3055 
3056 	/*
3057 	 * If the page length is smaller than the expected value,
3058 	 * the target device doesn't support D_SENSE. Bail out here.
3059 	 */
3060 	if (ctrl_bufp->mode_page.length <
3061 	    sizeof (struct mode_control_scsi3) - 2) {
3062 		SD_ERROR(SD_LOG_COMMON, un,
3063 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3064 		goto eds_exit;
3065 	}
3066 
3067 	/*
3068 	 * Clear PS bit for MODE SELECT
3069 	 */
3070 	ctrl_bufp->mode_page.ps = 0;
3071 
3072 	/*
3073 	 * Set D_SENSE to enable descriptor sense format.
3074 	 */
3075 	ctrl_bufp->d_sense = 1;
3076 
3077 	/*
3078 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3079 	 */
3080 	if (sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
3081 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT) != 0) {
3082 		SD_INFO(SD_LOG_COMMON, un,
3083 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3084 		goto eds_exit;
3085 	}
3086 
3087 eds_exit:
3088 	kmem_free(header, buflen);
3089 }
3090 
3091 /*
3092  *    Function: sd_reenable_dsense_task
3093  *
3094  * Description: Re-enable descriptor sense after device or bus reset
3095  *
3096  *     Context: Executes in a taskq() thread context
3097  */
3098 static void
3099 sd_reenable_dsense_task(void *arg)
3100 {
3101 	struct	sd_lun	*un = arg;
3102 
3103 	ASSERT(un != NULL);
3104 	sd_enable_descr_sense(un);
3105 }
3106 #endif /* _LP64 */
3107 
3108 /*
3109  *    Function: sd_set_mmc_caps
3110  *
3111  * Description: This routine determines if the device is MMC compliant and if
3112  *		the device supports CDDA via a mode sense of the CDVD
3113  *		capabilities mode page. Also checks if the device is a
3114  *		dvdram writable device.
3115  *
3116  *   Arguments: un - driver soft state (unit) structure
3117  *
3118  *     Context: Kernel thread context only
3119  */
3120 
3121 static void
3122 sd_set_mmc_caps(struct sd_lun *un)
3123 {
3124 	struct mode_header_grp2		*sense_mhp;
3125 	uchar_t				*sense_page;
3126 	caddr_t				buf;
3127 	int				bd_len;
3128 	int				status;
3129 	struct uscsi_cmd		com;
3130 	int				rtn;
3131 	uchar_t				*out_data_rw, *out_data_hd;
3132 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3133 
3134 	ASSERT(un != NULL);
3135 
3136 	/*
3137 	 * The flags which will be set in this function are - mmc compliant,
3138 	 * dvdram writable device, cdda support. Initialize them to FALSE
3139 	 * and if a capability is detected - it will be set to TRUE.
3140 	 */
3141 	un->un_f_mmc_cap = FALSE;
3142 	un->un_f_dvdram_writable_device = FALSE;
3143 	un->un_f_cfg_cdda = FALSE;
3144 
3145 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3146 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
3147 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3148 
3149 	if (status != 0) {
3150 		/* command failed; just return */
3151 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3152 		return;
3153 	}
3154 	/*
3155 	 * If the mode sense request for the CDROM CAPABILITIES
3156 	 * page (0x2A) succeeds the device is assumed to be MMC.
3157 	 */
3158 	un->un_f_mmc_cap = TRUE;
3159 
3160 	/* Get to the page data */
3161 	sense_mhp = (struct mode_header_grp2 *)buf;
3162 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3163 	    sense_mhp->bdesc_length_lo;
3164 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3165 		/*
3166 		 * We did not get back the expected block descriptor
3167 		 * length so we cannot determine if the device supports
3168 		 * CDDA. However, we still indicate the device is MMC
3169 		 * according to the successful response to the page
3170 		 * 0x2A mode sense request.
3171 		 */
3172 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3173 		    "sd_set_mmc_caps: Mode Sense returned "
3174 		    "invalid block descriptor length\n");
3175 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3176 		return;
3177 	}
3178 
3179 	/* See if read CDDA is supported */
3180 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3181 	    bd_len);
3182 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3183 
3184 	/* See if writing DVD RAM is supported. */
3185 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3186 	if (un->un_f_dvdram_writable_device == TRUE) {
3187 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3188 		return;
3189 	}
3190 
3191 	/*
3192 	 * If the device presents DVD or CD capabilities in the mode
3193 	 * page, we can return here since a RRD will not have
3194 	 * these capabilities.
3195 	 */
3196 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3197 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3198 		return;
3199 	}
3200 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3201 
3202 	/*
3203 	 * If un->un_f_dvdram_writable_device is still FALSE,
3204 	 * check for a Removable Rigid Disk (RRD).  A RRD
3205 	 * device is identified by the features RANDOM_WRITABLE and
3206 	 * HARDWARE_DEFECT_MANAGEMENT.
3207 	 */
3208 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3209 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3210 
3211 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3212 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3213 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3214 	if (rtn != 0) {
3215 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3216 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3217 		return;
3218 	}
3219 
3220 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3221 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3222 
3223 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3224 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3225 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3226 	if (rtn == 0) {
3227 		/*
3228 		 * We have good information, check for random writable
3229 		 * and hardware defect features.
3230 		 */
3231 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3232 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3233 			un->un_f_dvdram_writable_device = TRUE;
3234 		}
3235 	}
3236 
3237 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3238 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3239 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3240 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3241 }
3242 
3243 /*
3244  *    Function: sd_check_for_writable_cd
3245  *
3246  * Description: This routine determines if the media in the device is
3247  *		writable or not. It uses the get configuration command (0x46)
3248  *		to determine if the media is writable
3249  *
3250  *   Arguments: un - driver soft state (unit) structure
3251  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3252  *                           chain and the normal command waitq, or
3253  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3254  *                           "direct" chain and bypass the normal command
3255  *                           waitq.
3256  *
3257  *     Context: Never called at interrupt context.
3258  */
3259 
3260 static void
3261 sd_check_for_writable_cd(struct sd_lun *un, int path_flag)
3262 {
3263 	struct uscsi_cmd		com;
3264 	uchar_t				*out_data;
3265 	uchar_t				*rqbuf;
3266 	int				rtn;
3267 	uchar_t				*out_data_rw, *out_data_hd;
3268 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3269 	struct mode_header_grp2		*sense_mhp;
3270 	uchar_t				*sense_page;
3271 	caddr_t				buf;
3272 	int				bd_len;
3273 	int				status;
3274 
3275 	ASSERT(un != NULL);
3276 	ASSERT(mutex_owned(SD_MUTEX(un)));
3277 
3278 	/*
3279 	 * Initialize the writable media to false, if configuration info.
3280 	 * tells us otherwise then only we will set it.
3281 	 */
3282 	un->un_f_mmc_writable_media = FALSE;
3283 	mutex_exit(SD_MUTEX(un));
3284 
3285 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3286 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3287 
3288 	rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf, SENSE_LENGTH,
3289 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3290 
3291 	mutex_enter(SD_MUTEX(un));
3292 	if (rtn == 0) {
3293 		/*
3294 		 * We have good information, check for writable DVD.
3295 		 */
3296 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3297 			un->un_f_mmc_writable_media = TRUE;
3298 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3299 			kmem_free(rqbuf, SENSE_LENGTH);
3300 			return;
3301 		}
3302 	}
3303 
3304 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3305 	kmem_free(rqbuf, SENSE_LENGTH);
3306 
3307 	/*
3308 	 * Determine if this is a RRD type device.
3309 	 */
3310 	mutex_exit(SD_MUTEX(un));
3311 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3312 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
3313 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3314 	mutex_enter(SD_MUTEX(un));
3315 	if (status != 0) {
3316 		/* command failed; just return */
3317 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3318 		return;
3319 	}
3320 
3321 	/* Get to the page data */
3322 	sense_mhp = (struct mode_header_grp2 *)buf;
3323 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3324 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3325 		/*
3326 		 * We did not get back the expected block descriptor length so
3327 		 * we cannot check the mode page.
3328 		 */
3329 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3330 		    "sd_check_for_writable_cd: Mode Sense returned "
3331 		    "invalid block descriptor length\n");
3332 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3333 		return;
3334 	}
3335 
3336 	/*
3337 	 * If the device presents DVD or CD capabilities in the mode
3338 	 * page, we can return here since a RRD device will not have
3339 	 * these capabilities.
3340 	 */
3341 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3342 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3343 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3344 		return;
3345 	}
3346 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3347 
3348 	/*
3349 	 * If un->un_f_mmc_writable_media is still FALSE,
3350 	 * check for RRD type media.  A RRD device is identified
3351 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3352 	 */
3353 	mutex_exit(SD_MUTEX(un));
3354 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3355 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3356 
3357 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3358 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3359 	    RANDOM_WRITABLE, path_flag);
3360 	if (rtn != 0) {
3361 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3362 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3363 		mutex_enter(SD_MUTEX(un));
3364 		return;
3365 	}
3366 
3367 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3368 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3369 
3370 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3371 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3372 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3373 	mutex_enter(SD_MUTEX(un));
3374 	if (rtn == 0) {
3375 		/*
3376 		 * We have good information, check for random writable
3377 		 * and hardware defect features as current.
3378 		 */
3379 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3380 		    (out_data_rw[10] & 0x1) &&
3381 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3382 		    (out_data_hd[10] & 0x1)) {
3383 			un->un_f_mmc_writable_media = TRUE;
3384 		}
3385 	}
3386 
3387 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3388 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3389 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3390 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3391 }
3392 
3393 /*
3394  *    Function: sd_read_unit_properties
3395  *
3396  * Description: The following implements a property lookup mechanism.
3397  *		Properties for particular disks (keyed on vendor, model
3398  *		and rev numbers) are sought in the sd.conf file via
3399  *		sd_process_sdconf_file(), and if not found there, are
3400  *		looked for in a list hardcoded in this driver via
3401  *		sd_process_sdconf_table() Once located the properties
3402  *		are used to update the driver unit structure.
3403  *
3404  *   Arguments: un - driver soft state (unit) structure
3405  */
3406 
3407 static void
3408 sd_read_unit_properties(struct sd_lun *un)
3409 {
3410 	/*
3411 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3412 	 * the "sd-config-list" property (from the sd.conf file) or if
3413 	 * there was not a match for the inquiry vid/pid. If this event
3414 	 * occurs the static driver configuration table is searched for
3415 	 * a match.
3416 	 */
3417 	ASSERT(un != NULL);
3418 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3419 		sd_process_sdconf_table(un);
3420 	}
3421 
3422 	/* check for LSI device */
3423 	sd_is_lsi(un);
3424 
3425 
3426 }
3427 
3428 
3429 /*
3430  *    Function: sd_process_sdconf_file
3431  *
3432  * Description: Use ddi_getlongprop to obtain the properties from the
3433  *		driver's config file (ie, sd.conf) and update the driver
3434  *		soft state structure accordingly.
3435  *
3436  *   Arguments: un - driver soft state (unit) structure
3437  *
3438  * Return Code: SD_SUCCESS - The properties were successfully set according
3439  *			     to the driver configuration file.
3440  *		SD_FAILURE - The driver config list was not obtained or
3441  *			     there was no vid/pid match. This indicates that
3442  *			     the static config table should be used.
3443  *
3444  * The config file has a property, "sd-config-list", which consists of
3445  * one or more duplets as follows:
3446  *
3447  *  sd-config-list=
3448  *	<duplet>,
3449  *	[<duplet>,]
3450  *	[<duplet>];
3451  *
3452  * The structure of each duplet is as follows:
3453  *
3454  *  <duplet>:= <vid+pid>,<data-property-name_list>
3455  *
3456  * The first entry of the duplet is the device ID string (the concatenated
3457  * vid & pid; not to be confused with a device_id).  This is defined in
3458  * the same way as in the sd_disk_table.
3459  *
3460  * The second part of the duplet is a string that identifies a
3461  * data-property-name-list. The data-property-name-list is defined as
3462  * follows:
3463  *
3464  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3465  *
3466  * The syntax of <data-property-name> depends on the <version> field.
3467  *
3468  * If version = SD_CONF_VERSION_1 we have the following syntax:
3469  *
3470  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3471  *
3472  * where the prop0 value will be used to set prop0 if bit0 set in the
3473  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3474  *
3475  */
3476 
3477 static int
3478 sd_process_sdconf_file(struct sd_lun *un)
3479 {
3480 	char	*config_list = NULL;
3481 	int	config_list_len;
3482 	int	len;
3483 	int	dupletlen = 0;
3484 	char	*vidptr;
3485 	int	vidlen;
3486 	char	*dnlist_ptr;
3487 	char	*dataname_ptr;
3488 	int	dnlist_len;
3489 	int	dataname_len;
3490 	int	*data_list;
3491 	int	data_list_len;
3492 	int	rval = SD_FAILURE;
3493 	int	i;
3494 
3495 	ASSERT(un != NULL);
3496 
3497 	/* Obtain the configuration list associated with the .conf file */
3498 	if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), DDI_PROP_DONTPASS,
3499 	    sd_config_list, (caddr_t)&config_list, &config_list_len)
3500 	    != DDI_PROP_SUCCESS) {
3501 		return (SD_FAILURE);
3502 	}
3503 
3504 	/*
3505 	 * Compare vids in each duplet to the inquiry vid - if a match is
3506 	 * made, get the data value and update the soft state structure
3507 	 * accordingly.
3508 	 *
3509 	 * Note: This algorithm is complex and difficult to maintain. It should
3510 	 * be replaced with a more robust implementation.
3511 	 */
3512 	for (len = config_list_len, vidptr = config_list; len > 0;
3513 	    vidptr += dupletlen, len -= dupletlen) {
3514 		/*
3515 		 * Note: The assumption here is that each vid entry is on
3516 		 * a unique line from its associated duplet.
3517 		 */
3518 		vidlen = dupletlen = (int)strlen(vidptr);
3519 		if ((vidlen == 0) ||
3520 		    (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS)) {
3521 			dupletlen++;
3522 			continue;
3523 		}
3524 
3525 		/*
3526 		 * dnlist contains 1 or more blank separated
3527 		 * data-property-name entries
3528 		 */
3529 		dnlist_ptr = vidptr + vidlen + 1;
3530 		dnlist_len = (int)strlen(dnlist_ptr);
3531 		dupletlen += dnlist_len + 2;
3532 
3533 		/*
3534 		 * Set a pointer for the first data-property-name
3535 		 * entry in the list
3536 		 */
3537 		dataname_ptr = dnlist_ptr;
3538 		dataname_len = 0;
3539 
3540 		/*
3541 		 * Loop through all data-property-name entries in the
3542 		 * data-property-name-list setting the properties for each.
3543 		 */
3544 		while (dataname_len < dnlist_len) {
3545 			int version;
3546 
3547 			/*
3548 			 * Determine the length of the current
3549 			 * data-property-name entry by indexing until a
3550 			 * blank or NULL is encountered. When the space is
3551 			 * encountered reset it to a NULL for compliance
3552 			 * with ddi_getlongprop().
3553 			 */
3554 			for (i = 0; ((dataname_ptr[i] != ' ') &&
3555 			    (dataname_ptr[i] != '\0')); i++) {
3556 				;
3557 			}
3558 
3559 			dataname_len += i;
3560 			/* If not null terminated, Make it so */
3561 			if (dataname_ptr[i] == ' ') {
3562 				dataname_ptr[i] = '\0';
3563 			}
3564 			dataname_len++;
3565 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3566 			    "sd_process_sdconf_file: disk:%s, data:%s\n",
3567 			    vidptr, dataname_ptr);
3568 
3569 			/* Get the data list */
3570 			if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), 0,
3571 			    dataname_ptr, (caddr_t)&data_list, &data_list_len)
3572 			    != DDI_PROP_SUCCESS) {
3573 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3574 				    "sd_process_sdconf_file: data property (%s)"
3575 				    " has no value\n", dataname_ptr);
3576 				dataname_ptr = dnlist_ptr + dataname_len;
3577 				continue;
3578 			}
3579 
3580 			version = data_list[0];
3581 
3582 			if (version == SD_CONF_VERSION_1) {
3583 				sd_tunables values;
3584 
3585 				/* Set the properties */
3586 				if (sd_chk_vers1_data(un, data_list[1],
3587 				    &data_list[2], data_list_len, dataname_ptr)
3588 				    == SD_SUCCESS) {
3589 					sd_get_tunables_from_conf(un,
3590 					    data_list[1], &data_list[2],
3591 					    &values);
3592 					sd_set_vers1_properties(un,
3593 					    data_list[1], &values);
3594 					rval = SD_SUCCESS;
3595 				} else {
3596 					rval = SD_FAILURE;
3597 				}
3598 			} else {
3599 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3600 				    "data property %s version 0x%x is invalid.",
3601 				    dataname_ptr, version);
3602 				rval = SD_FAILURE;
3603 			}
3604 			kmem_free(data_list, data_list_len);
3605 			dataname_ptr = dnlist_ptr + dataname_len;
3606 		}
3607 	}
3608 
3609 	/* free up the memory allocated by ddi_getlongprop */
3610 	if (config_list) {
3611 		kmem_free(config_list, config_list_len);
3612 	}
3613 
3614 	return (rval);
3615 }
3616 
3617 /*
3618  *    Function: sd_get_tunables_from_conf()
3619  *
3620  *
3621  *    This function reads the data list from the sd.conf file and pulls
3622  *    the values that can have numeric values as arguments and places
3623  *    the values in the appropriate sd_tunables member.
3624  *    Since the order of the data list members varies across platforms
3625  *    This function reads them from the data list in a platform specific
3626  *    order and places them into the correct sd_tunable member that is
3627  *    consistent across all platforms.
3628  */
3629 static void
3630 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
3631     sd_tunables *values)
3632 {
3633 	int i;
3634 	int mask;
3635 
3636 	bzero(values, sizeof (sd_tunables));
3637 
3638 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3639 
3640 		mask = 1 << i;
3641 		if (mask > flags) {
3642 			break;
3643 		}
3644 
3645 		switch (mask & flags) {
3646 		case 0:	/* This mask bit not set in flags */
3647 			continue;
3648 		case SD_CONF_BSET_THROTTLE:
3649 			values->sdt_throttle = data_list[i];
3650 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3651 			    "sd_get_tunables_from_conf: throttle = %d\n",
3652 			    values->sdt_throttle);
3653 			break;
3654 		case SD_CONF_BSET_CTYPE:
3655 			values->sdt_ctype = data_list[i];
3656 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3657 			    "sd_get_tunables_from_conf: ctype = %d\n",
3658 			    values->sdt_ctype);
3659 			break;
3660 		case SD_CONF_BSET_NRR_COUNT:
3661 			values->sdt_not_rdy_retries = data_list[i];
3662 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3663 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
3664 			    values->sdt_not_rdy_retries);
3665 			break;
3666 		case SD_CONF_BSET_BSY_RETRY_COUNT:
3667 			values->sdt_busy_retries = data_list[i];
3668 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3669 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
3670 			    values->sdt_busy_retries);
3671 			break;
3672 		case SD_CONF_BSET_RST_RETRIES:
3673 			values->sdt_reset_retries = data_list[i];
3674 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3675 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
3676 			    values->sdt_reset_retries);
3677 			break;
3678 		case SD_CONF_BSET_RSV_REL_TIME:
3679 			values->sdt_reserv_rel_time = data_list[i];
3680 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3681 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
3682 			    values->sdt_reserv_rel_time);
3683 			break;
3684 		case SD_CONF_BSET_MIN_THROTTLE:
3685 			values->sdt_min_throttle = data_list[i];
3686 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3687 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
3688 			    values->sdt_min_throttle);
3689 			break;
3690 		case SD_CONF_BSET_DISKSORT_DISABLED:
3691 			values->sdt_disk_sort_dis = data_list[i];
3692 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3693 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
3694 			    values->sdt_disk_sort_dis);
3695 			break;
3696 		case SD_CONF_BSET_LUN_RESET_ENABLED:
3697 			values->sdt_lun_reset_enable = data_list[i];
3698 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3699 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
3700 			    "\n", values->sdt_lun_reset_enable);
3701 			break;
3702 		case SD_CONF_BSET_CACHE_IS_NV:
3703 			values->sdt_suppress_cache_flush = data_list[i];
3704 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3705 			    "sd_get_tunables_from_conf: \
3706 			    suppress_cache_flush = %d"
3707 			    "\n", values->sdt_suppress_cache_flush);
3708 			break;
3709 		}
3710 	}
3711 }
3712 
3713 /*
3714  *    Function: sd_process_sdconf_table
3715  *
3716  * Description: Search the static configuration table for a match on the
3717  *		inquiry vid/pid and update the driver soft state structure
3718  *		according to the table property values for the device.
3719  *
3720  *		The form of a configuration table entry is:
3721  *		  <vid+pid>,<flags>,<property-data>
3722  *		  "SEAGATE ST42400N",1,0x40000,
3723  *		  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1;
3724  *
3725  *   Arguments: un - driver soft state (unit) structure
3726  */
3727 
3728 static void
3729 sd_process_sdconf_table(struct sd_lun *un)
3730 {
3731 	char	*id = NULL;
3732 	int	table_index;
3733 	int	idlen;
3734 
3735 	ASSERT(un != NULL);
3736 	for (table_index = 0; table_index < sd_disk_table_size;
3737 	    table_index++) {
3738 		id = sd_disk_table[table_index].device_id;
3739 		idlen = strlen(id);
3740 		if (idlen == 0) {
3741 			continue;
3742 		}
3743 
3744 		/*
3745 		 * The static configuration table currently does not
3746 		 * implement version 10 properties. Additionally,
3747 		 * multiple data-property-name entries are not
3748 		 * implemented in the static configuration table.
3749 		 */
3750 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
3751 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3752 			    "sd_process_sdconf_table: disk %s\n", id);
3753 			sd_set_vers1_properties(un,
3754 			    sd_disk_table[table_index].flags,
3755 			    sd_disk_table[table_index].properties);
3756 			break;
3757 		}
3758 	}
3759 }
3760 
3761 
3762 /*
3763  *    Function: sd_sdconf_id_match
3764  *
3765  * Description: This local function implements a case sensitive vid/pid
3766  *		comparison as well as the boundary cases of wild card and
3767  *		multiple blanks.
3768  *
3769  *		Note: An implicit assumption made here is that the scsi
3770  *		inquiry structure will always keep the vid, pid and
3771  *		revision strings in consecutive sequence, so they can be
3772  *		read as a single string. If this assumption is not the
3773  *		case, a separate string, to be used for the check, needs
3774  *		to be built with these strings concatenated.
3775  *
3776  *   Arguments: un - driver soft state (unit) structure
3777  *		id - table or config file vid/pid
3778  *		idlen  - length of the vid/pid (bytes)
3779  *
3780  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3781  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3782  */
3783 
3784 static int
3785 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
3786 {
3787 	struct scsi_inquiry	*sd_inq;
3788 	int 			rval = SD_SUCCESS;
3789 
3790 	ASSERT(un != NULL);
3791 	sd_inq = un->un_sd->sd_inq;
3792 	ASSERT(id != NULL);
3793 
3794 	/*
3795 	 * We use the inq_vid as a pointer to a buffer containing the
3796 	 * vid and pid and use the entire vid/pid length of the table
3797 	 * entry for the comparison. This works because the inq_pid
3798 	 * data member follows inq_vid in the scsi_inquiry structure.
3799 	 */
3800 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
3801 		/*
3802 		 * The user id string is compared to the inquiry vid/pid
3803 		 * using a case insensitive comparison and ignoring
3804 		 * multiple spaces.
3805 		 */
3806 		rval = sd_blank_cmp(un, id, idlen);
3807 		if (rval != SD_SUCCESS) {
3808 			/*
3809 			 * User id strings that start and end with a "*"
3810 			 * are a special case. These do not have a
3811 			 * specific vendor, and the product string can
3812 			 * appear anywhere in the 16 byte PID portion of
3813 			 * the inquiry data. This is a simple strstr()
3814 			 * type search for the user id in the inquiry data.
3815 			 */
3816 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
3817 				char	*pidptr = &id[1];
3818 				int	i;
3819 				int	j;
3820 				int	pidstrlen = idlen - 2;
3821 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
3822 				    pidstrlen;
3823 
3824 				if (j < 0) {
3825 					return (SD_FAILURE);
3826 				}
3827 				for (i = 0; i < j; i++) {
3828 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
3829 					    pidptr, pidstrlen) == 0) {
3830 						rval = SD_SUCCESS;
3831 						break;
3832 					}
3833 				}
3834 			}
3835 		}
3836 	}
3837 	return (rval);
3838 }
3839 
3840 
3841 /*
3842  *    Function: sd_blank_cmp
3843  *
3844  * Description: If the id string starts and ends with a space, treat
3845  *		multiple consecutive spaces as equivalent to a single
3846  *		space. For example, this causes a sd_disk_table entry
3847  *		of " NEC CDROM " to match a device's id string of
3848  *		"NEC       CDROM".
3849  *
3850  *		Note: The success exit condition for this routine is if
3851  *		the pointer to the table entry is '\0' and the cnt of
3852  *		the inquiry length is zero. This will happen if the inquiry
3853  *		string returned by the device is padded with spaces to be
3854  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
3855  *		SCSI spec states that the inquiry string is to be padded with
3856  *		spaces.
3857  *
3858  *   Arguments: un - driver soft state (unit) structure
3859  *		id - table or config file vid/pid
3860  *		idlen  - length of the vid/pid (bytes)
3861  *
3862  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3863  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3864  */
3865 
3866 static int
3867 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
3868 {
3869 	char		*p1;
3870 	char		*p2;
3871 	int		cnt;
3872 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
3873 	    sizeof (SD_INQUIRY(un)->inq_pid);
3874 
3875 	ASSERT(un != NULL);
3876 	p2 = un->un_sd->sd_inq->inq_vid;
3877 	ASSERT(id != NULL);
3878 	p1 = id;
3879 
3880 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
3881 		/*
3882 		 * Note: string p1 is terminated by a NUL but string p2
3883 		 * isn't.  The end of p2 is determined by cnt.
3884 		 */
3885 		for (;;) {
3886 			/* skip over any extra blanks in both strings */
3887 			while ((*p1 != '\0') && (*p1 == ' ')) {
3888 				p1++;
3889 			}
3890 			while ((cnt != 0) && (*p2 == ' ')) {
3891 				p2++;
3892 				cnt--;
3893 			}
3894 
3895 			/* compare the two strings */
3896 			if ((cnt == 0) ||
3897 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
3898 				break;
3899 			}
3900 			while ((cnt > 0) &&
3901 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
3902 				p1++;
3903 				p2++;
3904 				cnt--;
3905 			}
3906 		}
3907 	}
3908 
3909 	/* return SD_SUCCESS if both strings match */
3910 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
3911 }
3912 
3913 
3914 /*
3915  *    Function: sd_chk_vers1_data
3916  *
3917  * Description: Verify the version 1 device properties provided by the
3918  *		user via the configuration file
3919  *
3920  *   Arguments: un	     - driver soft state (unit) structure
3921  *		flags	     - integer mask indicating properties to be set
3922  *		prop_list    - integer list of property values
3923  *		list_len     - length of user provided data
3924  *
3925  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
3926  *		SD_FAILURE - Indicates the user provided data is invalid
3927  */
3928 
3929 static int
3930 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
3931     int list_len, char *dataname_ptr)
3932 {
3933 	int i;
3934 	int mask = 1;
3935 	int index = 0;
3936 
3937 	ASSERT(un != NULL);
3938 
3939 	/* Check for a NULL property name and list */
3940 	if (dataname_ptr == NULL) {
3941 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3942 		    "sd_chk_vers1_data: NULL data property name.");
3943 		return (SD_FAILURE);
3944 	}
3945 	if (prop_list == NULL) {
3946 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3947 		    "sd_chk_vers1_data: %s NULL data property list.",
3948 		    dataname_ptr);
3949 		return (SD_FAILURE);
3950 	}
3951 
3952 	/* Display a warning if undefined bits are set in the flags */
3953 	if (flags & ~SD_CONF_BIT_MASK) {
3954 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3955 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
3956 		    "Properties not set.",
3957 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
3958 		return (SD_FAILURE);
3959 	}
3960 
3961 	/*
3962 	 * Verify the length of the list by identifying the highest bit set
3963 	 * in the flags and validating that the property list has a length
3964 	 * up to the index of this bit.
3965 	 */
3966 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3967 		if (flags & mask) {
3968 			index++;
3969 		}
3970 		mask = 1 << i;
3971 	}
3972 	if ((list_len / sizeof (int)) < (index + 2)) {
3973 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3974 		    "sd_chk_vers1_data: "
3975 		    "Data property list %s size is incorrect. "
3976 		    "Properties not set.", dataname_ptr);
3977 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
3978 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
3979 		return (SD_FAILURE);
3980 	}
3981 	return (SD_SUCCESS);
3982 }
3983 
3984 
3985 /*
3986  *    Function: sd_set_vers1_properties
3987  *
3988  * Description: Set version 1 device properties based on a property list
3989  *		retrieved from the driver configuration file or static
3990  *		configuration table. Version 1 properties have the format:
3991  *
3992  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3993  *
3994  *		where the prop0 value will be used to set prop0 if bit0
3995  *		is set in the flags
3996  *
3997  *   Arguments: un	     - driver soft state (unit) structure
3998  *		flags	     - integer mask indicating properties to be set
3999  *		prop_list    - integer list of property values
4000  */
4001 
4002 static void
4003 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
4004 {
4005 	ASSERT(un != NULL);
4006 
4007 	/*
4008 	 * Set the flag to indicate cache is to be disabled. An attempt
4009 	 * to disable the cache via sd_cache_control() will be made
4010 	 * later during attach once the basic initialization is complete.
4011 	 */
4012 	if (flags & SD_CONF_BSET_NOCACHE) {
4013 		un->un_f_opt_disable_cache = TRUE;
4014 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4015 		    "sd_set_vers1_properties: caching disabled flag set\n");
4016 	}
4017 
4018 	/* CD-specific configuration parameters */
4019 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4020 		un->un_f_cfg_playmsf_bcd = TRUE;
4021 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4022 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4023 	}
4024 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4025 		un->un_f_cfg_readsub_bcd = TRUE;
4026 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4027 		    "sd_set_vers1_properties: readsub_bcd set\n");
4028 	}
4029 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4030 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4031 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4032 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4033 	}
4034 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4035 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4036 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4037 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4038 	}
4039 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4040 		un->un_f_cfg_no_read_header = TRUE;
4041 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4042 		    "sd_set_vers1_properties: no_read_header set\n");
4043 	}
4044 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4045 		un->un_f_cfg_read_cd_xd4 = TRUE;
4046 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4047 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4048 	}
4049 
4050 	/* Support for devices which do not have valid/unique serial numbers */
4051 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4052 		un->un_f_opt_fab_devid = TRUE;
4053 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4054 		    "sd_set_vers1_properties: fab_devid bit set\n");
4055 	}
4056 
4057 	/* Support for user throttle configuration */
4058 	if (flags & SD_CONF_BSET_THROTTLE) {
4059 		ASSERT(prop_list != NULL);
4060 		un->un_saved_throttle = un->un_throttle =
4061 		    prop_list->sdt_throttle;
4062 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4063 		    "sd_set_vers1_properties: throttle set to %d\n",
4064 		    prop_list->sdt_throttle);
4065 	}
4066 
4067 	/* Set the per disk retry count according to the conf file or table. */
4068 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4069 		ASSERT(prop_list != NULL);
4070 		if (prop_list->sdt_not_rdy_retries) {
4071 			un->un_notready_retry_count =
4072 			    prop_list->sdt_not_rdy_retries;
4073 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4074 			    "sd_set_vers1_properties: not ready retry count"
4075 			    " set to %d\n", un->un_notready_retry_count);
4076 		}
4077 	}
4078 
4079 	/* The controller type is reported for generic disk driver ioctls */
4080 	if (flags & SD_CONF_BSET_CTYPE) {
4081 		ASSERT(prop_list != NULL);
4082 		switch (prop_list->sdt_ctype) {
4083 		case CTYPE_CDROM:
4084 			un->un_ctype = prop_list->sdt_ctype;
4085 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4086 			    "sd_set_vers1_properties: ctype set to "
4087 			    "CTYPE_CDROM\n");
4088 			break;
4089 		case CTYPE_CCS:
4090 			un->un_ctype = prop_list->sdt_ctype;
4091 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4092 			    "sd_set_vers1_properties: ctype set to "
4093 			    "CTYPE_CCS\n");
4094 			break;
4095 		case CTYPE_ROD:		/* RW optical */
4096 			un->un_ctype = prop_list->sdt_ctype;
4097 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4098 			    "sd_set_vers1_properties: ctype set to "
4099 			    "CTYPE_ROD\n");
4100 			break;
4101 		default:
4102 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4103 			    "sd_set_vers1_properties: Could not set "
4104 			    "invalid ctype value (%d)",
4105 			    prop_list->sdt_ctype);
4106 		}
4107 	}
4108 
4109 	/* Purple failover timeout */
4110 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4111 		ASSERT(prop_list != NULL);
4112 		un->un_busy_retry_count =
4113 		    prop_list->sdt_busy_retries;
4114 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4115 		    "sd_set_vers1_properties: "
4116 		    "busy retry count set to %d\n",
4117 		    un->un_busy_retry_count);
4118 	}
4119 
4120 	/* Purple reset retry count */
4121 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4122 		ASSERT(prop_list != NULL);
4123 		un->un_reset_retry_count =
4124 		    prop_list->sdt_reset_retries;
4125 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4126 		    "sd_set_vers1_properties: "
4127 		    "reset retry count set to %d\n",
4128 		    un->un_reset_retry_count);
4129 	}
4130 
4131 	/* Purple reservation release timeout */
4132 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4133 		ASSERT(prop_list != NULL);
4134 		un->un_reserve_release_time =
4135 		    prop_list->sdt_reserv_rel_time;
4136 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4137 		    "sd_set_vers1_properties: "
4138 		    "reservation release timeout set to %d\n",
4139 		    un->un_reserve_release_time);
4140 	}
4141 
4142 	/*
4143 	 * Driver flag telling the driver to verify that no commands are pending
4144 	 * for a device before issuing a Test Unit Ready. This is a workaround
4145 	 * for a firmware bug in some Seagate eliteI drives.
4146 	 */
4147 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4148 		un->un_f_cfg_tur_check = TRUE;
4149 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4150 		    "sd_set_vers1_properties: tur queue check set\n");
4151 	}
4152 
4153 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4154 		un->un_min_throttle = prop_list->sdt_min_throttle;
4155 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4156 		    "sd_set_vers1_properties: min throttle set to %d\n",
4157 		    un->un_min_throttle);
4158 	}
4159 
4160 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4161 		un->un_f_disksort_disabled =
4162 		    (prop_list->sdt_disk_sort_dis != 0) ?
4163 		    TRUE : FALSE;
4164 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4165 		    "sd_set_vers1_properties: disksort disabled "
4166 		    "flag set to %d\n",
4167 		    prop_list->sdt_disk_sort_dis);
4168 	}
4169 
4170 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4171 		un->un_f_lun_reset_enabled =
4172 		    (prop_list->sdt_lun_reset_enable != 0) ?
4173 		    TRUE : FALSE;
4174 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4175 		    "sd_set_vers1_properties: lun reset enabled "
4176 		    "flag set to %d\n",
4177 		    prop_list->sdt_lun_reset_enable);
4178 	}
4179 
4180 	if (flags & SD_CONF_BSET_CACHE_IS_NV) {
4181 		un->un_f_suppress_cache_flush =
4182 		    (prop_list->sdt_suppress_cache_flush != 0) ?
4183 		    TRUE : FALSE;
4184 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4185 		    "sd_set_vers1_properties: suppress_cache_flush "
4186 		    "flag set to %d\n",
4187 		    prop_list->sdt_suppress_cache_flush);
4188 	}
4189 
4190 	/*
4191 	 * Validate the throttle values.
4192 	 * If any of the numbers are invalid, set everything to defaults.
4193 	 */
4194 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4195 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4196 	    (un->un_min_throttle > un->un_throttle)) {
4197 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4198 		un->un_min_throttle = sd_min_throttle;
4199 	}
4200 }
4201 
4202 /*
4203  *   Function: sd_is_lsi()
4204  *
4205  *   Description: Check for lsi devices, step through the static device
4206  *	table to match vid/pid.
4207  *
4208  *   Args: un - ptr to sd_lun
4209  *
4210  *   Notes:  When creating new LSI property, need to add the new LSI property
4211  *		to this function.
4212  */
4213 static void
4214 sd_is_lsi(struct sd_lun *un)
4215 {
4216 	char	*id = NULL;
4217 	int	table_index;
4218 	int	idlen;
4219 	void	*prop;
4220 
4221 	ASSERT(un != NULL);
4222 	for (table_index = 0; table_index < sd_disk_table_size;
4223 	    table_index++) {
4224 		id = sd_disk_table[table_index].device_id;
4225 		idlen = strlen(id);
4226 		if (idlen == 0) {
4227 			continue;
4228 		}
4229 
4230 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4231 			prop = sd_disk_table[table_index].properties;
4232 			if (prop == &lsi_properties ||
4233 			    prop == &lsi_oem_properties ||
4234 			    prop == &lsi_properties_scsi ||
4235 			    prop == &symbios_properties) {
4236 				un->un_f_cfg_is_lsi = TRUE;
4237 			}
4238 			break;
4239 		}
4240 	}
4241 }
4242 
4243 /*
4244  *    Function: sd_get_physical_geometry
4245  *
4246  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4247  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4248  *		target, and use this information to initialize the physical
4249  *		geometry cache specified by pgeom_p.
4250  *
4251  *		MODE SENSE is an optional command, so failure in this case
4252  *		does not necessarily denote an error. We want to use the
4253  *		MODE SENSE commands to derive the physical geometry of the
4254  *		device, but if either command fails, the logical geometry is
4255  *		used as the fallback for disk label geometry in cmlb.
4256  *
4257  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4258  *		have already been initialized for the current target and
4259  *		that the current values be passed as args so that we don't
4260  *		end up ever trying to use -1 as a valid value. This could
4261  *		happen if either value is reset while we're not holding
4262  *		the mutex.
4263  *
4264  *   Arguments: un - driver soft state (unit) structure
4265  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4266  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4267  *			to use the USCSI "direct" chain and bypass the normal
4268  *			command waitq.
4269  *
4270  *     Context: Kernel thread only (can sleep).
4271  */
4272 
4273 static int
4274 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4275 	diskaddr_t capacity, int lbasize, int path_flag)
4276 {
4277 	struct	mode_format	*page3p;
4278 	struct	mode_geometry	*page4p;
4279 	struct	mode_header	*headerp;
4280 	int	sector_size;
4281 	int	nsect;
4282 	int	nhead;
4283 	int	ncyl;
4284 	int	intrlv;
4285 	int	spc;
4286 	diskaddr_t	modesense_capacity;
4287 	int	rpm;
4288 	int	bd_len;
4289 	int	mode_header_length;
4290 	uchar_t	*p3bufp;
4291 	uchar_t	*p4bufp;
4292 	int	cdbsize;
4293 	int 	ret = EIO;
4294 
4295 	ASSERT(un != NULL);
4296 
4297 	if (lbasize == 0) {
4298 		if (ISCD(un)) {
4299 			lbasize = 2048;
4300 		} else {
4301 			lbasize = un->un_sys_blocksize;
4302 		}
4303 	}
4304 	pgeom_p->g_secsize = (unsigned short)lbasize;
4305 
4306 	/*
4307 	 * If the unit is a cd/dvd drive MODE SENSE page three
4308 	 * and MODE SENSE page four are reserved (see SBC spec
4309 	 * and MMC spec). To prevent soft errors just return
4310 	 * using the default LBA size.
4311 	 */
4312 	if (ISCD(un))
4313 		return (ret);
4314 
4315 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4316 
4317 	/*
4318 	 * Retrieve MODE SENSE page 3 - Format Device Page
4319 	 */
4320 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4321 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p3bufp,
4322 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag)
4323 	    != 0) {
4324 		SD_ERROR(SD_LOG_COMMON, un,
4325 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4326 		goto page3_exit;
4327 	}
4328 
4329 	/*
4330 	 * Determine size of Block Descriptors in order to locate the mode
4331 	 * page data.  ATAPI devices return 0, SCSI devices should return
4332 	 * MODE_BLK_DESC_LENGTH.
4333 	 */
4334 	headerp = (struct mode_header *)p3bufp;
4335 	if (un->un_f_cfg_is_atapi == TRUE) {
4336 		struct mode_header_grp2 *mhp =
4337 		    (struct mode_header_grp2 *)headerp;
4338 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4339 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4340 	} else {
4341 		mode_header_length = MODE_HEADER_LENGTH;
4342 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4343 	}
4344 
4345 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4346 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4347 		    "received unexpected bd_len of %d, page3\n", bd_len);
4348 		goto page3_exit;
4349 	}
4350 
4351 	page3p = (struct mode_format *)
4352 	    ((caddr_t)headerp + mode_header_length + bd_len);
4353 
4354 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4355 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4356 		    "mode sense pg3 code mismatch %d\n",
4357 		    page3p->mode_page.code);
4358 		goto page3_exit;
4359 	}
4360 
4361 	/*
4362 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4363 	 * complete successfully; otherwise, revert to the logical geometry.
4364 	 * So, we need to save everything in temporary variables.
4365 	 */
4366 	sector_size = BE_16(page3p->data_bytes_sect);
4367 
4368 	/*
4369 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4370 	 */
4371 	if (sector_size == 0) {
4372 		sector_size = un->un_sys_blocksize;
4373 	} else {
4374 		sector_size &= ~(un->un_sys_blocksize - 1);
4375 	}
4376 
4377 	nsect  = BE_16(page3p->sect_track);
4378 	intrlv = BE_16(page3p->interleave);
4379 
4380 	SD_INFO(SD_LOG_COMMON, un,
4381 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
4382 	SD_INFO(SD_LOG_COMMON, un,
4383 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
4384 	    page3p->mode_page.code, nsect, sector_size);
4385 	SD_INFO(SD_LOG_COMMON, un,
4386 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
4387 	    BE_16(page3p->track_skew),
4388 	    BE_16(page3p->cylinder_skew));
4389 
4390 
4391 	/*
4392 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
4393 	 */
4394 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
4395 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p4bufp,
4396 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag)
4397 	    != 0) {
4398 		SD_ERROR(SD_LOG_COMMON, un,
4399 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
4400 		goto page4_exit;
4401 	}
4402 
4403 	/*
4404 	 * Determine size of Block Descriptors in order to locate the mode
4405 	 * page data.  ATAPI devices return 0, SCSI devices should return
4406 	 * MODE_BLK_DESC_LENGTH.
4407 	 */
4408 	headerp = (struct mode_header *)p4bufp;
4409 	if (un->un_f_cfg_is_atapi == TRUE) {
4410 		struct mode_header_grp2 *mhp =
4411 		    (struct mode_header_grp2 *)headerp;
4412 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4413 	} else {
4414 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4415 	}
4416 
4417 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4418 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4419 		    "received unexpected bd_len of %d, page4\n", bd_len);
4420 		goto page4_exit;
4421 	}
4422 
4423 	page4p = (struct mode_geometry *)
4424 	    ((caddr_t)headerp + mode_header_length + bd_len);
4425 
4426 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
4427 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4428 		    "mode sense pg4 code mismatch %d\n",
4429 		    page4p->mode_page.code);
4430 		goto page4_exit;
4431 	}
4432 
4433 	/*
4434 	 * Stash the data now, after we know that both commands completed.
4435 	 */
4436 
4437 
4438 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
4439 	spc   = nhead * nsect;
4440 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
4441 	rpm   = BE_16(page4p->rpm);
4442 
4443 	modesense_capacity = spc * ncyl;
4444 
4445 	SD_INFO(SD_LOG_COMMON, un,
4446 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
4447 	SD_INFO(SD_LOG_COMMON, un,
4448 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
4449 	SD_INFO(SD_LOG_COMMON, un,
4450 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
4451 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
4452 	    (void *)pgeom_p, capacity);
4453 
4454 	/*
4455 	 * Compensate if the drive's geometry is not rectangular, i.e.,
4456 	 * the product of C * H * S returned by MODE SENSE >= that returned
4457 	 * by read capacity. This is an idiosyncrasy of the original x86
4458 	 * disk subsystem.
4459 	 */
4460 	if (modesense_capacity >= capacity) {
4461 		SD_INFO(SD_LOG_COMMON, un,
4462 		    "sd_get_physical_geometry: adjusting acyl; "
4463 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
4464 		    (modesense_capacity - capacity + spc - 1) / spc);
4465 		if (sector_size != 0) {
4466 			/* 1243403: NEC D38x7 drives don't support sec size */
4467 			pgeom_p->g_secsize = (unsigned short)sector_size;
4468 		}
4469 		pgeom_p->g_nsect    = (unsigned short)nsect;
4470 		pgeom_p->g_nhead    = (unsigned short)nhead;
4471 		pgeom_p->g_capacity = capacity;
4472 		pgeom_p->g_acyl	    =
4473 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
4474 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
4475 	}
4476 
4477 	pgeom_p->g_rpm    = (unsigned short)rpm;
4478 	pgeom_p->g_intrlv = (unsigned short)intrlv;
4479 	ret = 0;
4480 
4481 	SD_INFO(SD_LOG_COMMON, un,
4482 	    "sd_get_physical_geometry: mode sense geometry:\n");
4483 	SD_INFO(SD_LOG_COMMON, un,
4484 	    "   nsect: %d; sector size: %d; interlv: %d\n",
4485 	    nsect, sector_size, intrlv);
4486 	SD_INFO(SD_LOG_COMMON, un,
4487 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
4488 	    nhead, ncyl, rpm, modesense_capacity);
4489 	SD_INFO(SD_LOG_COMMON, un,
4490 	    "sd_get_physical_geometry: (cached)\n");
4491 	SD_INFO(SD_LOG_COMMON, un,
4492 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
4493 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
4494 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
4495 	SD_INFO(SD_LOG_COMMON, un,
4496 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
4497 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
4498 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
4499 
4500 page4_exit:
4501 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
4502 page3_exit:
4503 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
4504 
4505 	return (ret);
4506 }
4507 
4508 /*
4509  *    Function: sd_get_virtual_geometry
4510  *
4511  * Description: Ask the controller to tell us about the target device.
4512  *
4513  *   Arguments: un - pointer to softstate
4514  *		capacity - disk capacity in #blocks
4515  *		lbasize - disk block size in bytes
4516  *
4517  *     Context: Kernel thread only
4518  */
4519 
4520 static int
4521 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
4522     diskaddr_t capacity, int lbasize)
4523 {
4524 	uint_t	geombuf;
4525 	int	spc;
4526 
4527 	ASSERT(un != NULL);
4528 
4529 	/* Set sector size, and total number of sectors */
4530 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
4531 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
4532 
4533 	/* Let the HBA tell us its geometry */
4534 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
4535 
4536 	/* A value of -1 indicates an undefined "geometry" property */
4537 	if (geombuf == (-1)) {
4538 		return (EINVAL);
4539 	}
4540 
4541 	/* Initialize the logical geometry cache. */
4542 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
4543 	lgeom_p->g_nsect   = geombuf & 0xffff;
4544 	lgeom_p->g_secsize = un->un_sys_blocksize;
4545 
4546 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
4547 
4548 	/*
4549 	 * Note: The driver originally converted the capacity value from
4550 	 * target blocks to system blocks. However, the capacity value passed
4551 	 * to this routine is already in terms of system blocks (this scaling
4552 	 * is done when the READ CAPACITY command is issued and processed).
4553 	 * This 'error' may have gone undetected because the usage of g_ncyl
4554 	 * (which is based upon g_capacity) is very limited within the driver
4555 	 */
4556 	lgeom_p->g_capacity = capacity;
4557 
4558 	/*
4559 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
4560 	 * hba may return zero values if the device has been removed.
4561 	 */
4562 	if (spc == 0) {
4563 		lgeom_p->g_ncyl = 0;
4564 	} else {
4565 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
4566 	}
4567 	lgeom_p->g_acyl = 0;
4568 
4569 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
4570 	return (0);
4571 
4572 }
4573 /*
4574  *    Function: sd_update_block_info
4575  *
4576  * Description: Calculate a byte count to sector count bitshift value
4577  *		from sector size.
4578  *
4579  *   Arguments: un: unit struct.
4580  *		lbasize: new target sector size
4581  *		capacity: new target capacity, ie. block count
4582  *
4583  *     Context: Kernel thread context
4584  */
4585 
4586 static void
4587 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
4588 {
4589 	uint_t		dblk;
4590 
4591 	if (lbasize != 0) {
4592 		un->un_tgt_blocksize = lbasize;
4593 		un->un_f_tgt_blocksize_is_valid	= TRUE;
4594 	}
4595 
4596 	if (capacity != 0) {
4597 		un->un_blockcount		= capacity;
4598 		un->un_f_blockcount_is_valid	= TRUE;
4599 	}
4600 
4601 	/*
4602 	 * Update device capacity properties.
4603 	 *
4604 	 *   'device-nblocks'	number of blocks in target's units
4605 	 *   'device-blksize'	data bearing size of target's block
4606 	 *
4607 	 * NOTE: math is complicated by the fact that un_tgt_blocksize may
4608 	 * not be a power of two for checksumming disks with 520/528 byte
4609 	 * sectors.
4610 	 */
4611 	if (un->un_f_tgt_blocksize_is_valid &&
4612 	    un->un_f_blockcount_is_valid &&
4613 	    un->un_sys_blocksize) {
4614 		dblk = un->un_tgt_blocksize / un->un_sys_blocksize;
4615 		(void) ddi_prop_update_int64(DDI_DEV_T_NONE, SD_DEVINFO(un),
4616 		    "device-nblocks", un->un_blockcount / dblk);
4617 		/*
4618 		 * To save memory, only define "device-blksize" when its
4619 		 * value is differnet than the default DEV_BSIZE value.
4620 		 */
4621 		if ((un->un_sys_blocksize * dblk) != DEV_BSIZE)
4622 			(void) ddi_prop_update_int(DDI_DEV_T_NONE,
4623 			    SD_DEVINFO(un), "device-blksize",
4624 			    un->un_sys_blocksize * dblk);
4625 	}
4626 }
4627 
4628 
4629 /*
4630  *    Function: sd_register_devid
4631  *
4632  * Description: This routine will obtain the device id information from the
4633  *		target, obtain the serial number, and register the device
4634  *		id with the ddi framework.
4635  *
4636  *   Arguments: devi - the system's dev_info_t for the device.
4637  *		un - driver soft state (unit) structure
4638  *		reservation_flag - indicates if a reservation conflict
4639  *		occurred during attach
4640  *
4641  *     Context: Kernel Thread
4642  */
4643 static void
4644 sd_register_devid(struct sd_lun *un, dev_info_t *devi, int reservation_flag)
4645 {
4646 	int		rval		= 0;
4647 	uchar_t		*inq80		= NULL;
4648 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
4649 	size_t		inq80_resid	= 0;
4650 	uchar_t		*inq83		= NULL;
4651 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
4652 	size_t		inq83_resid	= 0;
4653 	int		dlen, len;
4654 	char		*sn;
4655 
4656 	ASSERT(un != NULL);
4657 	ASSERT(mutex_owned(SD_MUTEX(un)));
4658 	ASSERT((SD_DEVINFO(un)) == devi);
4659 
4660 	/*
4661 	 * If transport has already registered a devid for this target
4662 	 * then that takes precedence over the driver's determination
4663 	 * of the devid.
4664 	 */
4665 	if (ddi_devid_get(SD_DEVINFO(un), &un->un_devid) == DDI_SUCCESS) {
4666 		ASSERT(un->un_devid);
4667 		return; /* use devid registered by the transport */
4668 	}
4669 
4670 	/*
4671 	 * This is the case of antiquated Sun disk drives that have the
4672 	 * FAB_DEVID property set in the disk_table.  These drives
4673 	 * manage the devid's by storing them in last 2 available sectors
4674 	 * on the drive and have them fabricated by the ddi layer by calling
4675 	 * ddi_devid_init and passing the DEVID_FAB flag.
4676 	 */
4677 	if (un->un_f_opt_fab_devid == TRUE) {
4678 		/*
4679 		 * Depending on EINVAL isn't reliable, since a reserved disk
4680 		 * may result in invalid geometry, so check to make sure a
4681 		 * reservation conflict did not occur during attach.
4682 		 */
4683 		if ((sd_get_devid(un) == EINVAL) &&
4684 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
4685 			/*
4686 			 * The devid is invalid AND there is no reservation
4687 			 * conflict.  Fabricate a new devid.
4688 			 */
4689 			(void) sd_create_devid(un);
4690 		}
4691 
4692 		/* Register the devid if it exists */
4693 		if (un->un_devid != NULL) {
4694 			(void) ddi_devid_register(SD_DEVINFO(un),
4695 			    un->un_devid);
4696 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4697 			    "sd_register_devid: Devid Fabricated\n");
4698 		}
4699 		return;
4700 	}
4701 
4702 	/*
4703 	 * We check the availibility of the World Wide Name (0x83) and Unit
4704 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
4705 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
4706 	 * 0x83 is availible, that is the best choice.  Our next choice is
4707 	 * 0x80.  If neither are availible, we munge the devid from the device
4708 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
4709 	 * to fabricate a devid for non-Sun qualified disks.
4710 	 */
4711 	if (sd_check_vpd_page_support(un) == 0) {
4712 		/* collect page 80 data if available */
4713 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
4714 
4715 			mutex_exit(SD_MUTEX(un));
4716 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
4717 			rval = sd_send_scsi_INQUIRY(un, inq80, inq80_len,
4718 			    0x01, 0x80, &inq80_resid);
4719 
4720 			if (rval != 0) {
4721 				kmem_free(inq80, inq80_len);
4722 				inq80 = NULL;
4723 				inq80_len = 0;
4724 			} else if (ddi_prop_exists(
4725 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
4726 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
4727 			    INQUIRY_SERIAL_NO) == 0) {
4728 				/*
4729 				 * If we don't already have a serial number
4730 				 * property, do quick verify of data returned
4731 				 * and define property.
4732 				 */
4733 				dlen = inq80_len - inq80_resid;
4734 				len = (size_t)inq80[3];
4735 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
4736 					/*
4737 					 * Ensure sn termination, skip leading
4738 					 * blanks, and create property
4739 					 * 'inquiry-serial-no'.
4740 					 */
4741 					sn = (char *)&inq80[4];
4742 					sn[len] = 0;
4743 					while (*sn && (*sn == ' '))
4744 						sn++;
4745 					if (*sn) {
4746 						(void) ddi_prop_update_string(
4747 						    DDI_DEV_T_NONE,
4748 						    SD_DEVINFO(un),
4749 						    INQUIRY_SERIAL_NO, sn);
4750 					}
4751 				}
4752 			}
4753 			mutex_enter(SD_MUTEX(un));
4754 		}
4755 
4756 		/* collect page 83 data if available */
4757 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
4758 			mutex_exit(SD_MUTEX(un));
4759 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
4760 			rval = sd_send_scsi_INQUIRY(un, inq83, inq83_len,
4761 			    0x01, 0x83, &inq83_resid);
4762 
4763 			if (rval != 0) {
4764 				kmem_free(inq83, inq83_len);
4765 				inq83 = NULL;
4766 				inq83_len = 0;
4767 			}
4768 			mutex_enter(SD_MUTEX(un));
4769 		}
4770 	}
4771 
4772 	/* encode best devid possible based on data available */
4773 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
4774 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
4775 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
4776 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
4777 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
4778 
4779 		/* devid successfully encoded, register devid */
4780 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
4781 
4782 	} else {
4783 		/*
4784 		 * Unable to encode a devid based on data available.
4785 		 * This is not a Sun qualified disk.  Older Sun disk
4786 		 * drives that have the SD_FAB_DEVID property
4787 		 * set in the disk_table and non Sun qualified
4788 		 * disks are treated in the same manner.  These
4789 		 * drives manage the devid's by storing them in
4790 		 * last 2 available sectors on the drive and
4791 		 * have them fabricated by the ddi layer by
4792 		 * calling ddi_devid_init and passing the
4793 		 * DEVID_FAB flag.
4794 		 * Create a fabricate devid only if there's no
4795 		 * fabricate devid existed.
4796 		 */
4797 		if (sd_get_devid(un) == EINVAL) {
4798 			(void) sd_create_devid(un);
4799 		}
4800 		un->un_f_opt_fab_devid = TRUE;
4801 
4802 		/* Register the devid if it exists */
4803 		if (un->un_devid != NULL) {
4804 			(void) ddi_devid_register(SD_DEVINFO(un),
4805 			    un->un_devid);
4806 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4807 			    "sd_register_devid: devid fabricated using "
4808 			    "ddi framework\n");
4809 		}
4810 	}
4811 
4812 	/* clean up resources */
4813 	if (inq80 != NULL) {
4814 		kmem_free(inq80, inq80_len);
4815 	}
4816 	if (inq83 != NULL) {
4817 		kmem_free(inq83, inq83_len);
4818 	}
4819 }
4820 
4821 
4822 
4823 /*
4824  *    Function: sd_get_devid
4825  *
4826  * Description: This routine will return 0 if a valid device id has been
4827  *		obtained from the target and stored in the soft state. If a
4828  *		valid device id has not been previously read and stored, a
4829  *		read attempt will be made.
4830  *
4831  *   Arguments: un - driver soft state (unit) structure
4832  *
4833  * Return Code: 0 if we successfully get the device id
4834  *
4835  *     Context: Kernel Thread
4836  */
4837 
4838 static int
4839 sd_get_devid(struct sd_lun *un)
4840 {
4841 	struct dk_devid		*dkdevid;
4842 	ddi_devid_t		tmpid;
4843 	uint_t			*ip;
4844 	size_t			sz;
4845 	diskaddr_t		blk;
4846 	int			status;
4847 	int			chksum;
4848 	int			i;
4849 	size_t			buffer_size;
4850 
4851 	ASSERT(un != NULL);
4852 	ASSERT(mutex_owned(SD_MUTEX(un)));
4853 
4854 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
4855 	    un);
4856 
4857 	if (un->un_devid != NULL) {
4858 		return (0);
4859 	}
4860 
4861 	mutex_exit(SD_MUTEX(un));
4862 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
4863 	    (void *)SD_PATH_DIRECT) != 0) {
4864 		mutex_enter(SD_MUTEX(un));
4865 		return (EINVAL);
4866 	}
4867 
4868 	/*
4869 	 * Read and verify device id, stored in the reserved cylinders at the
4870 	 * end of the disk. Backup label is on the odd sectors of the last
4871 	 * track of the last cylinder. Device id will be on track of the next
4872 	 * to last cylinder.
4873 	 */
4874 	mutex_enter(SD_MUTEX(un));
4875 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
4876 	mutex_exit(SD_MUTEX(un));
4877 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
4878 	status = sd_send_scsi_READ(un, dkdevid, buffer_size, blk,
4879 	    SD_PATH_DIRECT);
4880 	if (status != 0) {
4881 		goto error;
4882 	}
4883 
4884 	/* Validate the revision */
4885 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
4886 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
4887 		status = EINVAL;
4888 		goto error;
4889 	}
4890 
4891 	/* Calculate the checksum */
4892 	chksum = 0;
4893 	ip = (uint_t *)dkdevid;
4894 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
4895 	    i++) {
4896 		chksum ^= ip[i];
4897 	}
4898 
4899 	/* Compare the checksums */
4900 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
4901 		status = EINVAL;
4902 		goto error;
4903 	}
4904 
4905 	/* Validate the device id */
4906 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
4907 		status = EINVAL;
4908 		goto error;
4909 	}
4910 
4911 	/*
4912 	 * Store the device id in the driver soft state
4913 	 */
4914 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
4915 	tmpid = kmem_alloc(sz, KM_SLEEP);
4916 
4917 	mutex_enter(SD_MUTEX(un));
4918 
4919 	un->un_devid = tmpid;
4920 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
4921 
4922 	kmem_free(dkdevid, buffer_size);
4923 
4924 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
4925 
4926 	return (status);
4927 error:
4928 	mutex_enter(SD_MUTEX(un));
4929 	kmem_free(dkdevid, buffer_size);
4930 	return (status);
4931 }
4932 
4933 
4934 /*
4935  *    Function: sd_create_devid
4936  *
4937  * Description: This routine will fabricate the device id and write it
4938  *		to the disk.
4939  *
4940  *   Arguments: un - driver soft state (unit) structure
4941  *
4942  * Return Code: value of the fabricated device id
4943  *
4944  *     Context: Kernel Thread
4945  */
4946 
4947 static ddi_devid_t
4948 sd_create_devid(struct sd_lun *un)
4949 {
4950 	ASSERT(un != NULL);
4951 
4952 	/* Fabricate the devid */
4953 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
4954 	    == DDI_FAILURE) {
4955 		return (NULL);
4956 	}
4957 
4958 	/* Write the devid to disk */
4959 	if (sd_write_deviceid(un) != 0) {
4960 		ddi_devid_free(un->un_devid);
4961 		un->un_devid = NULL;
4962 	}
4963 
4964 	return (un->un_devid);
4965 }
4966 
4967 
4968 /*
4969  *    Function: sd_write_deviceid
4970  *
4971  * Description: This routine will write the device id to the disk
4972  *		reserved sector.
4973  *
4974  *   Arguments: un - driver soft state (unit) structure
4975  *
4976  * Return Code: EINVAL
4977  *		value returned by sd_send_scsi_cmd
4978  *
4979  *     Context: Kernel Thread
4980  */
4981 
4982 static int
4983 sd_write_deviceid(struct sd_lun *un)
4984 {
4985 	struct dk_devid		*dkdevid;
4986 	diskaddr_t		blk;
4987 	uint_t			*ip, chksum;
4988 	int			status;
4989 	int			i;
4990 
4991 	ASSERT(mutex_owned(SD_MUTEX(un)));
4992 
4993 	mutex_exit(SD_MUTEX(un));
4994 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
4995 	    (void *)SD_PATH_DIRECT) != 0) {
4996 		mutex_enter(SD_MUTEX(un));
4997 		return (-1);
4998 	}
4999 
5000 
5001 	/* Allocate the buffer */
5002 	dkdevid = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
5003 
5004 	/* Fill in the revision */
5005 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
5006 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
5007 
5008 	/* Copy in the device id */
5009 	mutex_enter(SD_MUTEX(un));
5010 	bcopy(un->un_devid, &dkdevid->dkd_devid,
5011 	    ddi_devid_sizeof(un->un_devid));
5012 	mutex_exit(SD_MUTEX(un));
5013 
5014 	/* Calculate the checksum */
5015 	chksum = 0;
5016 	ip = (uint_t *)dkdevid;
5017 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
5018 	    i++) {
5019 		chksum ^= ip[i];
5020 	}
5021 
5022 	/* Fill-in checksum */
5023 	DKD_FORMCHKSUM(chksum, dkdevid);
5024 
5025 	/* Write the reserved sector */
5026 	status = sd_send_scsi_WRITE(un, dkdevid, un->un_sys_blocksize, blk,
5027 	    SD_PATH_DIRECT);
5028 
5029 	kmem_free(dkdevid, un->un_sys_blocksize);
5030 
5031 	mutex_enter(SD_MUTEX(un));
5032 	return (status);
5033 }
5034 
5035 
5036 /*
5037  *    Function: sd_check_vpd_page_support
5038  *
5039  * Description: This routine sends an inquiry command with the EVPD bit set and
5040  *		a page code of 0x00 to the device. It is used to determine which
5041  *		vital product pages are availible to find the devid. We are
5042  *		looking for pages 0x83 or 0x80.  If we return a negative 1, the
5043  *		device does not support that command.
5044  *
5045  *   Arguments: un  - driver soft state (unit) structure
5046  *
5047  * Return Code: 0 - success
5048  *		1 - check condition
5049  *
5050  *     Context: This routine can sleep.
5051  */
5052 
5053 static int
5054 sd_check_vpd_page_support(struct sd_lun *un)
5055 {
5056 	uchar_t	*page_list	= NULL;
5057 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5058 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5059 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5060 	int    	rval		= 0;
5061 	int	counter;
5062 
5063 	ASSERT(un != NULL);
5064 	ASSERT(mutex_owned(SD_MUTEX(un)));
5065 
5066 	mutex_exit(SD_MUTEX(un));
5067 
5068 	/*
5069 	 * We'll set the page length to the maximum to save figuring it out
5070 	 * with an additional call.
5071 	 */
5072 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5073 
5074 	rval = sd_send_scsi_INQUIRY(un, page_list, page_length, evpd,
5075 	    page_code, NULL);
5076 
5077 	mutex_enter(SD_MUTEX(un));
5078 
5079 	/*
5080 	 * Now we must validate that the device accepted the command, as some
5081 	 * drives do not support it.  If the drive does support it, we will
5082 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5083 	 * not, we return -1.
5084 	 */
5085 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5086 		/* Loop to find one of the 2 pages we need */
5087 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5088 
5089 		/*
5090 		 * Pages are returned in ascending order, and 0x83 is what we
5091 		 * are hoping for.
5092 		 */
5093 		while ((page_list[counter] <= 0x86) &&
5094 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5095 		    VPD_HEAD_OFFSET))) {
5096 			/*
5097 			 * Add 3 because page_list[3] is the number of
5098 			 * pages minus 3
5099 			 */
5100 
5101 			switch (page_list[counter]) {
5102 			case 0x00:
5103 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5104 				break;
5105 			case 0x80:
5106 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5107 				break;
5108 			case 0x81:
5109 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5110 				break;
5111 			case 0x82:
5112 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5113 				break;
5114 			case 0x83:
5115 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5116 				break;
5117 			case 0x86:
5118 				un->un_vpd_page_mask |= SD_VPD_EXTENDED_DATA_PG;
5119 				break;
5120 			}
5121 			counter++;
5122 		}
5123 
5124 	} else {
5125 		rval = -1;
5126 
5127 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5128 		    "sd_check_vpd_page_support: This drive does not implement "
5129 		    "VPD pages.\n");
5130 	}
5131 
5132 	kmem_free(page_list, page_length);
5133 
5134 	return (rval);
5135 }
5136 
5137 
5138 /*
5139  *    Function: sd_setup_pm
5140  *
5141  * Description: Initialize Power Management on the device
5142  *
5143  *     Context: Kernel Thread
5144  */
5145 
5146 static void
5147 sd_setup_pm(struct sd_lun *un, dev_info_t *devi)
5148 {
5149 	uint_t	log_page_size;
5150 	uchar_t	*log_page_data;
5151 	int	rval;
5152 
5153 	/*
5154 	 * Since we are called from attach, holding a mutex for
5155 	 * un is unnecessary. Because some of the routines called
5156 	 * from here require SD_MUTEX to not be held, assert this
5157 	 * right up front.
5158 	 */
5159 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5160 	/*
5161 	 * Since the sd device does not have the 'reg' property,
5162 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5163 	 * The following code is to tell cpr that this device
5164 	 * DOES need to be suspended and resumed.
5165 	 */
5166 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5167 	    "pm-hardware-state", "needs-suspend-resume");
5168 
5169 	/*
5170 	 * This complies with the new power management framework
5171 	 * for certain desktop machines. Create the pm_components
5172 	 * property as a string array property.
5173 	 */
5174 	if (un->un_f_pm_supported) {
5175 		/*
5176 		 * not all devices have a motor, try it first.
5177 		 * some devices may return ILLEGAL REQUEST, some
5178 		 * will hang
5179 		 * The following START_STOP_UNIT is used to check if target
5180 		 * device has a motor.
5181 		 */
5182 		un->un_f_start_stop_supported = TRUE;
5183 		if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
5184 		    SD_PATH_DIRECT) != 0) {
5185 			un->un_f_start_stop_supported = FALSE;
5186 		}
5187 
5188 		/*
5189 		 * create pm properties anyways otherwise the parent can't
5190 		 * go to sleep
5191 		 */
5192 		(void) sd_create_pm_components(devi, un);
5193 		un->un_f_pm_is_enabled = TRUE;
5194 		return;
5195 	}
5196 
5197 	if (!un->un_f_log_sense_supported) {
5198 		un->un_power_level = SD_SPINDLE_ON;
5199 		un->un_f_pm_is_enabled = FALSE;
5200 		return;
5201 	}
5202 
5203 	rval = sd_log_page_supported(un, START_STOP_CYCLE_PAGE);
5204 
5205 #ifdef	SDDEBUG
5206 	if (sd_force_pm_supported) {
5207 		/* Force a successful result */
5208 		rval = 1;
5209 	}
5210 #endif
5211 
5212 	/*
5213 	 * If the start-stop cycle counter log page is not supported
5214 	 * or if the pm-capable property is SD_PM_CAPABLE_FALSE (0)
5215 	 * then we should not create the pm_components property.
5216 	 */
5217 	if (rval == -1) {
5218 		/*
5219 		 * Error.
5220 		 * Reading log sense failed, most likely this is
5221 		 * an older drive that does not support log sense.
5222 		 * If this fails auto-pm is not supported.
5223 		 */
5224 		un->un_power_level = SD_SPINDLE_ON;
5225 		un->un_f_pm_is_enabled = FALSE;
5226 
5227 	} else if (rval == 0) {
5228 		/*
5229 		 * Page not found.
5230 		 * The start stop cycle counter is implemented as page
5231 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
5232 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
5233 		 */
5234 		if (sd_log_page_supported(un, START_STOP_CYCLE_VU_PAGE) == 1) {
5235 			/*
5236 			 * Page found, use this one.
5237 			 */
5238 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
5239 			un->un_f_pm_is_enabled = TRUE;
5240 		} else {
5241 			/*
5242 			 * Error or page not found.
5243 			 * auto-pm is not supported for this device.
5244 			 */
5245 			un->un_power_level = SD_SPINDLE_ON;
5246 			un->un_f_pm_is_enabled = FALSE;
5247 		}
5248 	} else {
5249 		/*
5250 		 * Page found, use it.
5251 		 */
5252 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
5253 		un->un_f_pm_is_enabled = TRUE;
5254 	}
5255 
5256 
5257 	if (un->un_f_pm_is_enabled == TRUE) {
5258 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5259 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5260 
5261 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
5262 		    log_page_size, un->un_start_stop_cycle_page,
5263 		    0x01, 0, SD_PATH_DIRECT);
5264 #ifdef	SDDEBUG
5265 		if (sd_force_pm_supported) {
5266 			/* Force a successful result */
5267 			rval = 0;
5268 		}
5269 #endif
5270 
5271 		/*
5272 		 * If the Log sense for Page( Start/stop cycle counter page)
5273 		 * succeeds, then power managment is supported and we can
5274 		 * enable auto-pm.
5275 		 */
5276 		if (rval == 0)  {
5277 			(void) sd_create_pm_components(devi, un);
5278 		} else {
5279 			un->un_power_level = SD_SPINDLE_ON;
5280 			un->un_f_pm_is_enabled = FALSE;
5281 		}
5282 
5283 		kmem_free(log_page_data, log_page_size);
5284 	}
5285 }
5286 
5287 
5288 /*
5289  *    Function: sd_create_pm_components
5290  *
5291  * Description: Initialize PM property.
5292  *
5293  *     Context: Kernel thread context
5294  */
5295 
5296 static void
5297 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
5298 {
5299 	char *pm_comp[] = { "NAME=spindle-motor", "0=off", "1=on", NULL };
5300 
5301 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5302 
5303 	if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
5304 	    "pm-components", pm_comp, 3) == DDI_PROP_SUCCESS) {
5305 		/*
5306 		 * When components are initially created they are idle,
5307 		 * power up any non-removables.
5308 		 * Note: the return value of pm_raise_power can't be used
5309 		 * for determining if PM should be enabled for this device.
5310 		 * Even if you check the return values and remove this
5311 		 * property created above, the PM framework will not honor the
5312 		 * change after the first call to pm_raise_power. Hence,
5313 		 * removal of that property does not help if pm_raise_power
5314 		 * fails. In the case of removable media, the start/stop
5315 		 * will fail if the media is not present.
5316 		 */
5317 		if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
5318 		    SD_SPINDLE_ON) == DDI_SUCCESS)) {
5319 			mutex_enter(SD_MUTEX(un));
5320 			un->un_power_level = SD_SPINDLE_ON;
5321 			mutex_enter(&un->un_pm_mutex);
5322 			/* Set to on and not busy. */
5323 			un->un_pm_count = 0;
5324 		} else {
5325 			mutex_enter(SD_MUTEX(un));
5326 			un->un_power_level = SD_SPINDLE_OFF;
5327 			mutex_enter(&un->un_pm_mutex);
5328 			/* Set to off. */
5329 			un->un_pm_count = -1;
5330 		}
5331 		mutex_exit(&un->un_pm_mutex);
5332 		mutex_exit(SD_MUTEX(un));
5333 	} else {
5334 		un->un_power_level = SD_SPINDLE_ON;
5335 		un->un_f_pm_is_enabled = FALSE;
5336 	}
5337 }
5338 
5339 
5340 /*
5341  *    Function: sd_ddi_suspend
5342  *
5343  * Description: Performs system power-down operations. This includes
5344  *		setting the drive state to indicate its suspended so
5345  *		that no new commands will be accepted. Also, wait for
5346  *		all commands that are in transport or queued to a timer
5347  *		for retry to complete. All timeout threads are cancelled.
5348  *
5349  * Return Code: DDI_FAILURE or DDI_SUCCESS
5350  *
5351  *     Context: Kernel thread context
5352  */
5353 
5354 static int
5355 sd_ddi_suspend(dev_info_t *devi)
5356 {
5357 	struct	sd_lun	*un;
5358 	clock_t		wait_cmds_complete;
5359 
5360 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
5361 	if (un == NULL) {
5362 		return (DDI_FAILURE);
5363 	}
5364 
5365 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
5366 
5367 	mutex_enter(SD_MUTEX(un));
5368 
5369 	/* Return success if the device is already suspended. */
5370 	if (un->un_state == SD_STATE_SUSPENDED) {
5371 		mutex_exit(SD_MUTEX(un));
5372 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5373 		    "device already suspended, exiting\n");
5374 		return (DDI_SUCCESS);
5375 	}
5376 
5377 	/* Return failure if the device is being used by HA */
5378 	if (un->un_resvd_status &
5379 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
5380 		mutex_exit(SD_MUTEX(un));
5381 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5382 		    "device in use by HA, exiting\n");
5383 		return (DDI_FAILURE);
5384 	}
5385 
5386 	/*
5387 	 * Return failure if the device is in a resource wait
5388 	 * or power changing state.
5389 	 */
5390 	if ((un->un_state == SD_STATE_RWAIT) ||
5391 	    (un->un_state == SD_STATE_PM_CHANGING)) {
5392 		mutex_exit(SD_MUTEX(un));
5393 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5394 		    "device in resource wait state, exiting\n");
5395 		return (DDI_FAILURE);
5396 	}
5397 
5398 
5399 	un->un_save_state = un->un_last_state;
5400 	New_state(un, SD_STATE_SUSPENDED);
5401 
5402 	/*
5403 	 * Wait for all commands that are in transport or queued to a timer
5404 	 * for retry to complete.
5405 	 *
5406 	 * While waiting, no new commands will be accepted or sent because of
5407 	 * the new state we set above.
5408 	 *
5409 	 * Wait till current operation has completed. If we are in the resource
5410 	 * wait state (with an intr outstanding) then we need to wait till the
5411 	 * intr completes and starts the next cmd. We want to wait for
5412 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
5413 	 */
5414 	wait_cmds_complete = ddi_get_lbolt() +
5415 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
5416 
5417 	while (un->un_ncmds_in_transport != 0) {
5418 		/*
5419 		 * Fail if commands do not finish in the specified time.
5420 		 */
5421 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
5422 		    wait_cmds_complete) == -1) {
5423 			/*
5424 			 * Undo the state changes made above. Everything
5425 			 * must go back to it's original value.
5426 			 */
5427 			Restore_state(un);
5428 			un->un_last_state = un->un_save_state;
5429 			/* Wake up any threads that might be waiting. */
5430 			cv_broadcast(&un->un_suspend_cv);
5431 			mutex_exit(SD_MUTEX(un));
5432 			SD_ERROR(SD_LOG_IO_PM, un,
5433 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
5434 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
5435 			return (DDI_FAILURE);
5436 		}
5437 	}
5438 
5439 	/*
5440 	 * Cancel SCSI watch thread and timeouts, if any are active
5441 	 */
5442 
5443 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
5444 		opaque_t temp_token = un->un_swr_token;
5445 		mutex_exit(SD_MUTEX(un));
5446 		scsi_watch_suspend(temp_token);
5447 		mutex_enter(SD_MUTEX(un));
5448 	}
5449 
5450 	if (un->un_reset_throttle_timeid != NULL) {
5451 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
5452 		un->un_reset_throttle_timeid = NULL;
5453 		mutex_exit(SD_MUTEX(un));
5454 		(void) untimeout(temp_id);
5455 		mutex_enter(SD_MUTEX(un));
5456 	}
5457 
5458 	if (un->un_dcvb_timeid != NULL) {
5459 		timeout_id_t temp_id = un->un_dcvb_timeid;
5460 		un->un_dcvb_timeid = NULL;
5461 		mutex_exit(SD_MUTEX(un));
5462 		(void) untimeout(temp_id);
5463 		mutex_enter(SD_MUTEX(un));
5464 	}
5465 
5466 	mutex_enter(&un->un_pm_mutex);
5467 	if (un->un_pm_timeid != NULL) {
5468 		timeout_id_t temp_id = un->un_pm_timeid;
5469 		un->un_pm_timeid = NULL;
5470 		mutex_exit(&un->un_pm_mutex);
5471 		mutex_exit(SD_MUTEX(un));
5472 		(void) untimeout(temp_id);
5473 		mutex_enter(SD_MUTEX(un));
5474 	} else {
5475 		mutex_exit(&un->un_pm_mutex);
5476 	}
5477 
5478 	if (un->un_retry_timeid != NULL) {
5479 		timeout_id_t temp_id = un->un_retry_timeid;
5480 		un->un_retry_timeid = NULL;
5481 		mutex_exit(SD_MUTEX(un));
5482 		(void) untimeout(temp_id);
5483 		mutex_enter(SD_MUTEX(un));
5484 	}
5485 
5486 	if (un->un_direct_priority_timeid != NULL) {
5487 		timeout_id_t temp_id = un->un_direct_priority_timeid;
5488 		un->un_direct_priority_timeid = NULL;
5489 		mutex_exit(SD_MUTEX(un));
5490 		(void) untimeout(temp_id);
5491 		mutex_enter(SD_MUTEX(un));
5492 	}
5493 
5494 	if (un->un_f_is_fibre == TRUE) {
5495 		/*
5496 		 * Remove callbacks for insert and remove events
5497 		 */
5498 		if (un->un_insert_event != NULL) {
5499 			mutex_exit(SD_MUTEX(un));
5500 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
5501 			mutex_enter(SD_MUTEX(un));
5502 			un->un_insert_event = NULL;
5503 		}
5504 
5505 		if (un->un_remove_event != NULL) {
5506 			mutex_exit(SD_MUTEX(un));
5507 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
5508 			mutex_enter(SD_MUTEX(un));
5509 			un->un_remove_event = NULL;
5510 		}
5511 	}
5512 
5513 	mutex_exit(SD_MUTEX(un));
5514 
5515 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
5516 
5517 	return (DDI_SUCCESS);
5518 }
5519 
5520 
5521 /*
5522  *    Function: sd_ddi_pm_suspend
5523  *
5524  * Description: Set the drive state to low power.
5525  *		Someone else is required to actually change the drive
5526  *		power level.
5527  *
5528  *   Arguments: un - driver soft state (unit) structure
5529  *
5530  * Return Code: DDI_FAILURE or DDI_SUCCESS
5531  *
5532  *     Context: Kernel thread context
5533  */
5534 
5535 static int
5536 sd_ddi_pm_suspend(struct sd_lun *un)
5537 {
5538 	ASSERT(un != NULL);
5539 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: entry\n");
5540 
5541 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5542 	mutex_enter(SD_MUTEX(un));
5543 
5544 	/*
5545 	 * Exit if power management is not enabled for this device, or if
5546 	 * the device is being used by HA.
5547 	 */
5548 	if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
5549 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
5550 		mutex_exit(SD_MUTEX(un));
5551 		SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exiting\n");
5552 		return (DDI_SUCCESS);
5553 	}
5554 
5555 	SD_INFO(SD_LOG_POWER, un, "sd_ddi_pm_suspend: un_ncmds_in_driver=%ld\n",
5556 	    un->un_ncmds_in_driver);
5557 
5558 	/*
5559 	 * See if the device is not busy, ie.:
5560 	 *    - we have no commands in the driver for this device
5561 	 *    - not waiting for resources
5562 	 */
5563 	if ((un->un_ncmds_in_driver == 0) &&
5564 	    (un->un_state != SD_STATE_RWAIT)) {
5565 		/*
5566 		 * The device is not busy, so it is OK to go to low power state.
5567 		 * Indicate low power, but rely on someone else to actually
5568 		 * change it.
5569 		 */
5570 		mutex_enter(&un->un_pm_mutex);
5571 		un->un_pm_count = -1;
5572 		mutex_exit(&un->un_pm_mutex);
5573 		un->un_power_level = SD_SPINDLE_OFF;
5574 	}
5575 
5576 	mutex_exit(SD_MUTEX(un));
5577 
5578 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exit\n");
5579 
5580 	return (DDI_SUCCESS);
5581 }
5582 
5583 
5584 /*
5585  *    Function: sd_ddi_resume
5586  *
5587  * Description: Performs system power-up operations..
5588  *
5589  * Return Code: DDI_SUCCESS
5590  *		DDI_FAILURE
5591  *
5592  *     Context: Kernel thread context
5593  */
5594 
5595 static int
5596 sd_ddi_resume(dev_info_t *devi)
5597 {
5598 	struct	sd_lun	*un;
5599 
5600 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
5601 	if (un == NULL) {
5602 		return (DDI_FAILURE);
5603 	}
5604 
5605 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
5606 
5607 	mutex_enter(SD_MUTEX(un));
5608 	Restore_state(un);
5609 
5610 	/*
5611 	 * Restore the state which was saved to give the
5612 	 * the right state in un_last_state
5613 	 */
5614 	un->un_last_state = un->un_save_state;
5615 	/*
5616 	 * Note: throttle comes back at full.
5617 	 * Also note: this MUST be done before calling pm_raise_power
5618 	 * otherwise the system can get hung in biowait. The scenario where
5619 	 * this'll happen is under cpr suspend. Writing of the system
5620 	 * state goes through sddump, which writes 0 to un_throttle. If
5621 	 * writing the system state then fails, example if the partition is
5622 	 * too small, then cpr attempts a resume. If throttle isn't restored
5623 	 * from the saved value until after calling pm_raise_power then
5624 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
5625 	 * in biowait.
5626 	 */
5627 	un->un_throttle = un->un_saved_throttle;
5628 
5629 	/*
5630 	 * The chance of failure is very rare as the only command done in power
5631 	 * entry point is START command when you transition from 0->1 or
5632 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
5633 	 * which suspend was done. Ignore the return value as the resume should
5634 	 * not be failed. In the case of removable media the media need not be
5635 	 * inserted and hence there is a chance that raise power will fail with
5636 	 * media not present.
5637 	 */
5638 	if (un->un_f_attach_spinup) {
5639 		mutex_exit(SD_MUTEX(un));
5640 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
5641 		mutex_enter(SD_MUTEX(un));
5642 	}
5643 
5644 	/*
5645 	 * Don't broadcast to the suspend cv and therefore possibly
5646 	 * start I/O until after power has been restored.
5647 	 */
5648 	cv_broadcast(&un->un_suspend_cv);
5649 	cv_broadcast(&un->un_state_cv);
5650 
5651 	/* restart thread */
5652 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
5653 		scsi_watch_resume(un->un_swr_token);
5654 	}
5655 
5656 #if (defined(__fibre))
5657 	if (un->un_f_is_fibre == TRUE) {
5658 		/*
5659 		 * Add callbacks for insert and remove events
5660 		 */
5661 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
5662 			sd_init_event_callbacks(un);
5663 		}
5664 	}
5665 #endif
5666 
5667 	/*
5668 	 * Transport any pending commands to the target.
5669 	 *
5670 	 * If this is a low-activity device commands in queue will have to wait
5671 	 * until new commands come in, which may take awhile. Also, we
5672 	 * specifically don't check un_ncmds_in_transport because we know that
5673 	 * there really are no commands in progress after the unit was
5674 	 * suspended and we could have reached the throttle level, been
5675 	 * suspended, and have no new commands coming in for awhile. Highly
5676 	 * unlikely, but so is the low-activity disk scenario.
5677 	 */
5678 	ddi_xbuf_dispatch(un->un_xbuf_attr);
5679 
5680 	sd_start_cmds(un, NULL);
5681 	mutex_exit(SD_MUTEX(un));
5682 
5683 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
5684 
5685 	return (DDI_SUCCESS);
5686 }
5687 
5688 
5689 /*
5690  *    Function: sd_ddi_pm_resume
5691  *
5692  * Description: Set the drive state to powered on.
5693  *		Someone else is required to actually change the drive
5694  *		power level.
5695  *
5696  *   Arguments: un - driver soft state (unit) structure
5697  *
5698  * Return Code: DDI_SUCCESS
5699  *
5700  *     Context: Kernel thread context
5701  */
5702 
5703 static int
5704 sd_ddi_pm_resume(struct sd_lun *un)
5705 {
5706 	ASSERT(un != NULL);
5707 
5708 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5709 	mutex_enter(SD_MUTEX(un));
5710 	un->un_power_level = SD_SPINDLE_ON;
5711 
5712 	ASSERT(!mutex_owned(&un->un_pm_mutex));
5713 	mutex_enter(&un->un_pm_mutex);
5714 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
5715 		un->un_pm_count++;
5716 		ASSERT(un->un_pm_count == 0);
5717 		/*
5718 		 * Note: no longer do the cv_broadcast on un_suspend_cv. The
5719 		 * un_suspend_cv is for a system resume, not a power management
5720 		 * device resume. (4297749)
5721 		 *	 cv_broadcast(&un->un_suspend_cv);
5722 		 */
5723 	}
5724 	mutex_exit(&un->un_pm_mutex);
5725 	mutex_exit(SD_MUTEX(un));
5726 
5727 	return (DDI_SUCCESS);
5728 }
5729 
5730 
5731 /*
5732  *    Function: sd_pm_idletimeout_handler
5733  *
5734  * Description: A timer routine that's active only while a device is busy.
5735  *		The purpose is to extend slightly the pm framework's busy
5736  *		view of the device to prevent busy/idle thrashing for
5737  *		back-to-back commands. Do this by comparing the current time
5738  *		to the time at which the last command completed and when the
5739  *		difference is greater than sd_pm_idletime, call
5740  *		pm_idle_component. In addition to indicating idle to the pm
5741  *		framework, update the chain type to again use the internal pm
5742  *		layers of the driver.
5743  *
5744  *   Arguments: arg - driver soft state (unit) structure
5745  *
5746  *     Context: Executes in a timeout(9F) thread context
5747  */
5748 
5749 static void
5750 sd_pm_idletimeout_handler(void *arg)
5751 {
5752 	struct sd_lun *un = arg;
5753 
5754 	time_t	now;
5755 
5756 	mutex_enter(&sd_detach_mutex);
5757 	if (un->un_detach_count != 0) {
5758 		/* Abort if the instance is detaching */
5759 		mutex_exit(&sd_detach_mutex);
5760 		return;
5761 	}
5762 	mutex_exit(&sd_detach_mutex);
5763 
5764 	now = ddi_get_time();
5765 	/*
5766 	 * Grab both mutexes, in the proper order, since we're accessing
5767 	 * both PM and softstate variables.
5768 	 */
5769 	mutex_enter(SD_MUTEX(un));
5770 	mutex_enter(&un->un_pm_mutex);
5771 	if (((now - un->un_pm_idle_time) > sd_pm_idletime) &&
5772 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
5773 		/*
5774 		 * Update the chain types.
5775 		 * This takes affect on the next new command received.
5776 		 */
5777 		if (un->un_f_non_devbsize_supported) {
5778 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
5779 		} else {
5780 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
5781 		}
5782 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
5783 
5784 		SD_TRACE(SD_LOG_IO_PM, un,
5785 		    "sd_pm_idletimeout_handler: idling device\n");
5786 		(void) pm_idle_component(SD_DEVINFO(un), 0);
5787 		un->un_pm_idle_timeid = NULL;
5788 	} else {
5789 		un->un_pm_idle_timeid =
5790 		    timeout(sd_pm_idletimeout_handler, un,
5791 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
5792 	}
5793 	mutex_exit(&un->un_pm_mutex);
5794 	mutex_exit(SD_MUTEX(un));
5795 }
5796 
5797 
5798 /*
5799  *    Function: sd_pm_timeout_handler
5800  *
5801  * Description: Callback to tell framework we are idle.
5802  *
5803  *     Context: timeout(9f) thread context.
5804  */
5805 
5806 static void
5807 sd_pm_timeout_handler(void *arg)
5808 {
5809 	struct sd_lun *un = arg;
5810 
5811 	(void) pm_idle_component(SD_DEVINFO(un), 0);
5812 	mutex_enter(&un->un_pm_mutex);
5813 	un->un_pm_timeid = NULL;
5814 	mutex_exit(&un->un_pm_mutex);
5815 }
5816 
5817 
5818 /*
5819  *    Function: sdpower
5820  *
5821  * Description: PM entry point.
5822  *
5823  * Return Code: DDI_SUCCESS
5824  *		DDI_FAILURE
5825  *
5826  *     Context: Kernel thread context
5827  */
5828 
5829 static int
5830 sdpower(dev_info_t *devi, int component, int level)
5831 {
5832 	struct sd_lun	*un;
5833 	int		instance;
5834 	int		rval = DDI_SUCCESS;
5835 	uint_t		i, log_page_size, maxcycles, ncycles;
5836 	uchar_t		*log_page_data;
5837 	int		log_sense_page;
5838 	int		medium_present;
5839 	time_t		intvlp;
5840 	dev_t		dev;
5841 	struct pm_trans_data	sd_pm_tran_data;
5842 	uchar_t		save_state;
5843 	int		sval;
5844 	uchar_t		state_before_pm;
5845 	int		got_semaphore_here;
5846 
5847 	instance = ddi_get_instance(devi);
5848 
5849 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
5850 	    (SD_SPINDLE_OFF > level) || (level > SD_SPINDLE_ON) ||
5851 	    component != 0) {
5852 		return (DDI_FAILURE);
5853 	}
5854 
5855 	dev = sd_make_device(SD_DEVINFO(un));
5856 
5857 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
5858 
5859 	/*
5860 	 * Must synchronize power down with close.
5861 	 * Attempt to decrement/acquire the open/close semaphore,
5862 	 * but do NOT wait on it. If it's not greater than zero,
5863 	 * ie. it can't be decremented without waiting, then
5864 	 * someone else, either open or close, already has it
5865 	 * and the try returns 0. Use that knowledge here to determine
5866 	 * if it's OK to change the device power level.
5867 	 * Also, only increment it on exit if it was decremented, ie. gotten,
5868 	 * here.
5869 	 */
5870 	got_semaphore_here = sema_tryp(&un->un_semoclose);
5871 
5872 	mutex_enter(SD_MUTEX(un));
5873 
5874 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
5875 	    un->un_ncmds_in_driver);
5876 
5877 	/*
5878 	 * If un_ncmds_in_driver is non-zero it indicates commands are
5879 	 * already being processed in the driver, or if the semaphore was
5880 	 * not gotten here it indicates an open or close is being processed.
5881 	 * At the same time somebody is requesting to go low power which
5882 	 * can't happen, therefore we need to return failure.
5883 	 */
5884 	if ((level == SD_SPINDLE_OFF) &&
5885 	    ((un->un_ncmds_in_driver != 0) || (got_semaphore_here == 0))) {
5886 		mutex_exit(SD_MUTEX(un));
5887 
5888 		if (got_semaphore_here != 0) {
5889 			sema_v(&un->un_semoclose);
5890 		}
5891 		SD_TRACE(SD_LOG_IO_PM, un,
5892 		    "sdpower: exit, device has queued cmds.\n");
5893 		return (DDI_FAILURE);
5894 	}
5895 
5896 	/*
5897 	 * if it is OFFLINE that means the disk is completely dead
5898 	 * in our case we have to put the disk in on or off by sending commands
5899 	 * Of course that will fail anyway so return back here.
5900 	 *
5901 	 * Power changes to a device that's OFFLINE or SUSPENDED
5902 	 * are not allowed.
5903 	 */
5904 	if ((un->un_state == SD_STATE_OFFLINE) ||
5905 	    (un->un_state == SD_STATE_SUSPENDED)) {
5906 		mutex_exit(SD_MUTEX(un));
5907 
5908 		if (got_semaphore_here != 0) {
5909 			sema_v(&un->un_semoclose);
5910 		}
5911 		SD_TRACE(SD_LOG_IO_PM, un,
5912 		    "sdpower: exit, device is off-line.\n");
5913 		return (DDI_FAILURE);
5914 	}
5915 
5916 	/*
5917 	 * Change the device's state to indicate it's power level
5918 	 * is being changed. Do this to prevent a power off in the
5919 	 * middle of commands, which is especially bad on devices
5920 	 * that are really powered off instead of just spun down.
5921 	 */
5922 	state_before_pm = un->un_state;
5923 	un->un_state = SD_STATE_PM_CHANGING;
5924 
5925 	mutex_exit(SD_MUTEX(un));
5926 
5927 	/*
5928 	 * If "pm-capable" property is set to TRUE by HBA drivers,
5929 	 * bypass the following checking, otherwise, check the log
5930 	 * sense information for this device
5931 	 */
5932 	if ((level == SD_SPINDLE_OFF) && un->un_f_log_sense_supported) {
5933 		/*
5934 		 * Get the log sense information to understand whether the
5935 		 * the powercycle counts have gone beyond the threshhold.
5936 		 */
5937 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5938 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5939 
5940 		mutex_enter(SD_MUTEX(un));
5941 		log_sense_page = un->un_start_stop_cycle_page;
5942 		mutex_exit(SD_MUTEX(un));
5943 
5944 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
5945 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
5946 #ifdef	SDDEBUG
5947 		if (sd_force_pm_supported) {
5948 			/* Force a successful result */
5949 			rval = 0;
5950 		}
5951 #endif
5952 		if (rval != 0) {
5953 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5954 			    "Log Sense Failed\n");
5955 			kmem_free(log_page_data, log_page_size);
5956 			/* Cannot support power management on those drives */
5957 
5958 			if (got_semaphore_here != 0) {
5959 				sema_v(&un->un_semoclose);
5960 			}
5961 			/*
5962 			 * On exit put the state back to it's original value
5963 			 * and broadcast to anyone waiting for the power
5964 			 * change completion.
5965 			 */
5966 			mutex_enter(SD_MUTEX(un));
5967 			un->un_state = state_before_pm;
5968 			cv_broadcast(&un->un_suspend_cv);
5969 			mutex_exit(SD_MUTEX(un));
5970 			SD_TRACE(SD_LOG_IO_PM, un,
5971 			    "sdpower: exit, Log Sense Failed.\n");
5972 			return (DDI_FAILURE);
5973 		}
5974 
5975 		/*
5976 		 * From the page data - Convert the essential information to
5977 		 * pm_trans_data
5978 		 */
5979 		maxcycles =
5980 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
5981 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
5982 
5983 		sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
5984 
5985 		ncycles =
5986 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
5987 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
5988 
5989 		sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
5990 
5991 		for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
5992 			sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
5993 			    log_page_data[8+i];
5994 		}
5995 
5996 		kmem_free(log_page_data, log_page_size);
5997 
5998 		/*
5999 		 * Call pm_trans_check routine to get the Ok from
6000 		 * the global policy
6001 		 */
6002 
6003 		sd_pm_tran_data.format = DC_SCSI_FORMAT;
6004 		sd_pm_tran_data.un.scsi_cycles.flag = 0;
6005 
6006 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
6007 #ifdef	SDDEBUG
6008 		if (sd_force_pm_supported) {
6009 			/* Force a successful result */
6010 			rval = 1;
6011 		}
6012 #endif
6013 		switch (rval) {
6014 		case 0:
6015 			/*
6016 			 * Not Ok to Power cycle or error in parameters passed
6017 			 * Would have given the advised time to consider power
6018 			 * cycle. Based on the new intvlp parameter we are
6019 			 * supposed to pretend we are busy so that pm framework
6020 			 * will never call our power entry point. Because of
6021 			 * that install a timeout handler and wait for the
6022 			 * recommended time to elapse so that power management
6023 			 * can be effective again.
6024 			 *
6025 			 * To effect this behavior, call pm_busy_component to
6026 			 * indicate to the framework this device is busy.
6027 			 * By not adjusting un_pm_count the rest of PM in
6028 			 * the driver will function normally, and independant
6029 			 * of this but because the framework is told the device
6030 			 * is busy it won't attempt powering down until it gets
6031 			 * a matching idle. The timeout handler sends this.
6032 			 * Note: sd_pm_entry can't be called here to do this
6033 			 * because sdpower may have been called as a result
6034 			 * of a call to pm_raise_power from within sd_pm_entry.
6035 			 *
6036 			 * If a timeout handler is already active then
6037 			 * don't install another.
6038 			 */
6039 			mutex_enter(&un->un_pm_mutex);
6040 			if (un->un_pm_timeid == NULL) {
6041 				un->un_pm_timeid =
6042 				    timeout(sd_pm_timeout_handler,
6043 				    un, intvlp * drv_usectohz(1000000));
6044 				mutex_exit(&un->un_pm_mutex);
6045 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6046 			} else {
6047 				mutex_exit(&un->un_pm_mutex);
6048 			}
6049 			if (got_semaphore_here != 0) {
6050 				sema_v(&un->un_semoclose);
6051 			}
6052 			/*
6053 			 * On exit put the state back to it's original value
6054 			 * and broadcast to anyone waiting for the power
6055 			 * change completion.
6056 			 */
6057 			mutex_enter(SD_MUTEX(un));
6058 			un->un_state = state_before_pm;
6059 			cv_broadcast(&un->un_suspend_cv);
6060 			mutex_exit(SD_MUTEX(un));
6061 
6062 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6063 			    "trans check Failed, not ok to power cycle.\n");
6064 			return (DDI_FAILURE);
6065 
6066 		case -1:
6067 			if (got_semaphore_here != 0) {
6068 				sema_v(&un->un_semoclose);
6069 			}
6070 			/*
6071 			 * On exit put the state back to it's original value
6072 			 * and broadcast to anyone waiting for the power
6073 			 * change completion.
6074 			 */
6075 			mutex_enter(SD_MUTEX(un));
6076 			un->un_state = state_before_pm;
6077 			cv_broadcast(&un->un_suspend_cv);
6078 			mutex_exit(SD_MUTEX(un));
6079 			SD_TRACE(SD_LOG_IO_PM, un,
6080 			    "sdpower: exit, trans check command Failed.\n");
6081 			return (DDI_FAILURE);
6082 		}
6083 	}
6084 
6085 	if (level == SD_SPINDLE_OFF) {
6086 		/*
6087 		 * Save the last state... if the STOP FAILS we need it
6088 		 * for restoring
6089 		 */
6090 		mutex_enter(SD_MUTEX(un));
6091 		save_state = un->un_last_state;
6092 		/*
6093 		 * There must not be any cmds. getting processed
6094 		 * in the driver when we get here. Power to the
6095 		 * device is potentially going off.
6096 		 */
6097 		ASSERT(un->un_ncmds_in_driver == 0);
6098 		mutex_exit(SD_MUTEX(un));
6099 
6100 		/*
6101 		 * For now suspend the device completely before spindle is
6102 		 * turned off
6103 		 */
6104 		if ((rval = sd_ddi_pm_suspend(un)) == DDI_FAILURE) {
6105 			if (got_semaphore_here != 0) {
6106 				sema_v(&un->un_semoclose);
6107 			}
6108 			/*
6109 			 * On exit put the state back to it's original value
6110 			 * and broadcast to anyone waiting for the power
6111 			 * change completion.
6112 			 */
6113 			mutex_enter(SD_MUTEX(un));
6114 			un->un_state = state_before_pm;
6115 			cv_broadcast(&un->un_suspend_cv);
6116 			mutex_exit(SD_MUTEX(un));
6117 			SD_TRACE(SD_LOG_IO_PM, un,
6118 			    "sdpower: exit, PM suspend Failed.\n");
6119 			return (DDI_FAILURE);
6120 		}
6121 	}
6122 
6123 	/*
6124 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6125 	 * close, or strategy. Dump no long uses this routine, it uses it's
6126 	 * own code so it can be done in polled mode.
6127 	 */
6128 
6129 	medium_present = TRUE;
6130 
6131 	/*
6132 	 * When powering up, issue a TUR in case the device is at unit
6133 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6134 	 * a deadlock on un_pm_busy_cv will occur.
6135 	 */
6136 	if (level == SD_SPINDLE_ON) {
6137 		(void) sd_send_scsi_TEST_UNIT_READY(un,
6138 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6139 	}
6140 
6141 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
6142 	    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
6143 
6144 	sval = sd_send_scsi_START_STOP_UNIT(un,
6145 	    ((level == SD_SPINDLE_ON) ? SD_TARGET_START : SD_TARGET_STOP),
6146 	    SD_PATH_DIRECT);
6147 	/* Command failed, check for media present. */
6148 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
6149 		medium_present = FALSE;
6150 	}
6151 
6152 	/*
6153 	 * The conditions of interest here are:
6154 	 *   if a spindle off with media present fails,
6155 	 *	then restore the state and return an error.
6156 	 *   else if a spindle on fails,
6157 	 *	then return an error (there's no state to restore).
6158 	 * In all other cases we setup for the new state
6159 	 * and return success.
6160 	 */
6161 	switch (level) {
6162 	case SD_SPINDLE_OFF:
6163 		if ((medium_present == TRUE) && (sval != 0)) {
6164 			/* The stop command from above failed */
6165 			rval = DDI_FAILURE;
6166 			/*
6167 			 * The stop command failed, and we have media
6168 			 * present. Put the level back by calling the
6169 			 * sd_pm_resume() and set the state back to
6170 			 * it's previous value.
6171 			 */
6172 			(void) sd_ddi_pm_resume(un);
6173 			mutex_enter(SD_MUTEX(un));
6174 			un->un_last_state = save_state;
6175 			mutex_exit(SD_MUTEX(un));
6176 			break;
6177 		}
6178 		/*
6179 		 * The stop command from above succeeded.
6180 		 */
6181 		if (un->un_f_monitor_media_state) {
6182 			/*
6183 			 * Terminate watch thread in case of removable media
6184 			 * devices going into low power state. This is as per
6185 			 * the requirements of pm framework, otherwise commands
6186 			 * will be generated for the device (through watch
6187 			 * thread), even when the device is in low power state.
6188 			 */
6189 			mutex_enter(SD_MUTEX(un));
6190 			un->un_f_watcht_stopped = FALSE;
6191 			if (un->un_swr_token != NULL) {
6192 				opaque_t temp_token = un->un_swr_token;
6193 				un->un_f_watcht_stopped = TRUE;
6194 				un->un_swr_token = NULL;
6195 				mutex_exit(SD_MUTEX(un));
6196 				(void) scsi_watch_request_terminate(temp_token,
6197 				    SCSI_WATCH_TERMINATE_WAIT);
6198 			} else {
6199 				mutex_exit(SD_MUTEX(un));
6200 			}
6201 		}
6202 		break;
6203 
6204 	default:	/* The level requested is spindle on... */
6205 		/*
6206 		 * Legacy behavior: return success on a failed spinup
6207 		 * if there is no media in the drive.
6208 		 * Do this by looking at medium_present here.
6209 		 */
6210 		if ((sval != 0) && medium_present) {
6211 			/* The start command from above failed */
6212 			rval = DDI_FAILURE;
6213 			break;
6214 		}
6215 		/*
6216 		 * The start command from above succeeded
6217 		 * Resume the devices now that we have
6218 		 * started the disks
6219 		 */
6220 		(void) sd_ddi_pm_resume(un);
6221 
6222 		/*
6223 		 * Resume the watch thread since it was suspended
6224 		 * when the device went into low power mode.
6225 		 */
6226 		if (un->un_f_monitor_media_state) {
6227 			mutex_enter(SD_MUTEX(un));
6228 			if (un->un_f_watcht_stopped == TRUE) {
6229 				opaque_t temp_token;
6230 
6231 				un->un_f_watcht_stopped = FALSE;
6232 				mutex_exit(SD_MUTEX(un));
6233 				temp_token = scsi_watch_request_submit(
6234 				    SD_SCSI_DEVP(un),
6235 				    sd_check_media_time,
6236 				    SENSE_LENGTH, sd_media_watch_cb,
6237 				    (caddr_t)dev);
6238 				mutex_enter(SD_MUTEX(un));
6239 				un->un_swr_token = temp_token;
6240 			}
6241 			mutex_exit(SD_MUTEX(un));
6242 		}
6243 	}
6244 	if (got_semaphore_here != 0) {
6245 		sema_v(&un->un_semoclose);
6246 	}
6247 	/*
6248 	 * On exit put the state back to it's original value
6249 	 * and broadcast to anyone waiting for the power
6250 	 * change completion.
6251 	 */
6252 	mutex_enter(SD_MUTEX(un));
6253 	un->un_state = state_before_pm;
6254 	cv_broadcast(&un->un_suspend_cv);
6255 	mutex_exit(SD_MUTEX(un));
6256 
6257 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
6258 
6259 	return (rval);
6260 }
6261 
6262 
6263 
6264 /*
6265  *    Function: sdattach
6266  *
6267  * Description: Driver's attach(9e) entry point function.
6268  *
6269  *   Arguments: devi - opaque device info handle
6270  *		cmd  - attach  type
6271  *
6272  * Return Code: DDI_SUCCESS
6273  *		DDI_FAILURE
6274  *
6275  *     Context: Kernel thread context
6276  */
6277 
6278 static int
6279 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
6280 {
6281 	switch (cmd) {
6282 	case DDI_ATTACH:
6283 		return (sd_unit_attach(devi));
6284 	case DDI_RESUME:
6285 		return (sd_ddi_resume(devi));
6286 	default:
6287 		break;
6288 	}
6289 	return (DDI_FAILURE);
6290 }
6291 
6292 
6293 /*
6294  *    Function: sddetach
6295  *
6296  * Description: Driver's detach(9E) entry point function.
6297  *
6298  *   Arguments: devi - opaque device info handle
6299  *		cmd  - detach  type
6300  *
6301  * Return Code: DDI_SUCCESS
6302  *		DDI_FAILURE
6303  *
6304  *     Context: Kernel thread context
6305  */
6306 
6307 static int
6308 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
6309 {
6310 	switch (cmd) {
6311 	case DDI_DETACH:
6312 		return (sd_unit_detach(devi));
6313 	case DDI_SUSPEND:
6314 		return (sd_ddi_suspend(devi));
6315 	default:
6316 		break;
6317 	}
6318 	return (DDI_FAILURE);
6319 }
6320 
6321 
6322 /*
6323  *     Function: sd_sync_with_callback
6324  *
6325  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
6326  *		 state while the callback routine is active.
6327  *
6328  *    Arguments: un: softstate structure for the instance
6329  *
6330  *	Context: Kernel thread context
6331  */
6332 
6333 static void
6334 sd_sync_with_callback(struct sd_lun *un)
6335 {
6336 	ASSERT(un != NULL);
6337 
6338 	mutex_enter(SD_MUTEX(un));
6339 
6340 	ASSERT(un->un_in_callback >= 0);
6341 
6342 	while (un->un_in_callback > 0) {
6343 		mutex_exit(SD_MUTEX(un));
6344 		delay(2);
6345 		mutex_enter(SD_MUTEX(un));
6346 	}
6347 
6348 	mutex_exit(SD_MUTEX(un));
6349 }
6350 
6351 /*
6352  *    Function: sd_unit_attach
6353  *
6354  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
6355  *		the soft state structure for the device and performs
6356  *		all necessary structure and device initializations.
6357  *
6358  *   Arguments: devi: the system's dev_info_t for the device.
6359  *
6360  * Return Code: DDI_SUCCESS if attach is successful.
6361  *		DDI_FAILURE if any part of the attach fails.
6362  *
6363  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
6364  *		Kernel thread context only.  Can sleep.
6365  */
6366 
6367 static int
6368 sd_unit_attach(dev_info_t *devi)
6369 {
6370 	struct	scsi_device	*devp;
6371 	struct	sd_lun		*un;
6372 	char			*variantp;
6373 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
6374 	int	instance;
6375 	int	rval;
6376 	int	wc_enabled;
6377 	int	tgt;
6378 	uint64_t	capacity;
6379 	uint_t		lbasize = 0;
6380 	dev_info_t	*pdip = ddi_get_parent(devi);
6381 	int		offbyone = 0;
6382 	int		geom_label_valid = 0;
6383 
6384 	/*
6385 	 * Retrieve the target driver's private data area. This was set
6386 	 * up by the HBA.
6387 	 */
6388 	devp = ddi_get_driver_private(devi);
6389 
6390 	/*
6391 	 * Retrieve the target ID of the device.
6392 	 */
6393 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
6394 	    SCSI_ADDR_PROP_TARGET, -1);
6395 
6396 	/*
6397 	 * Since we have no idea what state things were left in by the last
6398 	 * user of the device, set up some 'default' settings, ie. turn 'em
6399 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
6400 	 * Do this before the scsi_probe, which sends an inquiry.
6401 	 * This is a fix for bug (4430280).
6402 	 * Of special importance is wide-xfer. The drive could have been left
6403 	 * in wide transfer mode by the last driver to communicate with it,
6404 	 * this includes us. If that's the case, and if the following is not
6405 	 * setup properly or we don't re-negotiate with the drive prior to
6406 	 * transferring data to/from the drive, it causes bus parity errors,
6407 	 * data overruns, and unexpected interrupts. This first occurred when
6408 	 * the fix for bug (4378686) was made.
6409 	 */
6410 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
6411 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
6412 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
6413 
6414 	/*
6415 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
6416 	 * on a target. Setting it per lun instance actually sets the
6417 	 * capability of this target, which affects those luns already
6418 	 * attached on the same target. So during attach, we can only disable
6419 	 * this capability only when no other lun has been attached on this
6420 	 * target. By doing this, we assume a target has the same tagged-qing
6421 	 * capability for every lun. The condition can be removed when HBA
6422 	 * is changed to support per lun based tagged-qing capability.
6423 	 */
6424 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
6425 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
6426 	}
6427 
6428 	/*
6429 	 * Use scsi_probe() to issue an INQUIRY command to the device.
6430 	 * This call will allocate and fill in the scsi_inquiry structure
6431 	 * and point the sd_inq member of the scsi_device structure to it.
6432 	 * If the attach succeeds, then this memory will not be de-allocated
6433 	 * (via scsi_unprobe()) until the instance is detached.
6434 	 */
6435 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
6436 		goto probe_failed;
6437 	}
6438 
6439 	/*
6440 	 * Check the device type as specified in the inquiry data and
6441 	 * claim it if it is of a type that we support.
6442 	 */
6443 	switch (devp->sd_inq->inq_dtype) {
6444 	case DTYPE_DIRECT:
6445 		break;
6446 	case DTYPE_RODIRECT:
6447 		break;
6448 	case DTYPE_OPTICAL:
6449 		break;
6450 	case DTYPE_NOTPRESENT:
6451 	default:
6452 		/* Unsupported device type; fail the attach. */
6453 		goto probe_failed;
6454 	}
6455 
6456 	/*
6457 	 * Allocate the soft state structure for this unit.
6458 	 *
6459 	 * We rely upon this memory being set to all zeroes by
6460 	 * ddi_soft_state_zalloc().  We assume that any member of the
6461 	 * soft state structure that is not explicitly initialized by
6462 	 * this routine will have a value of zero.
6463 	 */
6464 	instance = ddi_get_instance(devp->sd_dev);
6465 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
6466 		goto probe_failed;
6467 	}
6468 
6469 	/*
6470 	 * Retrieve a pointer to the newly-allocated soft state.
6471 	 *
6472 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
6473 	 * was successful, unless something has gone horribly wrong and the
6474 	 * ddi's soft state internals are corrupt (in which case it is
6475 	 * probably better to halt here than just fail the attach....)
6476 	 */
6477 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
6478 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
6479 		    instance);
6480 		/*NOTREACHED*/
6481 	}
6482 
6483 	/*
6484 	 * Link the back ptr of the driver soft state to the scsi_device
6485 	 * struct for this lun.
6486 	 * Save a pointer to the softstate in the driver-private area of
6487 	 * the scsi_device struct.
6488 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
6489 	 * we first set un->un_sd below.
6490 	 */
6491 	un->un_sd = devp;
6492 	devp->sd_private = (opaque_t)un;
6493 
6494 	/*
6495 	 * The following must be after devp is stored in the soft state struct.
6496 	 */
6497 #ifdef SDDEBUG
6498 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6499 	    "%s_unit_attach: un:0x%p instance:%d\n",
6500 	    ddi_driver_name(devi), un, instance);
6501 #endif
6502 
6503 	/*
6504 	 * Set up the device type and node type (for the minor nodes).
6505 	 * By default we assume that the device can at least support the
6506 	 * Common Command Set. Call it a CD-ROM if it reports itself
6507 	 * as a RODIRECT device.
6508 	 */
6509 	switch (devp->sd_inq->inq_dtype) {
6510 	case DTYPE_RODIRECT:
6511 		un->un_node_type = DDI_NT_CD_CHAN;
6512 		un->un_ctype	 = CTYPE_CDROM;
6513 		break;
6514 	case DTYPE_OPTICAL:
6515 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6516 		un->un_ctype	 = CTYPE_ROD;
6517 		break;
6518 	default:
6519 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6520 		un->un_ctype	 = CTYPE_CCS;
6521 		break;
6522 	}
6523 
6524 	/*
6525 	 * Try to read the interconnect type from the HBA.
6526 	 *
6527 	 * Note: This driver is currently compiled as two binaries, a parallel
6528 	 * scsi version (sd) and a fibre channel version (ssd). All functional
6529 	 * differences are determined at compile time. In the future a single
6530 	 * binary will be provided and the inteconnect type will be used to
6531 	 * differentiate between fibre and parallel scsi behaviors. At that time
6532 	 * it will be necessary for all fibre channel HBAs to support this
6533 	 * property.
6534 	 *
6535 	 * set un_f_is_fiber to TRUE ( default fiber )
6536 	 */
6537 	un->un_f_is_fibre = TRUE;
6538 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
6539 	case INTERCONNECT_SSA:
6540 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
6541 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6542 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
6543 		break;
6544 	case INTERCONNECT_PARALLEL:
6545 		un->un_f_is_fibre = FALSE;
6546 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
6547 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6548 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
6549 		break;
6550 	case INTERCONNECT_SATA:
6551 		un->un_f_is_fibre = FALSE;
6552 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
6553 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6554 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
6555 		break;
6556 	case INTERCONNECT_FIBRE:
6557 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
6558 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6559 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
6560 		break;
6561 	case INTERCONNECT_FABRIC:
6562 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
6563 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
6564 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6565 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
6566 		break;
6567 	default:
6568 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
6569 		/*
6570 		 * The HBA does not support the "interconnect-type" property
6571 		 * (or did not provide a recognized type).
6572 		 *
6573 		 * Note: This will be obsoleted when a single fibre channel
6574 		 * and parallel scsi driver is delivered. In the meantime the
6575 		 * interconnect type will be set to the platform default.If that
6576 		 * type is not parallel SCSI, it means that we should be
6577 		 * assuming "ssd" semantics. However, here this also means that
6578 		 * the FC HBA is not supporting the "interconnect-type" property
6579 		 * like we expect it to, so log this occurrence.
6580 		 */
6581 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
6582 		if (!SD_IS_PARALLEL_SCSI(un)) {
6583 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6584 			    "sd_unit_attach: un:0x%p Assuming "
6585 			    "INTERCONNECT_FIBRE\n", un);
6586 		} else {
6587 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6588 			    "sd_unit_attach: un:0x%p Assuming "
6589 			    "INTERCONNECT_PARALLEL\n", un);
6590 			un->un_f_is_fibre = FALSE;
6591 		}
6592 #else
6593 		/*
6594 		 * Note: This source will be implemented when a single fibre
6595 		 * channel and parallel scsi driver is delivered. The default
6596 		 * will be to assume that if a device does not support the
6597 		 * "interconnect-type" property it is a parallel SCSI HBA and
6598 		 * we will set the interconnect type for parallel scsi.
6599 		 */
6600 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
6601 		un->un_f_is_fibre = FALSE;
6602 #endif
6603 		break;
6604 	}
6605 
6606 	if (un->un_f_is_fibre == TRUE) {
6607 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
6608 		    SCSI_VERSION_3) {
6609 			switch (un->un_interconnect_type) {
6610 			case SD_INTERCONNECT_FIBRE:
6611 			case SD_INTERCONNECT_SSA:
6612 				un->un_node_type = DDI_NT_BLOCK_WWN;
6613 				break;
6614 			default:
6615 				break;
6616 			}
6617 		}
6618 	}
6619 
6620 	/*
6621 	 * Initialize the Request Sense command for the target
6622 	 */
6623 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
6624 		goto alloc_rqs_failed;
6625 	}
6626 
6627 	/*
6628 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
6629 	 * with separate binary for sd and ssd.
6630 	 *
6631 	 * x86 has 1 binary, un_retry_count is set base on connection type.
6632 	 * The hardcoded values will go away when Sparc uses 1 binary
6633 	 * for sd and ssd.  This hardcoded values need to match
6634 	 * SD_RETRY_COUNT in sddef.h
6635 	 * The value used is base on interconnect type.
6636 	 * fibre = 3, parallel = 5
6637 	 */
6638 #if defined(__i386) || defined(__amd64)
6639 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
6640 #else
6641 	un->un_retry_count = SD_RETRY_COUNT;
6642 #endif
6643 
6644 	/*
6645 	 * Set the per disk retry count to the default number of retries
6646 	 * for disks and CDROMs. This value can be overridden by the
6647 	 * disk property list or an entry in sd.conf.
6648 	 */
6649 	un->un_notready_retry_count =
6650 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
6651 	    : DISK_NOT_READY_RETRY_COUNT(un);
6652 
6653 	/*
6654 	 * Set the busy retry count to the default value of un_retry_count.
6655 	 * This can be overridden by entries in sd.conf or the device
6656 	 * config table.
6657 	 */
6658 	un->un_busy_retry_count = un->un_retry_count;
6659 
6660 	/*
6661 	 * Init the reset threshold for retries.  This number determines
6662 	 * how many retries must be performed before a reset can be issued
6663 	 * (for certain error conditions). This can be overridden by entries
6664 	 * in sd.conf or the device config table.
6665 	 */
6666 	un->un_reset_retry_count = (un->un_retry_count / 2);
6667 
6668 	/*
6669 	 * Set the victim_retry_count to the default un_retry_count
6670 	 */
6671 	un->un_victim_retry_count = (2 * un->un_retry_count);
6672 
6673 	/*
6674 	 * Set the reservation release timeout to the default value of
6675 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
6676 	 * device config table.
6677 	 */
6678 	un->un_reserve_release_time = 5;
6679 
6680 	/*
6681 	 * Set up the default maximum transfer size. Note that this may
6682 	 * get updated later in the attach, when setting up default wide
6683 	 * operations for disks.
6684 	 */
6685 #if defined(__i386) || defined(__amd64)
6686 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
6687 #else
6688 	un->un_max_xfer_size = (uint_t)maxphys;
6689 #endif
6690 
6691 	/*
6692 	 * Get "allow bus device reset" property (defaults to "enabled" if
6693 	 * the property was not defined). This is to disable bus resets for
6694 	 * certain kinds of error recovery. Note: In the future when a run-time
6695 	 * fibre check is available the soft state flag should default to
6696 	 * enabled.
6697 	 */
6698 	if (un->un_f_is_fibre == TRUE) {
6699 		un->un_f_allow_bus_device_reset = TRUE;
6700 	} else {
6701 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
6702 		    "allow-bus-device-reset", 1) != 0) {
6703 			un->un_f_allow_bus_device_reset = TRUE;
6704 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6705 			    "sd_unit_attach: un:0x%p Bus device reset "
6706 			    "enabled\n", un);
6707 		} else {
6708 			un->un_f_allow_bus_device_reset = FALSE;
6709 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6710 			    "sd_unit_attach: un:0x%p Bus device reset "
6711 			    "disabled\n", un);
6712 		}
6713 	}
6714 
6715 	/*
6716 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
6717 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
6718 	 *
6719 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
6720 	 * property. The new "variant" property with a value of "atapi" has been
6721 	 * introduced so that future 'variants' of standard SCSI behavior (like
6722 	 * atapi) could be specified by the underlying HBA drivers by supplying
6723 	 * a new value for the "variant" property, instead of having to define a
6724 	 * new property.
6725 	 */
6726 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
6727 		un->un_f_cfg_is_atapi = TRUE;
6728 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6729 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
6730 	}
6731 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
6732 	    &variantp) == DDI_PROP_SUCCESS) {
6733 		if (strcmp(variantp, "atapi") == 0) {
6734 			un->un_f_cfg_is_atapi = TRUE;
6735 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6736 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
6737 		}
6738 		ddi_prop_free(variantp);
6739 	}
6740 
6741 	un->un_cmd_timeout	= SD_IO_TIME;
6742 
6743 	/* Info on current states, statuses, etc. (Updated frequently) */
6744 	un->un_state		= SD_STATE_NORMAL;
6745 	un->un_last_state	= SD_STATE_NORMAL;
6746 
6747 	/* Control & status info for command throttling */
6748 	un->un_throttle		= sd_max_throttle;
6749 	un->un_saved_throttle	= sd_max_throttle;
6750 	un->un_min_throttle	= sd_min_throttle;
6751 
6752 	if (un->un_f_is_fibre == TRUE) {
6753 		un->un_f_use_adaptive_throttle = TRUE;
6754 	} else {
6755 		un->un_f_use_adaptive_throttle = FALSE;
6756 	}
6757 
6758 	/* Removable media support. */
6759 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
6760 	un->un_mediastate		= DKIO_NONE;
6761 	un->un_specified_mediastate	= DKIO_NONE;
6762 
6763 	/* CVs for suspend/resume (PM or DR) */
6764 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
6765 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
6766 
6767 	/* Power management support. */
6768 	un->un_power_level = SD_SPINDLE_UNINIT;
6769 
6770 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
6771 	un->un_f_wcc_inprog = 0;
6772 
6773 	/*
6774 	 * The open/close semaphore is used to serialize threads executing
6775 	 * in the driver's open & close entry point routines for a given
6776 	 * instance.
6777 	 */
6778 	(void) sema_init(&un->un_semoclose, 1, NULL, SEMA_DRIVER, NULL);
6779 
6780 	/*
6781 	 * The conf file entry and softstate variable is a forceful override,
6782 	 * meaning a non-zero value must be entered to change the default.
6783 	 */
6784 	un->un_f_disksort_disabled = FALSE;
6785 
6786 	/*
6787 	 * Retrieve the properties from the static driver table or the driver
6788 	 * configuration file (.conf) for this unit and update the soft state
6789 	 * for the device as needed for the indicated properties.
6790 	 * Note: the property configuration needs to occur here as some of the
6791 	 * following routines may have dependancies on soft state flags set
6792 	 * as part of the driver property configuration.
6793 	 */
6794 	sd_read_unit_properties(un);
6795 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6796 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
6797 
6798 	/*
6799 	 * Only if a device has "hotpluggable" property, it is
6800 	 * treated as hotpluggable device. Otherwise, it is
6801 	 * regarded as non-hotpluggable one.
6802 	 */
6803 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
6804 	    -1) != -1) {
6805 		un->un_f_is_hotpluggable = TRUE;
6806 	}
6807 
6808 	/*
6809 	 * set unit's attributes(flags) according to "hotpluggable" and
6810 	 * RMB bit in INQUIRY data.
6811 	 */
6812 	sd_set_unit_attributes(un, devi);
6813 
6814 	/*
6815 	 * By default, we mark the capacity, lbasize, and geometry
6816 	 * as invalid. Only if we successfully read a valid capacity
6817 	 * will we update the un_blockcount and un_tgt_blocksize with the
6818 	 * valid values (the geometry will be validated later).
6819 	 */
6820 	un->un_f_blockcount_is_valid	= FALSE;
6821 	un->un_f_tgt_blocksize_is_valid	= FALSE;
6822 
6823 	/*
6824 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
6825 	 * otherwise.
6826 	 */
6827 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
6828 	un->un_blockcount = 0;
6829 
6830 	/*
6831 	 * Set up the per-instance info needed to determine the correct
6832 	 * CDBs and other info for issuing commands to the target.
6833 	 */
6834 	sd_init_cdb_limits(un);
6835 
6836 	/*
6837 	 * Set up the IO chains to use, based upon the target type.
6838 	 */
6839 	if (un->un_f_non_devbsize_supported) {
6840 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
6841 	} else {
6842 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
6843 	}
6844 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
6845 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
6846 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
6847 
6848 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
6849 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
6850 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
6851 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
6852 
6853 
6854 	if (ISCD(un)) {
6855 		un->un_additional_codes = sd_additional_codes;
6856 	} else {
6857 		un->un_additional_codes = NULL;
6858 	}
6859 
6860 	/*
6861 	 * Create the kstats here so they can be available for attach-time
6862 	 * routines that send commands to the unit (either polled or via
6863 	 * sd_send_scsi_cmd).
6864 	 *
6865 	 * Note: This is a critical sequence that needs to be maintained:
6866 	 *	1) Instantiate the kstats here, before any routines using the
6867 	 *	   iopath (i.e. sd_send_scsi_cmd).
6868 	 *	2) Instantiate and initialize the partition stats
6869 	 *	   (sd_set_pstats).
6870 	 *	3) Initialize the error stats (sd_set_errstats), following
6871 	 *	   sd_validate_geometry(),sd_register_devid(),
6872 	 *	   and sd_cache_control().
6873 	 */
6874 
6875 	un->un_stats = kstat_create(sd_label, instance,
6876 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
6877 	if (un->un_stats != NULL) {
6878 		un->un_stats->ks_lock = SD_MUTEX(un);
6879 		kstat_install(un->un_stats);
6880 	}
6881 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6882 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
6883 
6884 	sd_create_errstats(un, instance);
6885 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6886 	    "sd_unit_attach: un:0x%p errstats created\n", un);
6887 
6888 	/*
6889 	 * The following if/else code was relocated here from below as part
6890 	 * of the fix for bug (4430280). However with the default setup added
6891 	 * on entry to this routine, it's no longer absolutely necessary for
6892 	 * this to be before the call to sd_spin_up_unit.
6893 	 */
6894 	if (SD_IS_PARALLEL_SCSI(un) || SD_IS_SERIAL(un)) {
6895 		/*
6896 		 * If SCSI-2 tagged queueing is supported by the target
6897 		 * and by the host adapter then we will enable it.
6898 		 */
6899 		un->un_tagflags = 0;
6900 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
6901 		    (devp->sd_inq->inq_cmdque) &&
6902 		    (un->un_f_arq_enabled == TRUE)) {
6903 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
6904 			    1, 1) == 1) {
6905 				un->un_tagflags = FLAG_STAG;
6906 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6907 				    "sd_unit_attach: un:0x%p tag queueing "
6908 				    "enabled\n", un);
6909 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
6910 			    "untagged-qing", 0) == 1) {
6911 				un->un_f_opt_queueing = TRUE;
6912 				un->un_saved_throttle = un->un_throttle =
6913 				    min(un->un_throttle, 3);
6914 			} else {
6915 				un->un_f_opt_queueing = FALSE;
6916 				un->un_saved_throttle = un->un_throttle = 1;
6917 			}
6918 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
6919 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
6920 			/* The Host Adapter supports internal queueing. */
6921 			un->un_f_opt_queueing = TRUE;
6922 			un->un_saved_throttle = un->un_throttle =
6923 			    min(un->un_throttle, 3);
6924 		} else {
6925 			un->un_f_opt_queueing = FALSE;
6926 			un->un_saved_throttle = un->un_throttle = 1;
6927 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6928 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
6929 		}
6930 
6931 		/*
6932 		 * Enable large transfers for SATA/SAS drives
6933 		 */
6934 		if (SD_IS_SERIAL(un)) {
6935 			un->un_max_xfer_size =
6936 			    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
6937 			    sd_max_xfer_size, SD_MAX_XFER_SIZE);
6938 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6939 			    "sd_unit_attach: un:0x%p max transfer "
6940 			    "size=0x%x\n", un, un->un_max_xfer_size);
6941 
6942 		}
6943 
6944 		/* Setup or tear down default wide operations for disks */
6945 
6946 		/*
6947 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
6948 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
6949 		 * system and be set to different values. In the future this
6950 		 * code may need to be updated when the ssd module is
6951 		 * obsoleted and removed from the system. (4299588)
6952 		 */
6953 		if (SD_IS_PARALLEL_SCSI(un) &&
6954 		    (devp->sd_inq->inq_rdf == RDF_SCSI2) &&
6955 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
6956 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
6957 			    1, 1) == 1) {
6958 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6959 				    "sd_unit_attach: un:0x%p Wide Transfer "
6960 				    "enabled\n", un);
6961 			}
6962 
6963 			/*
6964 			 * If tagged queuing has also been enabled, then
6965 			 * enable large xfers
6966 			 */
6967 			if (un->un_saved_throttle == sd_max_throttle) {
6968 				un->un_max_xfer_size =
6969 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
6970 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
6971 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6972 				    "sd_unit_attach: un:0x%p max transfer "
6973 				    "size=0x%x\n", un, un->un_max_xfer_size);
6974 			}
6975 		} else {
6976 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
6977 			    0, 1) == 1) {
6978 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6979 				    "sd_unit_attach: un:0x%p "
6980 				    "Wide Transfer disabled\n", un);
6981 			}
6982 		}
6983 	} else {
6984 		un->un_tagflags = FLAG_STAG;
6985 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
6986 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
6987 	}
6988 
6989 	/*
6990 	 * If this target supports LUN reset, try to enable it.
6991 	 */
6992 	if (un->un_f_lun_reset_enabled) {
6993 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
6994 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
6995 			    "un:0x%p lun_reset capability set\n", un);
6996 		} else {
6997 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
6998 			    "un:0x%p lun-reset capability not set\n", un);
6999 		}
7000 	}
7001 
7002 	/*
7003 	 * At this point in the attach, we have enough info in the
7004 	 * soft state to be able to issue commands to the target.
7005 	 *
7006 	 * All command paths used below MUST issue their commands as
7007 	 * SD_PATH_DIRECT. This is important as intermediate layers
7008 	 * are not all initialized yet (such as PM).
7009 	 */
7010 
7011 	/*
7012 	 * Send a TEST UNIT READY command to the device. This should clear
7013 	 * any outstanding UNIT ATTENTION that may be present.
7014 	 *
7015 	 * Note: Don't check for success, just track if there is a reservation,
7016 	 * this is a throw away command to clear any unit attentions.
7017 	 *
7018 	 * Note: This MUST be the first command issued to the target during
7019 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
7020 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
7021 	 * with attempts at spinning up a device with no media.
7022 	 */
7023 	if (sd_send_scsi_TEST_UNIT_READY(un, SD_DONT_RETRY_TUR) == EACCES) {
7024 		reservation_flag = SD_TARGET_IS_RESERVED;
7025 	}
7026 
7027 	/*
7028 	 * If the device is NOT a removable media device, attempt to spin
7029 	 * it up (using the START_STOP_UNIT command) and read its capacity
7030 	 * (using the READ CAPACITY command).  Note, however, that either
7031 	 * of these could fail and in some cases we would continue with
7032 	 * the attach despite the failure (see below).
7033 	 */
7034 	if (un->un_f_descr_format_supported) {
7035 		switch (sd_spin_up_unit(un)) {
7036 		case 0:
7037 			/*
7038 			 * Spin-up was successful; now try to read the
7039 			 * capacity.  If successful then save the results
7040 			 * and mark the capacity & lbasize as valid.
7041 			 */
7042 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7043 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
7044 
7045 			switch (sd_send_scsi_READ_CAPACITY(un, &capacity,
7046 			    &lbasize, SD_PATH_DIRECT)) {
7047 			case 0: {
7048 				if (capacity > DK_MAX_BLOCKS) {
7049 #ifdef _LP64
7050 					if (capacity + 1 >
7051 					    SD_GROUP1_MAX_ADDRESS) {
7052 						/*
7053 						 * Enable descriptor format
7054 						 * sense data so that we can
7055 						 * get 64 bit sense data
7056 						 * fields.
7057 						 */
7058 						sd_enable_descr_sense(un);
7059 					}
7060 #else
7061 					/* 32-bit kernels can't handle this */
7062 					scsi_log(SD_DEVINFO(un),
7063 					    sd_label, CE_WARN,
7064 					    "disk has %llu blocks, which "
7065 					    "is too large for a 32-bit "
7066 					    "kernel", capacity);
7067 
7068 #if defined(__i386) || defined(__amd64)
7069 					/*
7070 					 * 1TB disk was treated as (1T - 512)B
7071 					 * in the past, so that it might have
7072 					 * valid VTOC and solaris partitions,
7073 					 * we have to allow it to continue to
7074 					 * work.
7075 					 */
7076 					if (capacity -1 > DK_MAX_BLOCKS)
7077 #endif
7078 					goto spinup_failed;
7079 #endif
7080 				}
7081 
7082 				/*
7083 				 * Here it's not necessary to check the case:
7084 				 * the capacity of the device is bigger than
7085 				 * what the max hba cdb can support. Because
7086 				 * sd_send_scsi_READ_CAPACITY will retrieve
7087 				 * the capacity by sending USCSI command, which
7088 				 * is constrained by the max hba cdb. Actually,
7089 				 * sd_send_scsi_READ_CAPACITY will return
7090 				 * EINVAL when using bigger cdb than required
7091 				 * cdb length. Will handle this case in
7092 				 * "case EINVAL".
7093 				 */
7094 
7095 				/*
7096 				 * The following relies on
7097 				 * sd_send_scsi_READ_CAPACITY never
7098 				 * returning 0 for capacity and/or lbasize.
7099 				 */
7100 				sd_update_block_info(un, lbasize, capacity);
7101 
7102 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7103 				    "sd_unit_attach: un:0x%p capacity = %ld "
7104 				    "blocks; lbasize= %ld.\n", un,
7105 				    un->un_blockcount, un->un_tgt_blocksize);
7106 
7107 				break;
7108 			}
7109 			case EINVAL:
7110 				/*
7111 				 * In the case where the max-cdb-length property
7112 				 * is smaller than the required CDB length for
7113 				 * a SCSI device, a target driver can fail to
7114 				 * attach to that device.
7115 				 */
7116 				scsi_log(SD_DEVINFO(un),
7117 				    sd_label, CE_WARN,
7118 				    "disk capacity is too large "
7119 				    "for current cdb length");
7120 				goto spinup_failed;
7121 			case EACCES:
7122 				/*
7123 				 * Should never get here if the spin-up
7124 				 * succeeded, but code it in anyway.
7125 				 * From here, just continue with the attach...
7126 				 */
7127 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7128 				    "sd_unit_attach: un:0x%p "
7129 				    "sd_send_scsi_READ_CAPACITY "
7130 				    "returned reservation conflict\n", un);
7131 				reservation_flag = SD_TARGET_IS_RESERVED;
7132 				break;
7133 			default:
7134 				/*
7135 				 * Likewise, should never get here if the
7136 				 * spin-up succeeded. Just continue with
7137 				 * the attach...
7138 				 */
7139 				break;
7140 			}
7141 			break;
7142 		case EACCES:
7143 			/*
7144 			 * Device is reserved by another host.  In this case
7145 			 * we could not spin it up or read the capacity, but
7146 			 * we continue with the attach anyway.
7147 			 */
7148 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7149 			    "sd_unit_attach: un:0x%p spin-up reservation "
7150 			    "conflict.\n", un);
7151 			reservation_flag = SD_TARGET_IS_RESERVED;
7152 			break;
7153 		default:
7154 			/* Fail the attach if the spin-up failed. */
7155 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7156 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
7157 			goto spinup_failed;
7158 		}
7159 	}
7160 
7161 	/*
7162 	 * Check to see if this is a MMC drive
7163 	 */
7164 	if (ISCD(un)) {
7165 		sd_set_mmc_caps(un);
7166 	}
7167 
7168 
7169 	/*
7170 	 * Add a zero-length attribute to tell the world we support
7171 	 * kernel ioctls (for layered drivers)
7172 	 */
7173 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7174 	    DDI_KERNEL_IOCTL, NULL, 0);
7175 
7176 	/*
7177 	 * Add a boolean property to tell the world we support
7178 	 * the B_FAILFAST flag (for layered drivers)
7179 	 */
7180 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7181 	    "ddi-failfast-supported", NULL, 0);
7182 
7183 	/*
7184 	 * Initialize power management
7185 	 */
7186 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
7187 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
7188 	sd_setup_pm(un, devi);
7189 	if (un->un_f_pm_is_enabled == FALSE) {
7190 		/*
7191 		 * For performance, point to a jump table that does
7192 		 * not include pm.
7193 		 * The direct and priority chains don't change with PM.
7194 		 *
7195 		 * Note: this is currently done based on individual device
7196 		 * capabilities. When an interface for determining system
7197 		 * power enabled state becomes available, or when additional
7198 		 * layers are added to the command chain, these values will
7199 		 * have to be re-evaluated for correctness.
7200 		 */
7201 		if (un->un_f_non_devbsize_supported) {
7202 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
7203 		} else {
7204 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
7205 		}
7206 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
7207 	}
7208 
7209 	/*
7210 	 * This property is set to 0 by HA software to avoid retries
7211 	 * on a reserved disk. (The preferred property name is
7212 	 * "retry-on-reservation-conflict") (1189689)
7213 	 *
7214 	 * Note: The use of a global here can have unintended consequences. A
7215 	 * per instance variable is preferrable to match the capabilities of
7216 	 * different underlying hba's (4402600)
7217 	 */
7218 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
7219 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
7220 	    sd_retry_on_reservation_conflict);
7221 	if (sd_retry_on_reservation_conflict != 0) {
7222 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
7223 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
7224 		    sd_retry_on_reservation_conflict);
7225 	}
7226 
7227 	/* Set up options for QFULL handling. */
7228 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7229 	    "qfull-retries", -1)) != -1) {
7230 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
7231 		    rval, 1);
7232 	}
7233 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7234 	    "qfull-retry-interval", -1)) != -1) {
7235 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
7236 		    rval, 1);
7237 	}
7238 
7239 	/*
7240 	 * This just prints a message that announces the existence of the
7241 	 * device. The message is always printed in the system logfile, but
7242 	 * only appears on the console if the system is booted with the
7243 	 * -v (verbose) argument.
7244 	 */
7245 	ddi_report_dev(devi);
7246 
7247 	un->un_mediastate = DKIO_NONE;
7248 
7249 	cmlb_alloc_handle(&un->un_cmlbhandle);
7250 
7251 #if defined(__i386) || defined(__amd64)
7252 	/*
7253 	 * On x86, compensate for off-by-1 legacy error
7254 	 */
7255 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
7256 	    (lbasize == un->un_sys_blocksize))
7257 		offbyone = CMLB_OFF_BY_ONE;
7258 #endif
7259 
7260 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
7261 	    un->un_f_has_removable_media, un->un_f_is_hotpluggable,
7262 	    un->un_node_type, offbyone, un->un_cmlbhandle,
7263 	    (void *)SD_PATH_DIRECT) != 0) {
7264 		goto cmlb_attach_failed;
7265 	}
7266 
7267 
7268 	/*
7269 	 * Read and validate the device's geometry (ie, disk label)
7270 	 * A new unformatted drive will not have a valid geometry, but
7271 	 * the driver needs to successfully attach to this device so
7272 	 * the drive can be formatted via ioctls.
7273 	 */
7274 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
7275 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
7276 
7277 	mutex_enter(SD_MUTEX(un));
7278 
7279 	/*
7280 	 * Read and initialize the devid for the unit.
7281 	 */
7282 	ASSERT(un->un_errstats != NULL);
7283 	if (un->un_f_devid_supported) {
7284 		sd_register_devid(un, devi, reservation_flag);
7285 	}
7286 	mutex_exit(SD_MUTEX(un));
7287 
7288 #if (defined(__fibre))
7289 	/*
7290 	 * Register callbacks for fibre only.  You can't do this soley
7291 	 * on the basis of the devid_type because this is hba specific.
7292 	 * We need to query our hba capabilities to find out whether to
7293 	 * register or not.
7294 	 */
7295 	if (un->un_f_is_fibre) {
7296 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
7297 			sd_init_event_callbacks(un);
7298 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7299 			    "sd_unit_attach: un:0x%p event callbacks inserted",
7300 			    un);
7301 		}
7302 	}
7303 #endif
7304 
7305 	if (un->un_f_opt_disable_cache == TRUE) {
7306 		/*
7307 		 * Disable both read cache and write cache.  This is
7308 		 * the historic behavior of the keywords in the config file.
7309 		 */
7310 		if (sd_cache_control(un, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
7311 		    0) {
7312 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7313 			    "sd_unit_attach: un:0x%p Could not disable "
7314 			    "caching", un);
7315 			goto devid_failed;
7316 		}
7317 	}
7318 
7319 	/*
7320 	 * Check the value of the WCE bit now and
7321 	 * set un_f_write_cache_enabled accordingly.
7322 	 */
7323 	(void) sd_get_write_cache_enabled(un, &wc_enabled);
7324 	mutex_enter(SD_MUTEX(un));
7325 	un->un_f_write_cache_enabled = (wc_enabled != 0);
7326 	mutex_exit(SD_MUTEX(un));
7327 
7328 	/*
7329 	 * Check the value of the NV_SUP bit and set
7330 	 * un_f_suppress_cache_flush accordingly.
7331 	 */
7332 	sd_get_nv_sup(un);
7333 
7334 	/*
7335 	 * Find out what type of reservation this disk supports.
7336 	 */
7337 	switch (sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS, 0, NULL)) {
7338 	case 0:
7339 		/*
7340 		 * SCSI-3 reservations are supported.
7341 		 */
7342 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7343 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7344 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
7345 		break;
7346 	case ENOTSUP:
7347 		/*
7348 		 * The PERSISTENT RESERVE IN command would not be recognized by
7349 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
7350 		 */
7351 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7352 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
7353 		un->un_reservation_type = SD_SCSI2_RESERVATION;
7354 		break;
7355 	default:
7356 		/*
7357 		 * default to SCSI-3 reservations
7358 		 */
7359 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7360 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
7361 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7362 		break;
7363 	}
7364 
7365 	/*
7366 	 * Set the pstat and error stat values here, so data obtained during the
7367 	 * previous attach-time routines is available.
7368 	 *
7369 	 * Note: This is a critical sequence that needs to be maintained:
7370 	 *	1) Instantiate the kstats before any routines using the iopath
7371 	 *	   (i.e. sd_send_scsi_cmd).
7372 	 *	2) Initialize the error stats (sd_set_errstats) and partition
7373 	 *	   stats (sd_set_pstats)here, following
7374 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
7375 	 *	   sd_cache_control().
7376 	 */
7377 
7378 	if (un->un_f_pkstats_enabled && geom_label_valid) {
7379 		sd_set_pstats(un);
7380 		SD_TRACE(SD_LOG_IO_PARTITION, un,
7381 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
7382 	}
7383 
7384 	sd_set_errstats(un);
7385 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7386 	    "sd_unit_attach: un:0x%p errstats set\n", un);
7387 
7388 
7389 	/*
7390 	 * After successfully attaching an instance, we record the information
7391 	 * of how many luns have been attached on the relative target and
7392 	 * controller for parallel SCSI. This information is used when sd tries
7393 	 * to set the tagged queuing capability in HBA.
7394 	 */
7395 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
7396 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
7397 	}
7398 
7399 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7400 	    "sd_unit_attach: un:0x%p exit success\n", un);
7401 
7402 	return (DDI_SUCCESS);
7403 
7404 	/*
7405 	 * An error occurred during the attach; clean up & return failure.
7406 	 */
7407 
7408 devid_failed:
7409 
7410 setup_pm_failed:
7411 	ddi_remove_minor_node(devi, NULL);
7412 
7413 cmlb_attach_failed:
7414 	/*
7415 	 * Cleanup from the scsi_ifsetcap() calls (437868)
7416 	 */
7417 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
7418 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
7419 
7420 	/*
7421 	 * Refer to the comments of setting tagged-qing in the beginning of
7422 	 * sd_unit_attach. We can only disable tagged queuing when there is
7423 	 * no lun attached on the target.
7424 	 */
7425 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7426 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
7427 	}
7428 
7429 	if (un->un_f_is_fibre == FALSE) {
7430 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
7431 	}
7432 
7433 spinup_failed:
7434 
7435 	mutex_enter(SD_MUTEX(un));
7436 
7437 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
7438 	if (un->un_direct_priority_timeid != NULL) {
7439 		timeout_id_t temp_id = un->un_direct_priority_timeid;
7440 		un->un_direct_priority_timeid = NULL;
7441 		mutex_exit(SD_MUTEX(un));
7442 		(void) untimeout(temp_id);
7443 		mutex_enter(SD_MUTEX(un));
7444 	}
7445 
7446 	/* Cancel any pending start/stop timeouts */
7447 	if (un->un_startstop_timeid != NULL) {
7448 		timeout_id_t temp_id = un->un_startstop_timeid;
7449 		un->un_startstop_timeid = NULL;
7450 		mutex_exit(SD_MUTEX(un));
7451 		(void) untimeout(temp_id);
7452 		mutex_enter(SD_MUTEX(un));
7453 	}
7454 
7455 	/* Cancel any pending reset-throttle timeouts */
7456 	if (un->un_reset_throttle_timeid != NULL) {
7457 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
7458 		un->un_reset_throttle_timeid = NULL;
7459 		mutex_exit(SD_MUTEX(un));
7460 		(void) untimeout(temp_id);
7461 		mutex_enter(SD_MUTEX(un));
7462 	}
7463 
7464 	/* Cancel any pending retry timeouts */
7465 	if (un->un_retry_timeid != NULL) {
7466 		timeout_id_t temp_id = un->un_retry_timeid;
7467 		un->un_retry_timeid = NULL;
7468 		mutex_exit(SD_MUTEX(un));
7469 		(void) untimeout(temp_id);
7470 		mutex_enter(SD_MUTEX(un));
7471 	}
7472 
7473 	/* Cancel any pending delayed cv broadcast timeouts */
7474 	if (un->un_dcvb_timeid != NULL) {
7475 		timeout_id_t temp_id = un->un_dcvb_timeid;
7476 		un->un_dcvb_timeid = NULL;
7477 		mutex_exit(SD_MUTEX(un));
7478 		(void) untimeout(temp_id);
7479 		mutex_enter(SD_MUTEX(un));
7480 	}
7481 
7482 	mutex_exit(SD_MUTEX(un));
7483 
7484 	/* There should not be any in-progress I/O so ASSERT this check */
7485 	ASSERT(un->un_ncmds_in_transport == 0);
7486 	ASSERT(un->un_ncmds_in_driver == 0);
7487 
7488 	/* Do not free the softstate if the callback routine is active */
7489 	sd_sync_with_callback(un);
7490 
7491 	/*
7492 	 * Partition stats apparently are not used with removables. These would
7493 	 * not have been created during attach, so no need to clean them up...
7494 	 */
7495 	if (un->un_stats != NULL) {
7496 		kstat_delete(un->un_stats);
7497 		un->un_stats = NULL;
7498 	}
7499 	if (un->un_errstats != NULL) {
7500 		kstat_delete(un->un_errstats);
7501 		un->un_errstats = NULL;
7502 	}
7503 
7504 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
7505 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
7506 
7507 	ddi_prop_remove_all(devi);
7508 	sema_destroy(&un->un_semoclose);
7509 	cv_destroy(&un->un_state_cv);
7510 
7511 getrbuf_failed:
7512 
7513 	sd_free_rqs(un);
7514 
7515 alloc_rqs_failed:
7516 
7517 	devp->sd_private = NULL;
7518 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
7519 
7520 get_softstate_failed:
7521 	/*
7522 	 * Note: the man pages are unclear as to whether or not doing a
7523 	 * ddi_soft_state_free(sd_state, instance) is the right way to
7524 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
7525 	 * ddi_get_soft_state() fails.  The implication seems to be
7526 	 * that the get_soft_state cannot fail if the zalloc succeeds.
7527 	 */
7528 	ddi_soft_state_free(sd_state, instance);
7529 
7530 probe_failed:
7531 	scsi_unprobe(devp);
7532 
7533 	SD_ERROR(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: \
7534 	    un:0x%p exit failure\n", (void *)un);
7535 
7536 	return (DDI_FAILURE);
7537 }
7538 
7539 
7540 /*
7541  *    Function: sd_unit_detach
7542  *
7543  * Description: Performs DDI_DETACH processing for sddetach().
7544  *
7545  * Return Code: DDI_SUCCESS
7546  *		DDI_FAILURE
7547  *
7548  *     Context: Kernel thread context
7549  */
7550 
7551 static int
7552 sd_unit_detach(dev_info_t *devi)
7553 {
7554 	struct scsi_device	*devp;
7555 	struct sd_lun		*un;
7556 	int			i;
7557 	int			tgt;
7558 	dev_t			dev;
7559 	dev_info_t		*pdip = ddi_get_parent(devi);
7560 	int			instance = ddi_get_instance(devi);
7561 
7562 	mutex_enter(&sd_detach_mutex);
7563 
7564 	/*
7565 	 * Fail the detach for any of the following:
7566 	 *  - Unable to get the sd_lun struct for the instance
7567 	 *  - A layered driver has an outstanding open on the instance
7568 	 *  - Another thread is already detaching this instance
7569 	 *  - Another thread is currently performing an open
7570 	 */
7571 	devp = ddi_get_driver_private(devi);
7572 	if ((devp == NULL) ||
7573 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
7574 	    (un->un_ncmds_in_driver != 0) || (un->un_layer_count != 0) ||
7575 	    (un->un_detach_count != 0) || (un->un_opens_in_progress != 0)) {
7576 		mutex_exit(&sd_detach_mutex);
7577 		return (DDI_FAILURE);
7578 	}
7579 
7580 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
7581 
7582 	/*
7583 	 * Mark this instance as currently in a detach, to inhibit any
7584 	 * opens from a layered driver.
7585 	 */
7586 	un->un_detach_count++;
7587 	mutex_exit(&sd_detach_mutex);
7588 
7589 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7590 	    SCSI_ADDR_PROP_TARGET, -1);
7591 
7592 	dev = sd_make_device(SD_DEVINFO(un));
7593 
7594 #ifndef lint
7595 	_NOTE(COMPETING_THREADS_NOW);
7596 #endif
7597 
7598 	mutex_enter(SD_MUTEX(un));
7599 
7600 	/*
7601 	 * Fail the detach if there are any outstanding layered
7602 	 * opens on this device.
7603 	 */
7604 	for (i = 0; i < NDKMAP; i++) {
7605 		if (un->un_ocmap.lyropen[i] != 0) {
7606 			goto err_notclosed;
7607 		}
7608 	}
7609 
7610 	/*
7611 	 * Verify there are NO outstanding commands issued to this device.
7612 	 * ie, un_ncmds_in_transport == 0.
7613 	 * It's possible to have outstanding commands through the physio
7614 	 * code path, even though everything's closed.
7615 	 */
7616 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
7617 	    (un->un_direct_priority_timeid != NULL) ||
7618 	    (un->un_state == SD_STATE_RWAIT)) {
7619 		mutex_exit(SD_MUTEX(un));
7620 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7621 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
7622 		goto err_stillbusy;
7623 	}
7624 
7625 	/*
7626 	 * If we have the device reserved, release the reservation.
7627 	 */
7628 	if ((un->un_resvd_status & SD_RESERVE) &&
7629 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
7630 		mutex_exit(SD_MUTEX(un));
7631 		/*
7632 		 * Note: sd_reserve_release sends a command to the device
7633 		 * via the sd_ioctlcmd() path, and can sleep.
7634 		 */
7635 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
7636 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7637 			    "sd_dr_detach: Cannot release reservation \n");
7638 		}
7639 	} else {
7640 		mutex_exit(SD_MUTEX(un));
7641 	}
7642 
7643 	/*
7644 	 * Untimeout any reserve recover, throttle reset, restart unit
7645 	 * and delayed broadcast timeout threads. Protect the timeout pointer
7646 	 * from getting nulled by their callback functions.
7647 	 */
7648 	mutex_enter(SD_MUTEX(un));
7649 	if (un->un_resvd_timeid != NULL) {
7650 		timeout_id_t temp_id = un->un_resvd_timeid;
7651 		un->un_resvd_timeid = NULL;
7652 		mutex_exit(SD_MUTEX(un));
7653 		(void) untimeout(temp_id);
7654 		mutex_enter(SD_MUTEX(un));
7655 	}
7656 
7657 	if (un->un_reset_throttle_timeid != NULL) {
7658 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
7659 		un->un_reset_throttle_timeid = NULL;
7660 		mutex_exit(SD_MUTEX(un));
7661 		(void) untimeout(temp_id);
7662 		mutex_enter(SD_MUTEX(un));
7663 	}
7664 
7665 	if (un->un_startstop_timeid != NULL) {
7666 		timeout_id_t temp_id = un->un_startstop_timeid;
7667 		un->un_startstop_timeid = NULL;
7668 		mutex_exit(SD_MUTEX(un));
7669 		(void) untimeout(temp_id);
7670 		mutex_enter(SD_MUTEX(un));
7671 	}
7672 
7673 	if (un->un_dcvb_timeid != NULL) {
7674 		timeout_id_t temp_id = un->un_dcvb_timeid;
7675 		un->un_dcvb_timeid = NULL;
7676 		mutex_exit(SD_MUTEX(un));
7677 		(void) untimeout(temp_id);
7678 	} else {
7679 		mutex_exit(SD_MUTEX(un));
7680 	}
7681 
7682 	/* Remove any pending reservation reclaim requests for this device */
7683 	sd_rmv_resv_reclaim_req(dev);
7684 
7685 	mutex_enter(SD_MUTEX(un));
7686 
7687 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
7688 	if (un->un_direct_priority_timeid != NULL) {
7689 		timeout_id_t temp_id = un->un_direct_priority_timeid;
7690 		un->un_direct_priority_timeid = NULL;
7691 		mutex_exit(SD_MUTEX(un));
7692 		(void) untimeout(temp_id);
7693 		mutex_enter(SD_MUTEX(un));
7694 	}
7695 
7696 	/* Cancel any active multi-host disk watch thread requests */
7697 	if (un->un_mhd_token != NULL) {
7698 		mutex_exit(SD_MUTEX(un));
7699 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
7700 		if (scsi_watch_request_terminate(un->un_mhd_token,
7701 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
7702 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7703 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
7704 			/*
7705 			 * Note: We are returning here after having removed
7706 			 * some driver timeouts above. This is consistent with
7707 			 * the legacy implementation but perhaps the watch
7708 			 * terminate call should be made with the wait flag set.
7709 			 */
7710 			goto err_stillbusy;
7711 		}
7712 		mutex_enter(SD_MUTEX(un));
7713 		un->un_mhd_token = NULL;
7714 	}
7715 
7716 	if (un->un_swr_token != NULL) {
7717 		mutex_exit(SD_MUTEX(un));
7718 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
7719 		if (scsi_watch_request_terminate(un->un_swr_token,
7720 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
7721 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7722 			    "sd_dr_detach: Cannot cancel swr watch request\n");
7723 			/*
7724 			 * Note: We are returning here after having removed
7725 			 * some driver timeouts above. This is consistent with
7726 			 * the legacy implementation but perhaps the watch
7727 			 * terminate call should be made with the wait flag set.
7728 			 */
7729 			goto err_stillbusy;
7730 		}
7731 		mutex_enter(SD_MUTEX(un));
7732 		un->un_swr_token = NULL;
7733 	}
7734 
7735 	mutex_exit(SD_MUTEX(un));
7736 
7737 	/*
7738 	 * Clear any scsi_reset_notifies. We clear the reset notifies
7739 	 * if we have not registered one.
7740 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
7741 	 */
7742 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
7743 	    sd_mhd_reset_notify_cb, (caddr_t)un);
7744 
7745 	/*
7746 	 * protect the timeout pointers from getting nulled by
7747 	 * their callback functions during the cancellation process.
7748 	 * In such a scenario untimeout can be invoked with a null value.
7749 	 */
7750 	_NOTE(NO_COMPETING_THREADS_NOW);
7751 
7752 	mutex_enter(&un->un_pm_mutex);
7753 	if (un->un_pm_idle_timeid != NULL) {
7754 		timeout_id_t temp_id = un->un_pm_idle_timeid;
7755 		un->un_pm_idle_timeid = NULL;
7756 		mutex_exit(&un->un_pm_mutex);
7757 
7758 		/*
7759 		 * Timeout is active; cancel it.
7760 		 * Note that it'll never be active on a device
7761 		 * that does not support PM therefore we don't
7762 		 * have to check before calling pm_idle_component.
7763 		 */
7764 		(void) untimeout(temp_id);
7765 		(void) pm_idle_component(SD_DEVINFO(un), 0);
7766 		mutex_enter(&un->un_pm_mutex);
7767 	}
7768 
7769 	/*
7770 	 * Check whether there is already a timeout scheduled for power
7771 	 * management. If yes then don't lower the power here, that's.
7772 	 * the timeout handler's job.
7773 	 */
7774 	if (un->un_pm_timeid != NULL) {
7775 		timeout_id_t temp_id = un->un_pm_timeid;
7776 		un->un_pm_timeid = NULL;
7777 		mutex_exit(&un->un_pm_mutex);
7778 		/*
7779 		 * Timeout is active; cancel it.
7780 		 * Note that it'll never be active on a device
7781 		 * that does not support PM therefore we don't
7782 		 * have to check before calling pm_idle_component.
7783 		 */
7784 		(void) untimeout(temp_id);
7785 		(void) pm_idle_component(SD_DEVINFO(un), 0);
7786 
7787 	} else {
7788 		mutex_exit(&un->un_pm_mutex);
7789 		if ((un->un_f_pm_is_enabled == TRUE) &&
7790 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_SPINDLE_OFF) !=
7791 		    DDI_SUCCESS)) {
7792 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7793 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
7794 			/*
7795 			 * Fix for bug: 4297749, item # 13
7796 			 * The above test now includes a check to see if PM is
7797 			 * supported by this device before call
7798 			 * pm_lower_power().
7799 			 * Note, the following is not dead code. The call to
7800 			 * pm_lower_power above will generate a call back into
7801 			 * our sdpower routine which might result in a timeout
7802 			 * handler getting activated. Therefore the following
7803 			 * code is valid and necessary.
7804 			 */
7805 			mutex_enter(&un->un_pm_mutex);
7806 			if (un->un_pm_timeid != NULL) {
7807 				timeout_id_t temp_id = un->un_pm_timeid;
7808 				un->un_pm_timeid = NULL;
7809 				mutex_exit(&un->un_pm_mutex);
7810 				(void) untimeout(temp_id);
7811 				(void) pm_idle_component(SD_DEVINFO(un), 0);
7812 			} else {
7813 				mutex_exit(&un->un_pm_mutex);
7814 			}
7815 		}
7816 	}
7817 
7818 	/*
7819 	 * Cleanup from the scsi_ifsetcap() calls (437868)
7820 	 * Relocated here from above to be after the call to
7821 	 * pm_lower_power, which was getting errors.
7822 	 */
7823 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
7824 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
7825 
7826 	/*
7827 	 * Currently, tagged queuing is supported per target based by HBA.
7828 	 * Setting this per lun instance actually sets the capability of this
7829 	 * target in HBA, which affects those luns already attached on the
7830 	 * same target. So during detach, we can only disable this capability
7831 	 * only when this is the only lun left on this target. By doing
7832 	 * this, we assume a target has the same tagged queuing capability
7833 	 * for every lun. The condition can be removed when HBA is changed to
7834 	 * support per lun based tagged queuing capability.
7835 	 */
7836 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
7837 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
7838 	}
7839 
7840 	if (un->un_f_is_fibre == FALSE) {
7841 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
7842 	}
7843 
7844 	/*
7845 	 * Remove any event callbacks, fibre only
7846 	 */
7847 	if (un->un_f_is_fibre == TRUE) {
7848 		if ((un->un_insert_event != NULL) &&
7849 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
7850 		    DDI_SUCCESS)) {
7851 			/*
7852 			 * Note: We are returning here after having done
7853 			 * substantial cleanup above. This is consistent
7854 			 * with the legacy implementation but this may not
7855 			 * be the right thing to do.
7856 			 */
7857 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7858 			    "sd_dr_detach: Cannot cancel insert event\n");
7859 			goto err_remove_event;
7860 		}
7861 		un->un_insert_event = NULL;
7862 
7863 		if ((un->un_remove_event != NULL) &&
7864 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
7865 		    DDI_SUCCESS)) {
7866 			/*
7867 			 * Note: We are returning here after having done
7868 			 * substantial cleanup above. This is consistent
7869 			 * with the legacy implementation but this may not
7870 			 * be the right thing to do.
7871 			 */
7872 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7873 			    "sd_dr_detach: Cannot cancel remove event\n");
7874 			goto err_remove_event;
7875 		}
7876 		un->un_remove_event = NULL;
7877 	}
7878 
7879 	/* Do not free the softstate if the callback routine is active */
7880 	sd_sync_with_callback(un);
7881 
7882 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
7883 	cmlb_free_handle(&un->un_cmlbhandle);
7884 
7885 	/*
7886 	 * Hold the detach mutex here, to make sure that no other threads ever
7887 	 * can access a (partially) freed soft state structure.
7888 	 */
7889 	mutex_enter(&sd_detach_mutex);
7890 
7891 	/*
7892 	 * Clean up the soft state struct.
7893 	 * Cleanup is done in reverse order of allocs/inits.
7894 	 * At this point there should be no competing threads anymore.
7895 	 */
7896 
7897 	/* Unregister and free device id. */
7898 	ddi_devid_unregister(devi);
7899 	if (un->un_devid) {
7900 		ddi_devid_free(un->un_devid);
7901 		un->un_devid = NULL;
7902 	}
7903 
7904 	/*
7905 	 * Destroy wmap cache if it exists.
7906 	 */
7907 	if (un->un_wm_cache != NULL) {
7908 		kmem_cache_destroy(un->un_wm_cache);
7909 		un->un_wm_cache = NULL;
7910 	}
7911 
7912 	/*
7913 	 * kstat cleanup is done in detach for all device types (4363169).
7914 	 * We do not want to fail detach if the device kstats are not deleted
7915 	 * since there is a confusion about the devo_refcnt for the device.
7916 	 * We just delete the kstats and let detach complete successfully.
7917 	 */
7918 	if (un->un_stats != NULL) {
7919 		kstat_delete(un->un_stats);
7920 		un->un_stats = NULL;
7921 	}
7922 	if (un->un_errstats != NULL) {
7923 		kstat_delete(un->un_errstats);
7924 		un->un_errstats = NULL;
7925 	}
7926 
7927 	/* Remove partition stats */
7928 	if (un->un_f_pkstats_enabled) {
7929 		for (i = 0; i < NSDMAP; i++) {
7930 			if (un->un_pstats[i] != NULL) {
7931 				kstat_delete(un->un_pstats[i]);
7932 				un->un_pstats[i] = NULL;
7933 			}
7934 		}
7935 	}
7936 
7937 	/* Remove xbuf registration */
7938 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
7939 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
7940 
7941 	/* Remove driver properties */
7942 	ddi_prop_remove_all(devi);
7943 
7944 	mutex_destroy(&un->un_pm_mutex);
7945 	cv_destroy(&un->un_pm_busy_cv);
7946 
7947 	cv_destroy(&un->un_wcc_cv);
7948 
7949 	/* Open/close semaphore */
7950 	sema_destroy(&un->un_semoclose);
7951 
7952 	/* Removable media condvar. */
7953 	cv_destroy(&un->un_state_cv);
7954 
7955 	/* Suspend/resume condvar. */
7956 	cv_destroy(&un->un_suspend_cv);
7957 	cv_destroy(&un->un_disk_busy_cv);
7958 
7959 	sd_free_rqs(un);
7960 
7961 	/* Free up soft state */
7962 	devp->sd_private = NULL;
7963 
7964 	bzero(un, sizeof (struct sd_lun));
7965 	ddi_soft_state_free(sd_state, instance);
7966 
7967 	mutex_exit(&sd_detach_mutex);
7968 
7969 	/* This frees up the INQUIRY data associated with the device. */
7970 	scsi_unprobe(devp);
7971 
7972 	/*
7973 	 * After successfully detaching an instance, we update the information
7974 	 * of how many luns have been attached in the relative target and
7975 	 * controller for parallel SCSI. This information is used when sd tries
7976 	 * to set the tagged queuing capability in HBA.
7977 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
7978 	 * check if the device is parallel SCSI. However, we don't need to
7979 	 * check here because we've already checked during attach. No device
7980 	 * that is not parallel SCSI is in the chain.
7981 	 */
7982 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
7983 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
7984 	}
7985 
7986 	return (DDI_SUCCESS);
7987 
7988 err_notclosed:
7989 	mutex_exit(SD_MUTEX(un));
7990 
7991 err_stillbusy:
7992 	_NOTE(NO_COMPETING_THREADS_NOW);
7993 
7994 err_remove_event:
7995 	mutex_enter(&sd_detach_mutex);
7996 	un->un_detach_count--;
7997 	mutex_exit(&sd_detach_mutex);
7998 
7999 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
8000 	return (DDI_FAILURE);
8001 }
8002 
8003 
8004 /*
8005  *    Function: sd_create_errstats
8006  *
8007  * Description: This routine instantiates the device error stats.
8008  *
8009  *		Note: During attach the stats are instantiated first so they are
8010  *		available for attach-time routines that utilize the driver
8011  *		iopath to send commands to the device. The stats are initialized
8012  *		separately so data obtained during some attach-time routines is
8013  *		available. (4362483)
8014  *
8015  *   Arguments: un - driver soft state (unit) structure
8016  *		instance - driver instance
8017  *
8018  *     Context: Kernel thread context
8019  */
8020 
8021 static void
8022 sd_create_errstats(struct sd_lun *un, int instance)
8023 {
8024 	struct	sd_errstats	*stp;
8025 	char	kstatmodule_err[KSTAT_STRLEN];
8026 	char	kstatname[KSTAT_STRLEN];
8027 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
8028 
8029 	ASSERT(un != NULL);
8030 
8031 	if (un->un_errstats != NULL) {
8032 		return;
8033 	}
8034 
8035 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
8036 	    "%serr", sd_label);
8037 	(void) snprintf(kstatname, sizeof (kstatname),
8038 	    "%s%d,err", sd_label, instance);
8039 
8040 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
8041 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
8042 
8043 	if (un->un_errstats == NULL) {
8044 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8045 		    "sd_create_errstats: Failed kstat_create\n");
8046 		return;
8047 	}
8048 
8049 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8050 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
8051 	    KSTAT_DATA_UINT32);
8052 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
8053 	    KSTAT_DATA_UINT32);
8054 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
8055 	    KSTAT_DATA_UINT32);
8056 	kstat_named_init(&stp->sd_vid,		"Vendor",
8057 	    KSTAT_DATA_CHAR);
8058 	kstat_named_init(&stp->sd_pid,		"Product",
8059 	    KSTAT_DATA_CHAR);
8060 	kstat_named_init(&stp->sd_revision,	"Revision",
8061 	    KSTAT_DATA_CHAR);
8062 	kstat_named_init(&stp->sd_serial,	"Serial No",
8063 	    KSTAT_DATA_CHAR);
8064 	kstat_named_init(&stp->sd_capacity,	"Size",
8065 	    KSTAT_DATA_ULONGLONG);
8066 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
8067 	    KSTAT_DATA_UINT32);
8068 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
8069 	    KSTAT_DATA_UINT32);
8070 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
8071 	    KSTAT_DATA_UINT32);
8072 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
8073 	    KSTAT_DATA_UINT32);
8074 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
8075 	    KSTAT_DATA_UINT32);
8076 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
8077 	    KSTAT_DATA_UINT32);
8078 
8079 	un->un_errstats->ks_private = un;
8080 	un->un_errstats->ks_update  = nulldev;
8081 
8082 	kstat_install(un->un_errstats);
8083 }
8084 
8085 
8086 /*
8087  *    Function: sd_set_errstats
8088  *
8089  * Description: This routine sets the value of the vendor id, product id,
8090  *		revision, serial number, and capacity device error stats.
8091  *
8092  *		Note: During attach the stats are instantiated first so they are
8093  *		available for attach-time routines that utilize the driver
8094  *		iopath to send commands to the device. The stats are initialized
8095  *		separately so data obtained during some attach-time routines is
8096  *		available. (4362483)
8097  *
8098  *   Arguments: un - driver soft state (unit) structure
8099  *
8100  *     Context: Kernel thread context
8101  */
8102 
8103 static void
8104 sd_set_errstats(struct sd_lun *un)
8105 {
8106 	struct	sd_errstats	*stp;
8107 
8108 	ASSERT(un != NULL);
8109 	ASSERT(un->un_errstats != NULL);
8110 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8111 	ASSERT(stp != NULL);
8112 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
8113 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
8114 	(void) strncpy(stp->sd_revision.value.c,
8115 	    un->un_sd->sd_inq->inq_revision, 4);
8116 
8117 	/*
8118 	 * All the errstats are persistent across detach/attach,
8119 	 * so reset all the errstats here in case of the hot
8120 	 * replacement of disk drives, except for not changed
8121 	 * Sun qualified drives.
8122 	 */
8123 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
8124 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8125 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
8126 		stp->sd_softerrs.value.ui32 = 0;
8127 		stp->sd_harderrs.value.ui32 = 0;
8128 		stp->sd_transerrs.value.ui32 = 0;
8129 		stp->sd_rq_media_err.value.ui32 = 0;
8130 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
8131 		stp->sd_rq_nodev_err.value.ui32 = 0;
8132 		stp->sd_rq_recov_err.value.ui32 = 0;
8133 		stp->sd_rq_illrq_err.value.ui32 = 0;
8134 		stp->sd_rq_pfa_err.value.ui32 = 0;
8135 	}
8136 
8137 	/*
8138 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
8139 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
8140 	 * (4376302))
8141 	 */
8142 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
8143 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8144 		    sizeof (SD_INQUIRY(un)->inq_serial));
8145 	}
8146 
8147 	if (un->un_f_blockcount_is_valid != TRUE) {
8148 		/*
8149 		 * Set capacity error stat to 0 for no media. This ensures
8150 		 * a valid capacity is displayed in response to 'iostat -E'
8151 		 * when no media is present in the device.
8152 		 */
8153 		stp->sd_capacity.value.ui64 = 0;
8154 	} else {
8155 		/*
8156 		 * Multiply un_blockcount by un->un_sys_blocksize to get
8157 		 * capacity.
8158 		 *
8159 		 * Note: for non-512 blocksize devices "un_blockcount" has been
8160 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
8161 		 * (un_tgt_blocksize / un->un_sys_blocksize).
8162 		 */
8163 		stp->sd_capacity.value.ui64 = (uint64_t)
8164 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
8165 	}
8166 }
8167 
8168 
8169 /*
8170  *    Function: sd_set_pstats
8171  *
8172  * Description: This routine instantiates and initializes the partition
8173  *              stats for each partition with more than zero blocks.
8174  *		(4363169)
8175  *
8176  *   Arguments: un - driver soft state (unit) structure
8177  *
8178  *     Context: Kernel thread context
8179  */
8180 
8181 static void
8182 sd_set_pstats(struct sd_lun *un)
8183 {
8184 	char	kstatname[KSTAT_STRLEN];
8185 	int	instance;
8186 	int	i;
8187 	diskaddr_t	nblks = 0;
8188 	char	*partname = NULL;
8189 
8190 	ASSERT(un != NULL);
8191 
8192 	instance = ddi_get_instance(SD_DEVINFO(un));
8193 
8194 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
8195 	for (i = 0; i < NSDMAP; i++) {
8196 
8197 		if (cmlb_partinfo(un->un_cmlbhandle, i,
8198 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
8199 			continue;
8200 		mutex_enter(SD_MUTEX(un));
8201 
8202 		if ((un->un_pstats[i] == NULL) &&
8203 		    (nblks != 0)) {
8204 
8205 			(void) snprintf(kstatname, sizeof (kstatname),
8206 			    "%s%d,%s", sd_label, instance,
8207 			    partname);
8208 
8209 			un->un_pstats[i] = kstat_create(sd_label,
8210 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
8211 			    1, KSTAT_FLAG_PERSISTENT);
8212 			if (un->un_pstats[i] != NULL) {
8213 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
8214 				kstat_install(un->un_pstats[i]);
8215 			}
8216 		}
8217 		mutex_exit(SD_MUTEX(un));
8218 	}
8219 }
8220 
8221 
8222 #if (defined(__fibre))
8223 /*
8224  *    Function: sd_init_event_callbacks
8225  *
8226  * Description: This routine initializes the insertion and removal event
8227  *		callbacks. (fibre only)
8228  *
8229  *   Arguments: un - driver soft state (unit) structure
8230  *
8231  *     Context: Kernel thread context
8232  */
8233 
8234 static void
8235 sd_init_event_callbacks(struct sd_lun *un)
8236 {
8237 	ASSERT(un != NULL);
8238 
8239 	if ((un->un_insert_event == NULL) &&
8240 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
8241 	    &un->un_insert_event) == DDI_SUCCESS)) {
8242 		/*
8243 		 * Add the callback for an insertion event
8244 		 */
8245 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8246 		    un->un_insert_event, sd_event_callback, (void *)un,
8247 		    &(un->un_insert_cb_id));
8248 	}
8249 
8250 	if ((un->un_remove_event == NULL) &&
8251 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
8252 	    &un->un_remove_event) == DDI_SUCCESS)) {
8253 		/*
8254 		 * Add the callback for a removal event
8255 		 */
8256 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8257 		    un->un_remove_event, sd_event_callback, (void *)un,
8258 		    &(un->un_remove_cb_id));
8259 	}
8260 }
8261 
8262 
8263 /*
8264  *    Function: sd_event_callback
8265  *
8266  * Description: This routine handles insert/remove events (photon). The
8267  *		state is changed to OFFLINE which can be used to supress
8268  *		error msgs. (fibre only)
8269  *
8270  *   Arguments: un - driver soft state (unit) structure
8271  *
8272  *     Context: Callout thread context
8273  */
8274 /* ARGSUSED */
8275 static void
8276 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
8277     void *bus_impldata)
8278 {
8279 	struct sd_lun *un = (struct sd_lun *)arg;
8280 
8281 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
8282 	if (event == un->un_insert_event) {
8283 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
8284 		mutex_enter(SD_MUTEX(un));
8285 		if (un->un_state == SD_STATE_OFFLINE) {
8286 			if (un->un_last_state != SD_STATE_SUSPENDED) {
8287 				un->un_state = un->un_last_state;
8288 			} else {
8289 				/*
8290 				 * We have gone through SUSPEND/RESUME while
8291 				 * we were offline. Restore the last state
8292 				 */
8293 				un->un_state = un->un_save_state;
8294 			}
8295 		}
8296 		mutex_exit(SD_MUTEX(un));
8297 
8298 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
8299 	} else if (event == un->un_remove_event) {
8300 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
8301 		mutex_enter(SD_MUTEX(un));
8302 		/*
8303 		 * We need to handle an event callback that occurs during
8304 		 * the suspend operation, since we don't prevent it.
8305 		 */
8306 		if (un->un_state != SD_STATE_OFFLINE) {
8307 			if (un->un_state != SD_STATE_SUSPENDED) {
8308 				New_state(un, SD_STATE_OFFLINE);
8309 			} else {
8310 				un->un_last_state = SD_STATE_OFFLINE;
8311 			}
8312 		}
8313 		mutex_exit(SD_MUTEX(un));
8314 	} else {
8315 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
8316 		    "!Unknown event\n");
8317 	}
8318 
8319 }
8320 #endif
8321 
8322 /*
8323  *    Function: sd_cache_control()
8324  *
8325  * Description: This routine is the driver entry point for setting
8326  *		read and write caching by modifying the WCE (write cache
8327  *		enable) and RCD (read cache disable) bits of mode
8328  *		page 8 (MODEPAGE_CACHING).
8329  *
8330  *   Arguments: un - driver soft state (unit) structure
8331  *		rcd_flag - flag for controlling the read cache
8332  *		wce_flag - flag for controlling the write cache
8333  *
8334  * Return Code: EIO
8335  *		code returned by sd_send_scsi_MODE_SENSE and
8336  *		sd_send_scsi_MODE_SELECT
8337  *
8338  *     Context: Kernel Thread
8339  */
8340 
8341 static int
8342 sd_cache_control(struct sd_lun *un, int rcd_flag, int wce_flag)
8343 {
8344 	struct mode_caching	*mode_caching_page;
8345 	uchar_t			*header;
8346 	size_t			buflen;
8347 	int			hdrlen;
8348 	int			bd_len;
8349 	int			rval = 0;
8350 	struct mode_header_grp2	*mhp;
8351 
8352 	ASSERT(un != NULL);
8353 
8354 	/*
8355 	 * Do a test unit ready, otherwise a mode sense may not work if this
8356 	 * is the first command sent to the device after boot.
8357 	 */
8358 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
8359 
8360 	if (un->un_f_cfg_is_atapi == TRUE) {
8361 		hdrlen = MODE_HEADER_LENGTH_GRP2;
8362 	} else {
8363 		hdrlen = MODE_HEADER_LENGTH;
8364 	}
8365 
8366 	/*
8367 	 * Allocate memory for the retrieved mode page and its headers.  Set
8368 	 * a pointer to the page itself.  Use mode_cache_scsi3 to insure
8369 	 * we get all of the mode sense data otherwise, the mode select
8370 	 * will fail.  mode_cache_scsi3 is a superset of mode_caching.
8371 	 */
8372 	buflen = hdrlen + MODE_BLK_DESC_LENGTH +
8373 	    sizeof (struct mode_cache_scsi3);
8374 
8375 	header = kmem_zalloc(buflen, KM_SLEEP);
8376 
8377 	/* Get the information from the device. */
8378 	if (un->un_f_cfg_is_atapi == TRUE) {
8379 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
8380 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8381 	} else {
8382 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
8383 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8384 	}
8385 	if (rval != 0) {
8386 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
8387 		    "sd_cache_control: Mode Sense Failed\n");
8388 		kmem_free(header, buflen);
8389 		return (rval);
8390 	}
8391 
8392 	/*
8393 	 * Determine size of Block Descriptors in order to locate
8394 	 * the mode page data. ATAPI devices return 0, SCSI devices
8395 	 * should return MODE_BLK_DESC_LENGTH.
8396 	 */
8397 	if (un->un_f_cfg_is_atapi == TRUE) {
8398 		mhp	= (struct mode_header_grp2 *)header;
8399 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
8400 	} else {
8401 		bd_len  = ((struct mode_header *)header)->bdesc_length;
8402 	}
8403 
8404 	if (bd_len > MODE_BLK_DESC_LENGTH) {
8405 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
8406 		    "sd_cache_control: Mode Sense returned invalid "
8407 		    "block descriptor length\n");
8408 		kmem_free(header, buflen);
8409 		return (EIO);
8410 	}
8411 
8412 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
8413 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
8414 		SD_ERROR(SD_LOG_COMMON, un, "sd_cache_control: Mode Sense"
8415 		    " caching page code mismatch %d\n",
8416 		    mode_caching_page->mode_page.code);
8417 		kmem_free(header, buflen);
8418 		return (EIO);
8419 	}
8420 
8421 	/* Check the relevant bits on successful mode sense. */
8422 	if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
8423 	    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
8424 	    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
8425 	    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
8426 
8427 		size_t sbuflen;
8428 		uchar_t save_pg;
8429 
8430 		/*
8431 		 * Construct select buffer length based on the
8432 		 * length of the sense data returned.
8433 		 */
8434 		sbuflen =  hdrlen + MODE_BLK_DESC_LENGTH +
8435 		    sizeof (struct mode_page) +
8436 		    (int)mode_caching_page->mode_page.length;
8437 
8438 		/*
8439 		 * Set the caching bits as requested.
8440 		 */
8441 		if (rcd_flag == SD_CACHE_ENABLE)
8442 			mode_caching_page->rcd = 0;
8443 		else if (rcd_flag == SD_CACHE_DISABLE)
8444 			mode_caching_page->rcd = 1;
8445 
8446 		if (wce_flag == SD_CACHE_ENABLE)
8447 			mode_caching_page->wce = 1;
8448 		else if (wce_flag == SD_CACHE_DISABLE)
8449 			mode_caching_page->wce = 0;
8450 
8451 		/*
8452 		 * Save the page if the mode sense says the
8453 		 * drive supports it.
8454 		 */
8455 		save_pg = mode_caching_page->mode_page.ps ?
8456 		    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
8457 
8458 		/* Clear reserved bits before mode select. */
8459 		mode_caching_page->mode_page.ps = 0;
8460 
8461 		/*
8462 		 * Clear out mode header for mode select.
8463 		 * The rest of the retrieved page will be reused.
8464 		 */
8465 		bzero(header, hdrlen);
8466 
8467 		if (un->un_f_cfg_is_atapi == TRUE) {
8468 			mhp = (struct mode_header_grp2 *)header;
8469 			mhp->bdesc_length_hi = bd_len >> 8;
8470 			mhp->bdesc_length_lo = (uchar_t)bd_len & 0xff;
8471 		} else {
8472 			((struct mode_header *)header)->bdesc_length = bd_len;
8473 		}
8474 
8475 		/* Issue mode select to change the cache settings */
8476 		if (un->un_f_cfg_is_atapi == TRUE) {
8477 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, header,
8478 			    sbuflen, save_pg, SD_PATH_DIRECT);
8479 		} else {
8480 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
8481 			    sbuflen, save_pg, SD_PATH_DIRECT);
8482 		}
8483 	}
8484 
8485 	kmem_free(header, buflen);
8486 	return (rval);
8487 }
8488 
8489 
8490 /*
8491  *    Function: sd_get_write_cache_enabled()
8492  *
8493  * Description: This routine is the driver entry point for determining if
8494  *		write caching is enabled.  It examines the WCE (write cache
8495  *		enable) bits of mode page 8 (MODEPAGE_CACHING).
8496  *
8497  *   Arguments: un - driver soft state (unit) structure
8498  *		is_enabled - pointer to int where write cache enabled state
8499  *		is returned (non-zero -> write cache enabled)
8500  *
8501  *
8502  * Return Code: EIO
8503  *		code returned by sd_send_scsi_MODE_SENSE
8504  *
8505  *     Context: Kernel Thread
8506  *
8507  * NOTE: If ioctl is added to disable write cache, this sequence should
8508  * be followed so that no locking is required for accesses to
8509  * un->un_f_write_cache_enabled:
8510  * 	do mode select to clear wce
8511  * 	do synchronize cache to flush cache
8512  * 	set un->un_f_write_cache_enabled = FALSE
8513  *
8514  * Conversely, an ioctl to enable the write cache should be done
8515  * in this order:
8516  * 	set un->un_f_write_cache_enabled = TRUE
8517  * 	do mode select to set wce
8518  */
8519 
8520 static int
8521 sd_get_write_cache_enabled(struct sd_lun *un, int *is_enabled)
8522 {
8523 	struct mode_caching	*mode_caching_page;
8524 	uchar_t			*header;
8525 	size_t			buflen;
8526 	int			hdrlen;
8527 	int			bd_len;
8528 	int			rval = 0;
8529 
8530 	ASSERT(un != NULL);
8531 	ASSERT(is_enabled != NULL);
8532 
8533 	/* in case of error, flag as enabled */
8534 	*is_enabled = TRUE;
8535 
8536 	/*
8537 	 * Do a test unit ready, otherwise a mode sense may not work if this
8538 	 * is the first command sent to the device after boot.
8539 	 */
8540 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
8541 
8542 	if (un->un_f_cfg_is_atapi == TRUE) {
8543 		hdrlen = MODE_HEADER_LENGTH_GRP2;
8544 	} else {
8545 		hdrlen = MODE_HEADER_LENGTH;
8546 	}
8547 
8548 	/*
8549 	 * Allocate memory for the retrieved mode page and its headers.  Set
8550 	 * a pointer to the page itself.
8551 	 */
8552 	buflen = hdrlen + MODE_BLK_DESC_LENGTH + sizeof (struct mode_caching);
8553 	header = kmem_zalloc(buflen, KM_SLEEP);
8554 
8555 	/* Get the information from the device. */
8556 	if (un->un_f_cfg_is_atapi == TRUE) {
8557 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
8558 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8559 	} else {
8560 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
8561 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8562 	}
8563 	if (rval != 0) {
8564 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
8565 		    "sd_get_write_cache_enabled: Mode Sense Failed\n");
8566 		kmem_free(header, buflen);
8567 		return (rval);
8568 	}
8569 
8570 	/*
8571 	 * Determine size of Block Descriptors in order to locate
8572 	 * the mode page data. ATAPI devices return 0, SCSI devices
8573 	 * should return MODE_BLK_DESC_LENGTH.
8574 	 */
8575 	if (un->un_f_cfg_is_atapi == TRUE) {
8576 		struct mode_header_grp2	*mhp;
8577 		mhp	= (struct mode_header_grp2 *)header;
8578 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
8579 	} else {
8580 		bd_len  = ((struct mode_header *)header)->bdesc_length;
8581 	}
8582 
8583 	if (bd_len > MODE_BLK_DESC_LENGTH) {
8584 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
8585 		    "sd_get_write_cache_enabled: Mode Sense returned invalid "
8586 		    "block descriptor length\n");
8587 		kmem_free(header, buflen);
8588 		return (EIO);
8589 	}
8590 
8591 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
8592 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
8593 		SD_ERROR(SD_LOG_COMMON, un, "sd_cache_control: Mode Sense"
8594 		    " caching page code mismatch %d\n",
8595 		    mode_caching_page->mode_page.code);
8596 		kmem_free(header, buflen);
8597 		return (EIO);
8598 	}
8599 	*is_enabled = mode_caching_page->wce;
8600 
8601 	kmem_free(header, buflen);
8602 	return (0);
8603 }
8604 
8605 /*
8606  *    Function: sd_get_nv_sup()
8607  *
8608  * Description: This routine is the driver entry point for
8609  * determining whether non-volatile cache is supported. This
8610  * determination process works as follows:
8611  *
8612  * 1. sd first queries sd.conf on whether
8613  * suppress_cache_flush bit is set for this device.
8614  *
8615  * 2. if not there, then queries the internal disk table.
8616  *
8617  * 3. if either sd.conf or internal disk table specifies
8618  * cache flush be suppressed, we don't bother checking
8619  * NV_SUP bit.
8620  *
8621  * If SUPPRESS_CACHE_FLUSH bit is not set to 1, sd queries
8622  * the optional INQUIRY VPD page 0x86. If the device
8623  * supports VPD page 0x86, sd examines the NV_SUP
8624  * (non-volatile cache support) bit in the INQUIRY VPD page
8625  * 0x86:
8626  *   o If NV_SUP bit is set, sd assumes the device has a
8627  *   non-volatile cache and set the
8628  *   un_f_sync_nv_supported to TRUE.
8629  *   o Otherwise cache is not non-volatile,
8630  *   un_f_sync_nv_supported is set to FALSE.
8631  *
8632  * Arguments: un - driver soft state (unit) structure
8633  *
8634  * Return Code:
8635  *
8636  *     Context: Kernel Thread
8637  */
8638 
8639 static void
8640 sd_get_nv_sup(struct sd_lun *un)
8641 {
8642 	int		rval		= 0;
8643 	uchar_t		*inq86		= NULL;
8644 	size_t		inq86_len	= MAX_INQUIRY_SIZE;
8645 	size_t		inq86_resid	= 0;
8646 	struct		dk_callback *dkc;
8647 
8648 	ASSERT(un != NULL);
8649 
8650 	mutex_enter(SD_MUTEX(un));
8651 
8652 	/*
8653 	 * Be conservative on the device's support of
8654 	 * SYNC_NV bit: un_f_sync_nv_supported is
8655 	 * initialized to be false.
8656 	 */
8657 	un->un_f_sync_nv_supported = FALSE;
8658 
8659 	/*
8660 	 * If either sd.conf or internal disk table
8661 	 * specifies cache flush be suppressed, then
8662 	 * we don't bother checking NV_SUP bit.
8663 	 */
8664 	if (un->un_f_suppress_cache_flush == TRUE) {
8665 		mutex_exit(SD_MUTEX(un));
8666 		return;
8667 	}
8668 
8669 	if (sd_check_vpd_page_support(un) == 0 &&
8670 	    un->un_vpd_page_mask & SD_VPD_EXTENDED_DATA_PG) {
8671 		mutex_exit(SD_MUTEX(un));
8672 		/* collect page 86 data if available */
8673 		inq86 = kmem_zalloc(inq86_len, KM_SLEEP);
8674 		rval = sd_send_scsi_INQUIRY(un, inq86, inq86_len,
8675 		    0x01, 0x86, &inq86_resid);
8676 
8677 		if (rval == 0 && (inq86_len - inq86_resid > 6)) {
8678 			SD_TRACE(SD_LOG_COMMON, un,
8679 			    "sd_get_nv_sup: \
8680 			    successfully get VPD page: %x \
8681 			    PAGE LENGTH: %x BYTE 6: %x\n",
8682 			    inq86[1], inq86[3], inq86[6]);
8683 
8684 			mutex_enter(SD_MUTEX(un));
8685 			/*
8686 			 * check the value of NV_SUP bit: only if the device
8687 			 * reports NV_SUP bit to be 1, the
8688 			 * un_f_sync_nv_supported bit will be set to true.
8689 			 */
8690 			if (inq86[6] & SD_VPD_NV_SUP) {
8691 				un->un_f_sync_nv_supported = TRUE;
8692 			}
8693 			mutex_exit(SD_MUTEX(un));
8694 		}
8695 		kmem_free(inq86, inq86_len);
8696 	} else {
8697 		mutex_exit(SD_MUTEX(un));
8698 	}
8699 
8700 	/*
8701 	 * Send a SYNC CACHE command to check whether
8702 	 * SYNC_NV bit is supported. This command should have
8703 	 * un_f_sync_nv_supported set to correct value.
8704 	 */
8705 	mutex_enter(SD_MUTEX(un));
8706 	if (un->un_f_sync_nv_supported) {
8707 		mutex_exit(SD_MUTEX(un));
8708 		dkc = kmem_zalloc(sizeof (struct dk_callback), KM_SLEEP);
8709 		dkc->dkc_flag = FLUSH_VOLATILE;
8710 		(void) sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
8711 
8712 		/*
8713 		 * Send a TEST UNIT READY command to the device. This should
8714 		 * clear any outstanding UNIT ATTENTION that may be present.
8715 		 */
8716 		(void) sd_send_scsi_TEST_UNIT_READY(un, SD_DONT_RETRY_TUR);
8717 
8718 		kmem_free(dkc, sizeof (struct dk_callback));
8719 	} else {
8720 		mutex_exit(SD_MUTEX(un));
8721 	}
8722 
8723 	SD_TRACE(SD_LOG_COMMON, un, "sd_get_nv_sup: \
8724 	    un_f_suppress_cache_flush is set to %d\n",
8725 	    un->un_f_suppress_cache_flush);
8726 }
8727 
8728 /*
8729  *    Function: sd_make_device
8730  *
8731  * Description: Utility routine to return the Solaris device number from
8732  *		the data in the device's dev_info structure.
8733  *
8734  * Return Code: The Solaris device number
8735  *
8736  *     Context: Any
8737  */
8738 
8739 static dev_t
8740 sd_make_device(dev_info_t *devi)
8741 {
8742 	return (makedevice(ddi_name_to_major(ddi_get_name(devi)),
8743 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
8744 }
8745 
8746 
8747 /*
8748  *    Function: sd_pm_entry
8749  *
8750  * Description: Called at the start of a new command to manage power
8751  *		and busy status of a device. This includes determining whether
8752  *		the current power state of the device is sufficient for
8753  *		performing the command or whether it must be changed.
8754  *		The PM framework is notified appropriately.
8755  *		Only with a return status of DDI_SUCCESS will the
8756  *		component be busy to the framework.
8757  *
8758  *		All callers of sd_pm_entry must check the return status
8759  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
8760  *		of DDI_FAILURE indicates the device failed to power up.
8761  *		In this case un_pm_count has been adjusted so the result
8762  *		on exit is still powered down, ie. count is less than 0.
8763  *		Calling sd_pm_exit with this count value hits an ASSERT.
8764  *
8765  * Return Code: DDI_SUCCESS or DDI_FAILURE
8766  *
8767  *     Context: Kernel thread context.
8768  */
8769 
8770 static int
8771 sd_pm_entry(struct sd_lun *un)
8772 {
8773 	int return_status = DDI_SUCCESS;
8774 
8775 	ASSERT(!mutex_owned(SD_MUTEX(un)));
8776 	ASSERT(!mutex_owned(&un->un_pm_mutex));
8777 
8778 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
8779 
8780 	if (un->un_f_pm_is_enabled == FALSE) {
8781 		SD_TRACE(SD_LOG_IO_PM, un,
8782 		    "sd_pm_entry: exiting, PM not enabled\n");
8783 		return (return_status);
8784 	}
8785 
8786 	/*
8787 	 * Just increment a counter if PM is enabled. On the transition from
8788 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
8789 	 * the count with each IO and mark the device as idle when the count
8790 	 * hits 0.
8791 	 *
8792 	 * If the count is less than 0 the device is powered down. If a powered
8793 	 * down device is successfully powered up then the count must be
8794 	 * incremented to reflect the power up. Note that it'll get incremented
8795 	 * a second time to become busy.
8796 	 *
8797 	 * Because the following has the potential to change the device state
8798 	 * and must release the un_pm_mutex to do so, only one thread can be
8799 	 * allowed through at a time.
8800 	 */
8801 
8802 	mutex_enter(&un->un_pm_mutex);
8803 	while (un->un_pm_busy == TRUE) {
8804 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
8805 	}
8806 	un->un_pm_busy = TRUE;
8807 
8808 	if (un->un_pm_count < 1) {
8809 
8810 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
8811 
8812 		/*
8813 		 * Indicate we are now busy so the framework won't attempt to
8814 		 * power down the device. This call will only fail if either
8815 		 * we passed a bad component number or the device has no
8816 		 * components. Neither of these should ever happen.
8817 		 */
8818 		mutex_exit(&un->un_pm_mutex);
8819 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
8820 		ASSERT(return_status == DDI_SUCCESS);
8821 
8822 		mutex_enter(&un->un_pm_mutex);
8823 
8824 		if (un->un_pm_count < 0) {
8825 			mutex_exit(&un->un_pm_mutex);
8826 
8827 			SD_TRACE(SD_LOG_IO_PM, un,
8828 			    "sd_pm_entry: power up component\n");
8829 
8830 			/*
8831 			 * pm_raise_power will cause sdpower to be called
8832 			 * which brings the device power level to the
8833 			 * desired state, ON in this case. If successful,
8834 			 * un_pm_count and un_power_level will be updated
8835 			 * appropriately.
8836 			 */
8837 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
8838 			    SD_SPINDLE_ON);
8839 
8840 			mutex_enter(&un->un_pm_mutex);
8841 
8842 			if (return_status != DDI_SUCCESS) {
8843 				/*
8844 				 * Power up failed.
8845 				 * Idle the device and adjust the count
8846 				 * so the result on exit is that we're
8847 				 * still powered down, ie. count is less than 0.
8848 				 */
8849 				SD_TRACE(SD_LOG_IO_PM, un,
8850 				    "sd_pm_entry: power up failed,"
8851 				    " idle the component\n");
8852 
8853 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8854 				un->un_pm_count--;
8855 			} else {
8856 				/*
8857 				 * Device is powered up, verify the
8858 				 * count is non-negative.
8859 				 * This is debug only.
8860 				 */
8861 				ASSERT(un->un_pm_count == 0);
8862 			}
8863 		}
8864 
8865 		if (return_status == DDI_SUCCESS) {
8866 			/*
8867 			 * For performance, now that the device has been tagged
8868 			 * as busy, and it's known to be powered up, update the
8869 			 * chain types to use jump tables that do not include
8870 			 * pm. This significantly lowers the overhead and
8871 			 * therefore improves performance.
8872 			 */
8873 
8874 			mutex_exit(&un->un_pm_mutex);
8875 			mutex_enter(SD_MUTEX(un));
8876 			SD_TRACE(SD_LOG_IO_PM, un,
8877 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
8878 			    un->un_uscsi_chain_type);
8879 
8880 			if (un->un_f_non_devbsize_supported) {
8881 				un->un_buf_chain_type =
8882 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
8883 			} else {
8884 				un->un_buf_chain_type =
8885 				    SD_CHAIN_INFO_DISK_NO_PM;
8886 			}
8887 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8888 
8889 			SD_TRACE(SD_LOG_IO_PM, un,
8890 			    "             changed  uscsi_chain_type to   %d\n",
8891 			    un->un_uscsi_chain_type);
8892 			mutex_exit(SD_MUTEX(un));
8893 			mutex_enter(&un->un_pm_mutex);
8894 
8895 			if (un->un_pm_idle_timeid == NULL) {
8896 				/* 300 ms. */
8897 				un->un_pm_idle_timeid =
8898 				    timeout(sd_pm_idletimeout_handler, un,
8899 				    (drv_usectohz((clock_t)300000)));
8900 				/*
8901 				 * Include an extra call to busy which keeps the
8902 				 * device busy with-respect-to the PM layer
8903 				 * until the timer fires, at which time it'll
8904 				 * get the extra idle call.
8905 				 */
8906 				(void) pm_busy_component(SD_DEVINFO(un), 0);
8907 			}
8908 		}
8909 	}
8910 	un->un_pm_busy = FALSE;
8911 	/* Next... */
8912 	cv_signal(&un->un_pm_busy_cv);
8913 
8914 	un->un_pm_count++;
8915 
8916 	SD_TRACE(SD_LOG_IO_PM, un,
8917 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
8918 
8919 	mutex_exit(&un->un_pm_mutex);
8920 
8921 	return (return_status);
8922 }
8923 
8924 
8925 /*
8926  *    Function: sd_pm_exit
8927  *
8928  * Description: Called at the completion of a command to manage busy
8929  *		status for the device. If the device becomes idle the
8930  *		PM framework is notified.
8931  *
8932  *     Context: Kernel thread context
8933  */
8934 
8935 static void
8936 sd_pm_exit(struct sd_lun *un)
8937 {
8938 	ASSERT(!mutex_owned(SD_MUTEX(un)));
8939 	ASSERT(!mutex_owned(&un->un_pm_mutex));
8940 
8941 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
8942 
8943 	/*
8944 	 * After attach the following flag is only read, so don't
8945 	 * take the penalty of acquiring a mutex for it.
8946 	 */
8947 	if (un->un_f_pm_is_enabled == TRUE) {
8948 
8949 		mutex_enter(&un->un_pm_mutex);
8950 		un->un_pm_count--;
8951 
8952 		SD_TRACE(SD_LOG_IO_PM, un,
8953 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
8954 
8955 		ASSERT(un->un_pm_count >= 0);
8956 		if (un->un_pm_count == 0) {
8957 			mutex_exit(&un->un_pm_mutex);
8958 
8959 			SD_TRACE(SD_LOG_IO_PM, un,
8960 			    "sd_pm_exit: idle component\n");
8961 
8962 			(void) pm_idle_component(SD_DEVINFO(un), 0);
8963 
8964 		} else {
8965 			mutex_exit(&un->un_pm_mutex);
8966 		}
8967 	}
8968 
8969 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
8970 }
8971 
8972 
8973 /*
8974  *    Function: sdopen
8975  *
8976  * Description: Driver's open(9e) entry point function.
8977  *
8978  *   Arguments: dev_i   - pointer to device number
8979  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
8980  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
8981  *		cred_p  - user credential pointer
8982  *
8983  * Return Code: EINVAL
8984  *		ENXIO
8985  *		EIO
8986  *		EROFS
8987  *		EBUSY
8988  *
8989  *     Context: Kernel thread context
8990  */
8991 /* ARGSUSED */
8992 static int
8993 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
8994 {
8995 	struct sd_lun	*un;
8996 	int		nodelay;
8997 	int		part;
8998 	uint64_t	partmask;
8999 	int		instance;
9000 	dev_t		dev;
9001 	int		rval = EIO;
9002 	diskaddr_t	nblks = 0;
9003 
9004 	/* Validate the open type */
9005 	if (otyp >= OTYPCNT) {
9006 		return (EINVAL);
9007 	}
9008 
9009 	dev = *dev_p;
9010 	instance = SDUNIT(dev);
9011 	mutex_enter(&sd_detach_mutex);
9012 
9013 	/*
9014 	 * Fail the open if there is no softstate for the instance, or
9015 	 * if another thread somewhere is trying to detach the instance.
9016 	 */
9017 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
9018 	    (un->un_detach_count != 0)) {
9019 		mutex_exit(&sd_detach_mutex);
9020 		/*
9021 		 * The probe cache only needs to be cleared when open (9e) fails
9022 		 * with ENXIO (4238046).
9023 		 */
9024 		/*
9025 		 * un-conditionally clearing probe cache is ok with
9026 		 * separate sd/ssd binaries
9027 		 * x86 platform can be an issue with both parallel
9028 		 * and fibre in 1 binary
9029 		 */
9030 		sd_scsi_clear_probe_cache();
9031 		return (ENXIO);
9032 	}
9033 
9034 	/*
9035 	 * The un_layer_count is to prevent another thread in specfs from
9036 	 * trying to detach the instance, which can happen when we are
9037 	 * called from a higher-layer driver instead of thru specfs.
9038 	 * This will not be needed when DDI provides a layered driver
9039 	 * interface that allows specfs to know that an instance is in
9040 	 * use by a layered driver & should not be detached.
9041 	 *
9042 	 * Note: the semantics for layered driver opens are exactly one
9043 	 * close for every open.
9044 	 */
9045 	if (otyp == OTYP_LYR) {
9046 		un->un_layer_count++;
9047 	}
9048 
9049 	/*
9050 	 * Keep a count of the current # of opens in progress. This is because
9051 	 * some layered drivers try to call us as a regular open. This can
9052 	 * cause problems that we cannot prevent, however by keeping this count
9053 	 * we can at least keep our open and detach routines from racing against
9054 	 * each other under such conditions.
9055 	 */
9056 	un->un_opens_in_progress++;
9057 	mutex_exit(&sd_detach_mutex);
9058 
9059 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
9060 	part	 = SDPART(dev);
9061 	partmask = 1 << part;
9062 
9063 	/*
9064 	 * We use a semaphore here in order to serialize
9065 	 * open and close requests on the device.
9066 	 */
9067 	sema_p(&un->un_semoclose);
9068 
9069 	mutex_enter(SD_MUTEX(un));
9070 
9071 	/*
9072 	 * All device accesses go thru sdstrategy() where we check
9073 	 * on suspend status but there could be a scsi_poll command,
9074 	 * which bypasses sdstrategy(), so we need to check pm
9075 	 * status.
9076 	 */
9077 
9078 	if (!nodelay) {
9079 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9080 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9081 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9082 		}
9083 
9084 		mutex_exit(SD_MUTEX(un));
9085 		if (sd_pm_entry(un) != DDI_SUCCESS) {
9086 			rval = EIO;
9087 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
9088 			    "sdopen: sd_pm_entry failed\n");
9089 			goto open_failed_with_pm;
9090 		}
9091 		mutex_enter(SD_MUTEX(un));
9092 	}
9093 
9094 	/* check for previous exclusive open */
9095 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
9096 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
9097 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
9098 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
9099 
9100 	if (un->un_exclopen & (partmask)) {
9101 		goto excl_open_fail;
9102 	}
9103 
9104 	if (flag & FEXCL) {
9105 		int i;
9106 		if (un->un_ocmap.lyropen[part]) {
9107 			goto excl_open_fail;
9108 		}
9109 		for (i = 0; i < (OTYPCNT - 1); i++) {
9110 			if (un->un_ocmap.regopen[i] & (partmask)) {
9111 				goto excl_open_fail;
9112 			}
9113 		}
9114 	}
9115 
9116 	/*
9117 	 * Check the write permission if this is a removable media device,
9118 	 * NDELAY has not been set, and writable permission is requested.
9119 	 *
9120 	 * Note: If NDELAY was set and this is write-protected media the WRITE
9121 	 * attempt will fail with EIO as part of the I/O processing. This is a
9122 	 * more permissive implementation that allows the open to succeed and
9123 	 * WRITE attempts to fail when appropriate.
9124 	 */
9125 	if (un->un_f_chk_wp_open) {
9126 		if ((flag & FWRITE) && (!nodelay)) {
9127 			mutex_exit(SD_MUTEX(un));
9128 			/*
9129 			 * Defer the check for write permission on writable
9130 			 * DVD drive till sdstrategy and will not fail open even
9131 			 * if FWRITE is set as the device can be writable
9132 			 * depending upon the media and the media can change
9133 			 * after the call to open().
9134 			 */
9135 			if (un->un_f_dvdram_writable_device == FALSE) {
9136 				if (ISCD(un) || sr_check_wp(dev)) {
9137 				rval = EROFS;
9138 				mutex_enter(SD_MUTEX(un));
9139 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9140 				    "write to cd or write protected media\n");
9141 				goto open_fail;
9142 				}
9143 			}
9144 			mutex_enter(SD_MUTEX(un));
9145 		}
9146 	}
9147 
9148 	/*
9149 	 * If opening in NDELAY/NONBLOCK mode, just return.
9150 	 * Check if disk is ready and has a valid geometry later.
9151 	 */
9152 	if (!nodelay) {
9153 		mutex_exit(SD_MUTEX(un));
9154 		rval = sd_ready_and_valid(un);
9155 		mutex_enter(SD_MUTEX(un));
9156 		/*
9157 		 * Fail if device is not ready or if the number of disk
9158 		 * blocks is zero or negative for non CD devices.
9159 		 */
9160 
9161 		nblks = 0;
9162 
9163 		if (rval == SD_READY_VALID && (!ISCD(un))) {
9164 			/* if cmlb_partinfo fails, nblks remains 0 */
9165 			mutex_exit(SD_MUTEX(un));
9166 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
9167 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
9168 			mutex_enter(SD_MUTEX(un));
9169 		}
9170 
9171 		if ((rval != SD_READY_VALID) ||
9172 		    (!ISCD(un) && nblks <= 0)) {
9173 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
9174 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9175 			    "device not ready or invalid disk block value\n");
9176 			goto open_fail;
9177 		}
9178 #if defined(__i386) || defined(__amd64)
9179 	} else {
9180 		uchar_t *cp;
9181 		/*
9182 		 * x86 requires special nodelay handling, so that p0 is
9183 		 * always defined and accessible.
9184 		 * Invalidate geometry only if device is not already open.
9185 		 */
9186 		cp = &un->un_ocmap.chkd[0];
9187 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9188 			if (*cp != (uchar_t)0) {
9189 				break;
9190 			}
9191 			cp++;
9192 		}
9193 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9194 			mutex_exit(SD_MUTEX(un));
9195 			cmlb_invalidate(un->un_cmlbhandle,
9196 			    (void *)SD_PATH_DIRECT);
9197 			mutex_enter(SD_MUTEX(un));
9198 		}
9199 
9200 #endif
9201 	}
9202 
9203 	if (otyp == OTYP_LYR) {
9204 		un->un_ocmap.lyropen[part]++;
9205 	} else {
9206 		un->un_ocmap.regopen[otyp] |= partmask;
9207 	}
9208 
9209 	/* Set up open and exclusive open flags */
9210 	if (flag & FEXCL) {
9211 		un->un_exclopen |= (partmask);
9212 	}
9213 
9214 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9215 	    "open of part %d type %d\n", part, otyp);
9216 
9217 	mutex_exit(SD_MUTEX(un));
9218 	if (!nodelay) {
9219 		sd_pm_exit(un);
9220 	}
9221 
9222 	sema_v(&un->un_semoclose);
9223 
9224 	mutex_enter(&sd_detach_mutex);
9225 	un->un_opens_in_progress--;
9226 	mutex_exit(&sd_detach_mutex);
9227 
9228 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
9229 	return (DDI_SUCCESS);
9230 
9231 excl_open_fail:
9232 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
9233 	rval = EBUSY;
9234 
9235 open_fail:
9236 	mutex_exit(SD_MUTEX(un));
9237 
9238 	/*
9239 	 * On a failed open we must exit the pm management.
9240 	 */
9241 	if (!nodelay) {
9242 		sd_pm_exit(un);
9243 	}
9244 open_failed_with_pm:
9245 	sema_v(&un->un_semoclose);
9246 
9247 	mutex_enter(&sd_detach_mutex);
9248 	un->un_opens_in_progress--;
9249 	if (otyp == OTYP_LYR) {
9250 		un->un_layer_count--;
9251 	}
9252 	mutex_exit(&sd_detach_mutex);
9253 
9254 	return (rval);
9255 }
9256 
9257 
9258 /*
9259  *    Function: sdclose
9260  *
9261  * Description: Driver's close(9e) entry point function.
9262  *
9263  *   Arguments: dev    - device number
9264  *		flag   - file status flag, informational only
9265  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9266  *		cred_p - user credential pointer
9267  *
9268  * Return Code: ENXIO
9269  *
9270  *     Context: Kernel thread context
9271  */
9272 /* ARGSUSED */
9273 static int
9274 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
9275 {
9276 	struct sd_lun	*un;
9277 	uchar_t		*cp;
9278 	int		part;
9279 	int		nodelay;
9280 	int		rval = 0;
9281 
9282 	/* Validate the open type */
9283 	if (otyp >= OTYPCNT) {
9284 		return (ENXIO);
9285 	}
9286 
9287 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9288 		return (ENXIO);
9289 	}
9290 
9291 	part = SDPART(dev);
9292 	nodelay = flag & (FNDELAY | FNONBLOCK);
9293 
9294 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
9295 	    "sdclose: close of part %d type %d\n", part, otyp);
9296 
9297 	/*
9298 	 * We use a semaphore here in order to serialize
9299 	 * open and close requests on the device.
9300 	 */
9301 	sema_p(&un->un_semoclose);
9302 
9303 	mutex_enter(SD_MUTEX(un));
9304 
9305 	/* Don't proceed if power is being changed. */
9306 	while (un->un_state == SD_STATE_PM_CHANGING) {
9307 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9308 	}
9309 
9310 	if (un->un_exclopen & (1 << part)) {
9311 		un->un_exclopen &= ~(1 << part);
9312 	}
9313 
9314 	/* Update the open partition map */
9315 	if (otyp == OTYP_LYR) {
9316 		un->un_ocmap.lyropen[part] -= 1;
9317 	} else {
9318 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
9319 	}
9320 
9321 	cp = &un->un_ocmap.chkd[0];
9322 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9323 		if (*cp != NULL) {
9324 			break;
9325 		}
9326 		cp++;
9327 	}
9328 
9329 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9330 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
9331 
9332 		/*
9333 		 * We avoid persistance upon the last close, and set
9334 		 * the throttle back to the maximum.
9335 		 */
9336 		un->un_throttle = un->un_saved_throttle;
9337 
9338 		if (un->un_state == SD_STATE_OFFLINE) {
9339 			if (un->un_f_is_fibre == FALSE) {
9340 				scsi_log(SD_DEVINFO(un), sd_label,
9341 				    CE_WARN, "offline\n");
9342 			}
9343 			mutex_exit(SD_MUTEX(un));
9344 			cmlb_invalidate(un->un_cmlbhandle,
9345 			    (void *)SD_PATH_DIRECT);
9346 			mutex_enter(SD_MUTEX(un));
9347 
9348 		} else {
9349 			/*
9350 			 * Flush any outstanding writes in NVRAM cache.
9351 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
9352 			 * cmd, it may not work for non-Pluto devices.
9353 			 * SYNCHRONIZE CACHE is not required for removables,
9354 			 * except DVD-RAM drives.
9355 			 *
9356 			 * Also note: because SYNCHRONIZE CACHE is currently
9357 			 * the only command issued here that requires the
9358 			 * drive be powered up, only do the power up before
9359 			 * sending the Sync Cache command. If additional
9360 			 * commands are added which require a powered up
9361 			 * drive, the following sequence may have to change.
9362 			 *
9363 			 * And finally, note that parallel SCSI on SPARC
9364 			 * only issues a Sync Cache to DVD-RAM, a newly
9365 			 * supported device.
9366 			 */
9367 #if defined(__i386) || defined(__amd64)
9368 			if (un->un_f_sync_cache_supported ||
9369 			    un->un_f_dvdram_writable_device == TRUE) {
9370 #else
9371 			if (un->un_f_dvdram_writable_device == TRUE) {
9372 #endif
9373 				mutex_exit(SD_MUTEX(un));
9374 				if (sd_pm_entry(un) == DDI_SUCCESS) {
9375 					rval =
9376 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
9377 					    NULL);
9378 					/* ignore error if not supported */
9379 					if (rval == ENOTSUP) {
9380 						rval = 0;
9381 					} else if (rval != 0) {
9382 						rval = EIO;
9383 					}
9384 					sd_pm_exit(un);
9385 				} else {
9386 					rval = EIO;
9387 				}
9388 				mutex_enter(SD_MUTEX(un));
9389 			}
9390 
9391 			/*
9392 			 * For devices which supports DOOR_LOCK, send an ALLOW
9393 			 * MEDIA REMOVAL command, but don't get upset if it
9394 			 * fails. We need to raise the power of the drive before
9395 			 * we can call sd_send_scsi_DOORLOCK()
9396 			 */
9397 			if (un->un_f_doorlock_supported) {
9398 				mutex_exit(SD_MUTEX(un));
9399 				if (sd_pm_entry(un) == DDI_SUCCESS) {
9400 					rval = sd_send_scsi_DOORLOCK(un,
9401 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
9402 
9403 					sd_pm_exit(un);
9404 					if (ISCD(un) && (rval != 0) &&
9405 					    (nodelay != 0)) {
9406 						rval = ENXIO;
9407 					}
9408 				} else {
9409 					rval = EIO;
9410 				}
9411 				mutex_enter(SD_MUTEX(un));
9412 			}
9413 
9414 			/*
9415 			 * If a device has removable media, invalidate all
9416 			 * parameters related to media, such as geometry,
9417 			 * blocksize, and blockcount.
9418 			 */
9419 			if (un->un_f_has_removable_media) {
9420 				sr_ejected(un);
9421 			}
9422 
9423 			/*
9424 			 * Destroy the cache (if it exists) which was
9425 			 * allocated for the write maps since this is
9426 			 * the last close for this media.
9427 			 */
9428 			if (un->un_wm_cache) {
9429 				/*
9430 				 * Check if there are pending commands.
9431 				 * and if there are give a warning and
9432 				 * do not destroy the cache.
9433 				 */
9434 				if (un->un_ncmds_in_driver > 0) {
9435 					scsi_log(SD_DEVINFO(un),
9436 					    sd_label, CE_WARN,
9437 					    "Unable to clean up memory "
9438 					    "because of pending I/O\n");
9439 				} else {
9440 					kmem_cache_destroy(
9441 					    un->un_wm_cache);
9442 					un->un_wm_cache = NULL;
9443 				}
9444 			}
9445 		}
9446 	}
9447 
9448 	mutex_exit(SD_MUTEX(un));
9449 	sema_v(&un->un_semoclose);
9450 
9451 	if (otyp == OTYP_LYR) {
9452 		mutex_enter(&sd_detach_mutex);
9453 		/*
9454 		 * The detach routine may run when the layer count
9455 		 * drops to zero.
9456 		 */
9457 		un->un_layer_count--;
9458 		mutex_exit(&sd_detach_mutex);
9459 	}
9460 
9461 	return (rval);
9462 }
9463 
9464 
9465 /*
9466  *    Function: sd_ready_and_valid
9467  *
9468  * Description: Test if device is ready and has a valid geometry.
9469  *
9470  *   Arguments: dev - device number
9471  *		un  - driver soft state (unit) structure
9472  *
9473  * Return Code: SD_READY_VALID		ready and valid label
9474  *		SD_NOT_READY_VALID	not ready, no label
9475  *		SD_RESERVED_BY_OTHERS	reservation conflict
9476  *
9477  *     Context: Never called at interrupt context.
9478  */
9479 
9480 static int
9481 sd_ready_and_valid(struct sd_lun *un)
9482 {
9483 	struct sd_errstats	*stp;
9484 	uint64_t		capacity;
9485 	uint_t			lbasize;
9486 	int			rval = SD_READY_VALID;
9487 	char			name_str[48];
9488 	int			is_valid;
9489 
9490 	ASSERT(un != NULL);
9491 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9492 
9493 	mutex_enter(SD_MUTEX(un));
9494 	/*
9495 	 * If a device has removable media, we must check if media is
9496 	 * ready when checking if this device is ready and valid.
9497 	 */
9498 	if (un->un_f_has_removable_media) {
9499 		mutex_exit(SD_MUTEX(un));
9500 		if (sd_send_scsi_TEST_UNIT_READY(un, 0) != 0) {
9501 			rval = SD_NOT_READY_VALID;
9502 			mutex_enter(SD_MUTEX(un));
9503 			goto done;
9504 		}
9505 
9506 		is_valid = SD_IS_VALID_LABEL(un);
9507 		mutex_enter(SD_MUTEX(un));
9508 		if (!is_valid ||
9509 		    (un->un_f_blockcount_is_valid == FALSE) ||
9510 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
9511 
9512 			/* capacity has to be read every open. */
9513 			mutex_exit(SD_MUTEX(un));
9514 			if (sd_send_scsi_READ_CAPACITY(un, &capacity,
9515 			    &lbasize, SD_PATH_DIRECT) != 0) {
9516 				cmlb_invalidate(un->un_cmlbhandle,
9517 				    (void *)SD_PATH_DIRECT);
9518 				mutex_enter(SD_MUTEX(un));
9519 				rval = SD_NOT_READY_VALID;
9520 				goto done;
9521 			} else {
9522 				mutex_enter(SD_MUTEX(un));
9523 				sd_update_block_info(un, lbasize, capacity);
9524 			}
9525 		}
9526 
9527 		/*
9528 		 * Check if the media in the device is writable or not.
9529 		 */
9530 		if (!is_valid && ISCD(un)) {
9531 			sd_check_for_writable_cd(un, SD_PATH_DIRECT);
9532 		}
9533 
9534 	} else {
9535 		/*
9536 		 * Do a test unit ready to clear any unit attention from non-cd
9537 		 * devices.
9538 		 */
9539 		mutex_exit(SD_MUTEX(un));
9540 		(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
9541 		mutex_enter(SD_MUTEX(un));
9542 	}
9543 
9544 
9545 	/*
9546 	 * If this is a non 512 block device, allocate space for
9547 	 * the wmap cache. This is being done here since every time
9548 	 * a media is changed this routine will be called and the
9549 	 * block size is a function of media rather than device.
9550 	 */
9551 	if (un->un_f_non_devbsize_supported && NOT_DEVBSIZE(un)) {
9552 		if (!(un->un_wm_cache)) {
9553 			(void) snprintf(name_str, sizeof (name_str),
9554 			    "%s%d_cache",
9555 			    ddi_driver_name(SD_DEVINFO(un)),
9556 			    ddi_get_instance(SD_DEVINFO(un)));
9557 			un->un_wm_cache = kmem_cache_create(
9558 			    name_str, sizeof (struct sd_w_map),
9559 			    8, sd_wm_cache_constructor,
9560 			    sd_wm_cache_destructor, NULL,
9561 			    (void *)un, NULL, 0);
9562 			if (!(un->un_wm_cache)) {
9563 					rval = ENOMEM;
9564 					goto done;
9565 			}
9566 		}
9567 	}
9568 
9569 	if (un->un_state == SD_STATE_NORMAL) {
9570 		/*
9571 		 * If the target is not yet ready here (defined by a TUR
9572 		 * failure), invalidate the geometry and print an 'offline'
9573 		 * message. This is a legacy message, as the state of the
9574 		 * target is not actually changed to SD_STATE_OFFLINE.
9575 		 *
9576 		 * If the TUR fails for EACCES (Reservation Conflict),
9577 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
9578 		 * reservation conflict. If the TUR fails for other
9579 		 * reasons, SD_NOT_READY_VALID will be returned.
9580 		 */
9581 		int err;
9582 
9583 		mutex_exit(SD_MUTEX(un));
9584 		err = sd_send_scsi_TEST_UNIT_READY(un, 0);
9585 		mutex_enter(SD_MUTEX(un));
9586 
9587 		if (err != 0) {
9588 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
9589 			    "offline or reservation conflict\n");
9590 			mutex_exit(SD_MUTEX(un));
9591 			cmlb_invalidate(un->un_cmlbhandle,
9592 			    (void *)SD_PATH_DIRECT);
9593 			mutex_enter(SD_MUTEX(un));
9594 			if (err == EACCES) {
9595 				rval = SD_RESERVED_BY_OTHERS;
9596 			} else {
9597 				rval = SD_NOT_READY_VALID;
9598 			}
9599 			goto done;
9600 		}
9601 	}
9602 
9603 	if (un->un_f_format_in_progress == FALSE) {
9604 		mutex_exit(SD_MUTEX(un));
9605 		if (cmlb_validate(un->un_cmlbhandle, 0,
9606 		    (void *)SD_PATH_DIRECT) != 0) {
9607 			rval = SD_NOT_READY_VALID;
9608 			mutex_enter(SD_MUTEX(un));
9609 			goto done;
9610 		}
9611 		if (un->un_f_pkstats_enabled) {
9612 			sd_set_pstats(un);
9613 			SD_TRACE(SD_LOG_IO_PARTITION, un,
9614 			    "sd_ready_and_valid: un:0x%p pstats created and "
9615 			    "set\n", un);
9616 		}
9617 		mutex_enter(SD_MUTEX(un));
9618 	}
9619 
9620 	/*
9621 	 * If this device supports DOOR_LOCK command, try and send
9622 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
9623 	 * if it fails. For a CD, however, it is an error
9624 	 */
9625 	if (un->un_f_doorlock_supported) {
9626 		mutex_exit(SD_MUTEX(un));
9627 		if ((sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
9628 		    SD_PATH_DIRECT) != 0) && ISCD(un)) {
9629 			rval = SD_NOT_READY_VALID;
9630 			mutex_enter(SD_MUTEX(un));
9631 			goto done;
9632 		}
9633 		mutex_enter(SD_MUTEX(un));
9634 	}
9635 
9636 	/* The state has changed, inform the media watch routines */
9637 	un->un_mediastate = DKIO_INSERTED;
9638 	cv_broadcast(&un->un_state_cv);
9639 	rval = SD_READY_VALID;
9640 
9641 done:
9642 
9643 	/*
9644 	 * Initialize the capacity kstat value, if no media previously
9645 	 * (capacity kstat is 0) and a media has been inserted
9646 	 * (un_blockcount > 0).
9647 	 */
9648 	if (un->un_errstats != NULL) {
9649 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
9650 		if ((stp->sd_capacity.value.ui64 == 0) &&
9651 		    (un->un_f_blockcount_is_valid == TRUE)) {
9652 			stp->sd_capacity.value.ui64 =
9653 			    (uint64_t)((uint64_t)un->un_blockcount *
9654 			    un->un_sys_blocksize);
9655 		}
9656 	}
9657 
9658 	mutex_exit(SD_MUTEX(un));
9659 	return (rval);
9660 }
9661 
9662 
9663 /*
9664  *    Function: sdmin
9665  *
9666  * Description: Routine to limit the size of a data transfer. Used in
9667  *		conjunction with physio(9F).
9668  *
9669  *   Arguments: bp - pointer to the indicated buf(9S) struct.
9670  *
9671  *     Context: Kernel thread context.
9672  */
9673 
9674 static void
9675 sdmin(struct buf *bp)
9676 {
9677 	struct sd_lun	*un;
9678 	int		instance;
9679 
9680 	instance = SDUNIT(bp->b_edev);
9681 
9682 	un = ddi_get_soft_state(sd_state, instance);
9683 	ASSERT(un != NULL);
9684 
9685 	if (bp->b_bcount > un->un_max_xfer_size) {
9686 		bp->b_bcount = un->un_max_xfer_size;
9687 	}
9688 }
9689 
9690 
9691 /*
9692  *    Function: sdread
9693  *
9694  * Description: Driver's read(9e) entry point function.
9695  *
9696  *   Arguments: dev   - device number
9697  *		uio   - structure pointer describing where data is to be stored
9698  *			in user's space
9699  *		cred_p  - user credential pointer
9700  *
9701  * Return Code: ENXIO
9702  *		EIO
9703  *		EINVAL
9704  *		value returned by physio
9705  *
9706  *     Context: Kernel thread context.
9707  */
9708 /* ARGSUSED */
9709 static int
9710 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
9711 {
9712 	struct sd_lun	*un = NULL;
9713 	int		secmask;
9714 	int		err;
9715 
9716 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9717 		return (ENXIO);
9718 	}
9719 
9720 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9721 
9722 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9723 		mutex_enter(SD_MUTEX(un));
9724 		/*
9725 		 * Because the call to sd_ready_and_valid will issue I/O we
9726 		 * must wait here if either the device is suspended or
9727 		 * if it's power level is changing.
9728 		 */
9729 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9730 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9731 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9732 		}
9733 		un->un_ncmds_in_driver++;
9734 		mutex_exit(SD_MUTEX(un));
9735 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9736 			mutex_enter(SD_MUTEX(un));
9737 			un->un_ncmds_in_driver--;
9738 			ASSERT(un->un_ncmds_in_driver >= 0);
9739 			mutex_exit(SD_MUTEX(un));
9740 			return (EIO);
9741 		}
9742 		mutex_enter(SD_MUTEX(un));
9743 		un->un_ncmds_in_driver--;
9744 		ASSERT(un->un_ncmds_in_driver >= 0);
9745 		mutex_exit(SD_MUTEX(un));
9746 	}
9747 
9748 	/*
9749 	 * Read requests are restricted to multiples of the system block size.
9750 	 */
9751 	secmask = un->un_sys_blocksize - 1;
9752 
9753 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9754 		SD_ERROR(SD_LOG_READ_WRITE, un,
9755 		    "sdread: file offset not modulo %d\n",
9756 		    un->un_sys_blocksize);
9757 		err = EINVAL;
9758 	} else if (uio->uio_iov->iov_len & (secmask)) {
9759 		SD_ERROR(SD_LOG_READ_WRITE, un,
9760 		    "sdread: transfer length not modulo %d\n",
9761 		    un->un_sys_blocksize);
9762 		err = EINVAL;
9763 	} else {
9764 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
9765 	}
9766 	return (err);
9767 }
9768 
9769 
9770 /*
9771  *    Function: sdwrite
9772  *
9773  * Description: Driver's write(9e) entry point function.
9774  *
9775  *   Arguments: dev   - device number
9776  *		uio   - structure pointer describing where data is stored in
9777  *			user's space
9778  *		cred_p  - user credential pointer
9779  *
9780  * Return Code: ENXIO
9781  *		EIO
9782  *		EINVAL
9783  *		value returned by physio
9784  *
9785  *     Context: Kernel thread context.
9786  */
9787 /* ARGSUSED */
9788 static int
9789 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
9790 {
9791 	struct sd_lun	*un = NULL;
9792 	int		secmask;
9793 	int		err;
9794 
9795 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9796 		return (ENXIO);
9797 	}
9798 
9799 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9800 
9801 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9802 		mutex_enter(SD_MUTEX(un));
9803 		/*
9804 		 * Because the call to sd_ready_and_valid will issue I/O we
9805 		 * must wait here if either the device is suspended or
9806 		 * if it's power level is changing.
9807 		 */
9808 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9809 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9810 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9811 		}
9812 		un->un_ncmds_in_driver++;
9813 		mutex_exit(SD_MUTEX(un));
9814 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9815 			mutex_enter(SD_MUTEX(un));
9816 			un->un_ncmds_in_driver--;
9817 			ASSERT(un->un_ncmds_in_driver >= 0);
9818 			mutex_exit(SD_MUTEX(un));
9819 			return (EIO);
9820 		}
9821 		mutex_enter(SD_MUTEX(un));
9822 		un->un_ncmds_in_driver--;
9823 		ASSERT(un->un_ncmds_in_driver >= 0);
9824 		mutex_exit(SD_MUTEX(un));
9825 	}
9826 
9827 	/*
9828 	 * Write requests are restricted to multiples of the system block size.
9829 	 */
9830 	secmask = un->un_sys_blocksize - 1;
9831 
9832 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9833 		SD_ERROR(SD_LOG_READ_WRITE, un,
9834 		    "sdwrite: file offset not modulo %d\n",
9835 		    un->un_sys_blocksize);
9836 		err = EINVAL;
9837 	} else if (uio->uio_iov->iov_len & (secmask)) {
9838 		SD_ERROR(SD_LOG_READ_WRITE, un,
9839 		    "sdwrite: transfer length not modulo %d\n",
9840 		    un->un_sys_blocksize);
9841 		err = EINVAL;
9842 	} else {
9843 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
9844 	}
9845 	return (err);
9846 }
9847 
9848 
9849 /*
9850  *    Function: sdaread
9851  *
9852  * Description: Driver's aread(9e) entry point function.
9853  *
9854  *   Arguments: dev   - device number
9855  *		aio   - structure pointer describing where data is to be stored
9856  *		cred_p  - user credential pointer
9857  *
9858  * Return Code: ENXIO
9859  *		EIO
9860  *		EINVAL
9861  *		value returned by aphysio
9862  *
9863  *     Context: Kernel thread context.
9864  */
9865 /* ARGSUSED */
9866 static int
9867 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
9868 {
9869 	struct sd_lun	*un = NULL;
9870 	struct uio	*uio = aio->aio_uio;
9871 	int		secmask;
9872 	int		err;
9873 
9874 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9875 		return (ENXIO);
9876 	}
9877 
9878 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9879 
9880 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9881 		mutex_enter(SD_MUTEX(un));
9882 		/*
9883 		 * Because the call to sd_ready_and_valid will issue I/O we
9884 		 * must wait here if either the device is suspended or
9885 		 * if it's power level is changing.
9886 		 */
9887 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9888 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9889 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9890 		}
9891 		un->un_ncmds_in_driver++;
9892 		mutex_exit(SD_MUTEX(un));
9893 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9894 			mutex_enter(SD_MUTEX(un));
9895 			un->un_ncmds_in_driver--;
9896 			ASSERT(un->un_ncmds_in_driver >= 0);
9897 			mutex_exit(SD_MUTEX(un));
9898 			return (EIO);
9899 		}
9900 		mutex_enter(SD_MUTEX(un));
9901 		un->un_ncmds_in_driver--;
9902 		ASSERT(un->un_ncmds_in_driver >= 0);
9903 		mutex_exit(SD_MUTEX(un));
9904 	}
9905 
9906 	/*
9907 	 * Read requests are restricted to multiples of the system block size.
9908 	 */
9909 	secmask = un->un_sys_blocksize - 1;
9910 
9911 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9912 		SD_ERROR(SD_LOG_READ_WRITE, un,
9913 		    "sdaread: file offset not modulo %d\n",
9914 		    un->un_sys_blocksize);
9915 		err = EINVAL;
9916 	} else if (uio->uio_iov->iov_len & (secmask)) {
9917 		SD_ERROR(SD_LOG_READ_WRITE, un,
9918 		    "sdaread: transfer length not modulo %d\n",
9919 		    un->un_sys_blocksize);
9920 		err = EINVAL;
9921 	} else {
9922 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
9923 	}
9924 	return (err);
9925 }
9926 
9927 
9928 /*
9929  *    Function: sdawrite
9930  *
9931  * Description: Driver's awrite(9e) entry point function.
9932  *
9933  *   Arguments: dev   - device number
9934  *		aio   - structure pointer describing where data is stored
9935  *		cred_p  - user credential pointer
9936  *
9937  * Return Code: ENXIO
9938  *		EIO
9939  *		EINVAL
9940  *		value returned by aphysio
9941  *
9942  *     Context: Kernel thread context.
9943  */
9944 /* ARGSUSED */
9945 static int
9946 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
9947 {
9948 	struct sd_lun	*un = NULL;
9949 	struct uio	*uio = aio->aio_uio;
9950 	int		secmask;
9951 	int		err;
9952 
9953 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9954 		return (ENXIO);
9955 	}
9956 
9957 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9958 
9959 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9960 		mutex_enter(SD_MUTEX(un));
9961 		/*
9962 		 * Because the call to sd_ready_and_valid will issue I/O we
9963 		 * must wait here if either the device is suspended or
9964 		 * if it's power level is changing.
9965 		 */
9966 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9967 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9968 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9969 		}
9970 		un->un_ncmds_in_driver++;
9971 		mutex_exit(SD_MUTEX(un));
9972 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9973 			mutex_enter(SD_MUTEX(un));
9974 			un->un_ncmds_in_driver--;
9975 			ASSERT(un->un_ncmds_in_driver >= 0);
9976 			mutex_exit(SD_MUTEX(un));
9977 			return (EIO);
9978 		}
9979 		mutex_enter(SD_MUTEX(un));
9980 		un->un_ncmds_in_driver--;
9981 		ASSERT(un->un_ncmds_in_driver >= 0);
9982 		mutex_exit(SD_MUTEX(un));
9983 	}
9984 
9985 	/*
9986 	 * Write requests are restricted to multiples of the system block size.
9987 	 */
9988 	secmask = un->un_sys_blocksize - 1;
9989 
9990 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9991 		SD_ERROR(SD_LOG_READ_WRITE, un,
9992 		    "sdawrite: file offset not modulo %d\n",
9993 		    un->un_sys_blocksize);
9994 		err = EINVAL;
9995 	} else if (uio->uio_iov->iov_len & (secmask)) {
9996 		SD_ERROR(SD_LOG_READ_WRITE, un,
9997 		    "sdawrite: transfer length not modulo %d\n",
9998 		    un->un_sys_blocksize);
9999 		err = EINVAL;
10000 	} else {
10001 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
10002 	}
10003 	return (err);
10004 }
10005 
10006 
10007 
10008 
10009 
10010 /*
10011  * Driver IO processing follows the following sequence:
10012  *
10013  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
10014  *         |                |                     ^
10015  *         v                v                     |
10016  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
10017  *         |                |                     |                   |
10018  *         v                |                     |                   |
10019  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
10020  *         |                |                     ^                   ^
10021  *         v                v                     |                   |
10022  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
10023  *         |                |                     |                   |
10024  *     +---+                |                     +------------+      +-------+
10025  *     |                    |                                  |              |
10026  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10027  *     |                    v                                  |              |
10028  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
10029  *     |                    |                                  ^              |
10030  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10031  *     |                    v                                  |              |
10032  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
10033  *     |                    |                                  ^              |
10034  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10035  *     |                    v                                  |              |
10036  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
10037  *     |                    |                                  ^              |
10038  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
10039  *     |                    v                                  |              |
10040  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
10041  *     |                    |                                  ^              |
10042  *     |                    |                                  |              |
10043  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
10044  *                          |                           ^
10045  *                          v                           |
10046  *                   sd_core_iostart()                  |
10047  *                          |                           |
10048  *                          |                           +------>(*destroypkt)()
10049  *                          +-> sd_start_cmds() <-+     |           |
10050  *                          |                     |     |           v
10051  *                          |                     |     |  scsi_destroy_pkt(9F)
10052  *                          |                     |     |
10053  *                          +->(*initpkt)()       +- sdintr()
10054  *                          |  |                        |  |
10055  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
10056  *                          |  +-> scsi_setup_cdb(9F)   |
10057  *                          |                           |
10058  *                          +--> scsi_transport(9F)     |
10059  *                                     |                |
10060  *                                     +----> SCSA ---->+
10061  *
10062  *
10063  * This code is based upon the following presumptions:
10064  *
10065  *   - iostart and iodone functions operate on buf(9S) structures. These
10066  *     functions perform the necessary operations on the buf(9S) and pass
10067  *     them along to the next function in the chain by using the macros
10068  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
10069  *     (for iodone side functions).
10070  *
10071  *   - The iostart side functions may sleep. The iodone side functions
10072  *     are called under interrupt context and may NOT sleep. Therefore
10073  *     iodone side functions also may not call iostart side functions.
10074  *     (NOTE: iostart side functions should NOT sleep for memory, as
10075  *     this could result in deadlock.)
10076  *
10077  *   - An iostart side function may call its corresponding iodone side
10078  *     function directly (if necessary).
10079  *
10080  *   - In the event of an error, an iostart side function can return a buf(9S)
10081  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
10082  *     b_error in the usual way of course).
10083  *
10084  *   - The taskq mechanism may be used by the iodone side functions to dispatch
10085  *     requests to the iostart side functions.  The iostart side functions in
10086  *     this case would be called under the context of a taskq thread, so it's
10087  *     OK for them to block/sleep/spin in this case.
10088  *
10089  *   - iostart side functions may allocate "shadow" buf(9S) structs and
10090  *     pass them along to the next function in the chain.  The corresponding
10091  *     iodone side functions must coalesce the "shadow" bufs and return
10092  *     the "original" buf to the next higher layer.
10093  *
10094  *   - The b_private field of the buf(9S) struct holds a pointer to
10095  *     an sd_xbuf struct, which contains information needed to
10096  *     construct the scsi_pkt for the command.
10097  *
10098  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
10099  *     layer must acquire & release the SD_MUTEX(un) as needed.
10100  */
10101 
10102 
10103 /*
10104  * Create taskq for all targets in the system. This is created at
10105  * _init(9E) and destroyed at _fini(9E).
10106  *
10107  * Note: here we set the minalloc to a reasonably high number to ensure that
10108  * we will have an adequate supply of task entries available at interrupt time.
10109  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
10110  * sd_create_taskq().  Since we do not want to sleep for allocations at
10111  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
10112  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
10113  * requests any one instant in time.
10114  */
10115 #define	SD_TASKQ_NUMTHREADS	8
10116 #define	SD_TASKQ_MINALLOC	256
10117 #define	SD_TASKQ_MAXALLOC	256
10118 
10119 static taskq_t	*sd_tq = NULL;
10120 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
10121 
10122 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
10123 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
10124 
10125 /*
10126  * The following task queue is being created for the write part of
10127  * read-modify-write of non-512 block size devices.
10128  * Limit the number of threads to 1 for now. This number has been chosen
10129  * considering the fact that it applies only to dvd ram drives/MO drives
10130  * currently. Performance for which is not main criteria at this stage.
10131  * Note: It needs to be explored if we can use a single taskq in future
10132  */
10133 #define	SD_WMR_TASKQ_NUMTHREADS	1
10134 static taskq_t	*sd_wmr_tq = NULL;
10135 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
10136 
10137 /*
10138  *    Function: sd_taskq_create
10139  *
10140  * Description: Create taskq thread(s) and preallocate task entries
10141  *
10142  * Return Code: Returns a pointer to the allocated taskq_t.
10143  *
10144  *     Context: Can sleep. Requires blockable context.
10145  *
10146  *       Notes: - The taskq() facility currently is NOT part of the DDI.
10147  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
10148  *		- taskq_create() will block for memory, also it will panic
10149  *		  if it cannot create the requested number of threads.
10150  *		- Currently taskq_create() creates threads that cannot be
10151  *		  swapped.
10152  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
10153  *		  supply of taskq entries at interrupt time (ie, so that we
10154  *		  do not have to sleep for memory)
10155  */
10156 
10157 static void
10158 sd_taskq_create(void)
10159 {
10160 	char	taskq_name[TASKQ_NAMELEN];
10161 
10162 	ASSERT(sd_tq == NULL);
10163 	ASSERT(sd_wmr_tq == NULL);
10164 
10165 	(void) snprintf(taskq_name, sizeof (taskq_name),
10166 	    "%s_drv_taskq", sd_label);
10167 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
10168 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10169 	    TASKQ_PREPOPULATE));
10170 
10171 	(void) snprintf(taskq_name, sizeof (taskq_name),
10172 	    "%s_rmw_taskq", sd_label);
10173 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
10174 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10175 	    TASKQ_PREPOPULATE));
10176 }
10177 
10178 
10179 /*
10180  *    Function: sd_taskq_delete
10181  *
10182  * Description: Complementary cleanup routine for sd_taskq_create().
10183  *
10184  *     Context: Kernel thread context.
10185  */
10186 
10187 static void
10188 sd_taskq_delete(void)
10189 {
10190 	ASSERT(sd_tq != NULL);
10191 	ASSERT(sd_wmr_tq != NULL);
10192 	taskq_destroy(sd_tq);
10193 	taskq_destroy(sd_wmr_tq);
10194 	sd_tq = NULL;
10195 	sd_wmr_tq = NULL;
10196 }
10197 
10198 
10199 /*
10200  *    Function: sdstrategy
10201  *
10202  * Description: Driver's strategy (9E) entry point function.
10203  *
10204  *   Arguments: bp - pointer to buf(9S)
10205  *
10206  * Return Code: Always returns zero
10207  *
10208  *     Context: Kernel thread context.
10209  */
10210 
10211 static int
10212 sdstrategy(struct buf *bp)
10213 {
10214 	struct sd_lun *un;
10215 
10216 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
10217 	if (un == NULL) {
10218 		bioerror(bp, EIO);
10219 		bp->b_resid = bp->b_bcount;
10220 		biodone(bp);
10221 		return (0);
10222 	}
10223 	/* As was done in the past, fail new cmds. if state is dumping. */
10224 	if (un->un_state == SD_STATE_DUMPING) {
10225 		bioerror(bp, ENXIO);
10226 		bp->b_resid = bp->b_bcount;
10227 		biodone(bp);
10228 		return (0);
10229 	}
10230 
10231 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10232 
10233 	/*
10234 	 * Commands may sneak in while we released the mutex in
10235 	 * DDI_SUSPEND, we should block new commands. However, old
10236 	 * commands that are still in the driver at this point should
10237 	 * still be allowed to drain.
10238 	 */
10239 	mutex_enter(SD_MUTEX(un));
10240 	/*
10241 	 * Must wait here if either the device is suspended or
10242 	 * if it's power level is changing.
10243 	 */
10244 	while ((un->un_state == SD_STATE_SUSPENDED) ||
10245 	    (un->un_state == SD_STATE_PM_CHANGING)) {
10246 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10247 	}
10248 
10249 	un->un_ncmds_in_driver++;
10250 
10251 	/*
10252 	 * atapi: Since we are running the CD for now in PIO mode we need to
10253 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
10254 	 * the HBA's init_pkt routine.
10255 	 */
10256 	if (un->un_f_cfg_is_atapi == TRUE) {
10257 		mutex_exit(SD_MUTEX(un));
10258 		bp_mapin(bp);
10259 		mutex_enter(SD_MUTEX(un));
10260 	}
10261 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
10262 	    un->un_ncmds_in_driver);
10263 
10264 	mutex_exit(SD_MUTEX(un));
10265 
10266 	/*
10267 	 * This will (eventually) allocate the sd_xbuf area and
10268 	 * call sd_xbuf_strategy().  We just want to return the
10269 	 * result of ddi_xbuf_qstrategy so that we have an opt-
10270 	 * imized tail call which saves us a stack frame.
10271 	 */
10272 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
10273 }
10274 
10275 
10276 /*
10277  *    Function: sd_xbuf_strategy
10278  *
10279  * Description: Function for initiating IO operations via the
10280  *		ddi_xbuf_qstrategy() mechanism.
10281  *
10282  *     Context: Kernel thread context.
10283  */
10284 
10285 static void
10286 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
10287 {
10288 	struct sd_lun *un = arg;
10289 
10290 	ASSERT(bp != NULL);
10291 	ASSERT(xp != NULL);
10292 	ASSERT(un != NULL);
10293 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10294 
10295 	/*
10296 	 * Initialize the fields in the xbuf and save a pointer to the
10297 	 * xbuf in bp->b_private.
10298 	 */
10299 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
10300 
10301 	/* Send the buf down the iostart chain */
10302 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
10303 }
10304 
10305 
10306 /*
10307  *    Function: sd_xbuf_init
10308  *
10309  * Description: Prepare the given sd_xbuf struct for use.
10310  *
10311  *   Arguments: un - ptr to softstate
10312  *		bp - ptr to associated buf(9S)
10313  *		xp - ptr to associated sd_xbuf
10314  *		chain_type - IO chain type to use:
10315  *			SD_CHAIN_NULL
10316  *			SD_CHAIN_BUFIO
10317  *			SD_CHAIN_USCSI
10318  *			SD_CHAIN_DIRECT
10319  *			SD_CHAIN_DIRECT_PRIORITY
10320  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
10321  *			initialization; may be NULL if none.
10322  *
10323  *     Context: Kernel thread context
10324  */
10325 
10326 static void
10327 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
10328 	uchar_t chain_type, void *pktinfop)
10329 {
10330 	int index;
10331 
10332 	ASSERT(un != NULL);
10333 	ASSERT(bp != NULL);
10334 	ASSERT(xp != NULL);
10335 
10336 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
10337 	    bp, chain_type);
10338 
10339 	xp->xb_un	= un;
10340 	xp->xb_pktp	= NULL;
10341 	xp->xb_pktinfo	= pktinfop;
10342 	xp->xb_private	= bp->b_private;
10343 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
10344 
10345 	/*
10346 	 * Set up the iostart and iodone chain indexes in the xbuf, based
10347 	 * upon the specified chain type to use.
10348 	 */
10349 	switch (chain_type) {
10350 	case SD_CHAIN_NULL:
10351 		/*
10352 		 * Fall thru to just use the values for the buf type, even
10353 		 * tho for the NULL chain these values will never be used.
10354 		 */
10355 		/* FALLTHRU */
10356 	case SD_CHAIN_BUFIO:
10357 		index = un->un_buf_chain_type;
10358 		break;
10359 	case SD_CHAIN_USCSI:
10360 		index = un->un_uscsi_chain_type;
10361 		break;
10362 	case SD_CHAIN_DIRECT:
10363 		index = un->un_direct_chain_type;
10364 		break;
10365 	case SD_CHAIN_DIRECT_PRIORITY:
10366 		index = un->un_priority_chain_type;
10367 		break;
10368 	default:
10369 		/* We're really broken if we ever get here... */
10370 		panic("sd_xbuf_init: illegal chain type!");
10371 		/*NOTREACHED*/
10372 	}
10373 
10374 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
10375 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
10376 
10377 	/*
10378 	 * It might be a bit easier to simply bzero the entire xbuf above,
10379 	 * but it turns out that since we init a fair number of members anyway,
10380 	 * we save a fair number cycles by doing explicit assignment of zero.
10381 	 */
10382 	xp->xb_pkt_flags	= 0;
10383 	xp->xb_dma_resid	= 0;
10384 	xp->xb_retry_count	= 0;
10385 	xp->xb_victim_retry_count = 0;
10386 	xp->xb_ua_retry_count	= 0;
10387 	xp->xb_nr_retry_count	= 0;
10388 	xp->xb_sense_bp		= NULL;
10389 	xp->xb_sense_status	= 0;
10390 	xp->xb_sense_state	= 0;
10391 	xp->xb_sense_resid	= 0;
10392 
10393 	bp->b_private	= xp;
10394 	bp->b_flags	&= ~(B_DONE | B_ERROR);
10395 	bp->b_resid	= 0;
10396 	bp->av_forw	= NULL;
10397 	bp->av_back	= NULL;
10398 	bioerror(bp, 0);
10399 
10400 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
10401 }
10402 
10403 
10404 /*
10405  *    Function: sd_uscsi_strategy
10406  *
10407  * Description: Wrapper for calling into the USCSI chain via physio(9F)
10408  *
10409  *   Arguments: bp - buf struct ptr
10410  *
10411  * Return Code: Always returns 0
10412  *
10413  *     Context: Kernel thread context
10414  */
10415 
10416 static int
10417 sd_uscsi_strategy(struct buf *bp)
10418 {
10419 	struct sd_lun		*un;
10420 	struct sd_uscsi_info	*uip;
10421 	struct sd_xbuf		*xp;
10422 	uchar_t			chain_type;
10423 
10424 	ASSERT(bp != NULL);
10425 
10426 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
10427 	if (un == NULL) {
10428 		bioerror(bp, EIO);
10429 		bp->b_resid = bp->b_bcount;
10430 		biodone(bp);
10431 		return (0);
10432 	}
10433 
10434 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10435 
10436 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
10437 
10438 	mutex_enter(SD_MUTEX(un));
10439 	/*
10440 	 * atapi: Since we are running the CD for now in PIO mode we need to
10441 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
10442 	 * the HBA's init_pkt routine.
10443 	 */
10444 	if (un->un_f_cfg_is_atapi == TRUE) {
10445 		mutex_exit(SD_MUTEX(un));
10446 		bp_mapin(bp);
10447 		mutex_enter(SD_MUTEX(un));
10448 	}
10449 	un->un_ncmds_in_driver++;
10450 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
10451 	    un->un_ncmds_in_driver);
10452 	mutex_exit(SD_MUTEX(un));
10453 
10454 	/*
10455 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
10456 	 */
10457 	ASSERT(bp->b_private != NULL);
10458 	uip = (struct sd_uscsi_info *)bp->b_private;
10459 
10460 	switch (uip->ui_flags) {
10461 	case SD_PATH_DIRECT:
10462 		chain_type = SD_CHAIN_DIRECT;
10463 		break;
10464 	case SD_PATH_DIRECT_PRIORITY:
10465 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
10466 		break;
10467 	default:
10468 		chain_type = SD_CHAIN_USCSI;
10469 		break;
10470 	}
10471 
10472 	/*
10473 	 * We may allocate extra buf for external USCSI commands. If the
10474 	 * application asks for bigger than 20-byte sense data via USCSI,
10475 	 * SCSA layer will allocate 252 bytes sense buf for that command.
10476 	 */
10477 	xp = kmem_zalloc(sizeof (struct sd_xbuf) - SENSE_LENGTH +
10478 	    (int)(((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_rqlen), KM_SLEEP);
10479 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
10480 
10481 	/* Use the index obtained within xbuf_init */
10482 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
10483 
10484 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
10485 
10486 	return (0);
10487 }
10488 
10489 /*
10490  *    Function: sd_send_scsi_cmd
10491  *
10492  * Description: Runs a USCSI command for user (when called thru sdioctl),
10493  *		or for the driver
10494  *
10495  *   Arguments: dev - the dev_t for the device
10496  *		incmd - ptr to a valid uscsi_cmd struct
10497  *		flag - bit flag, indicating open settings, 32/64 bit type
10498  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
10499  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
10500  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
10501  *			to use the USCSI "direct" chain and bypass the normal
10502  *			command waitq.
10503  *
10504  * Return Code: 0 -  successful completion of the given command
10505  *		EIO - scsi_uscsi_handle_command() failed
10506  *		ENXIO  - soft state not found for specified dev
10507  *		EINVAL
10508  *		EFAULT - copyin/copyout error
10509  *		return code of scsi_uscsi_handle_command():
10510  *			EIO
10511  *			ENXIO
10512  *			EACCES
10513  *
10514  *     Context: Waits for command to complete. Can sleep.
10515  */
10516 
10517 static int
10518 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
10519 	enum uio_seg dataspace, int path_flag)
10520 {
10521 	struct sd_uscsi_info	*uip;
10522 	struct uscsi_cmd	*uscmd;
10523 	struct sd_lun	*un;
10524 	int	format = 0;
10525 	int	rval;
10526 
10527 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
10528 	if (un == NULL) {
10529 		return (ENXIO);
10530 	}
10531 
10532 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10533 
10534 #ifdef SDDEBUG
10535 	switch (dataspace) {
10536 	case UIO_USERSPACE:
10537 		SD_TRACE(SD_LOG_IO, un,
10538 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_USERSPACE\n", un);
10539 		break;
10540 	case UIO_SYSSPACE:
10541 		SD_TRACE(SD_LOG_IO, un,
10542 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_SYSSPACE\n", un);
10543 		break;
10544 	default:
10545 		SD_TRACE(SD_LOG_IO, un,
10546 		    "sd_send_scsi_cmd: entry: un:0x%p UNEXPECTED SPACE\n", un);
10547 		break;
10548 	}
10549 #endif
10550 
10551 	rval = scsi_uscsi_alloc_and_copyin((intptr_t)incmd, flag,
10552 	    SD_ADDRESS(un), &uscmd);
10553 	if (rval != 0) {
10554 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
10555 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
10556 		return (rval);
10557 	}
10558 
10559 	if ((uscmd->uscsi_cdb != NULL) &&
10560 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
10561 		mutex_enter(SD_MUTEX(un));
10562 		un->un_f_format_in_progress = TRUE;
10563 		mutex_exit(SD_MUTEX(un));
10564 		format = 1;
10565 	}
10566 
10567 	/*
10568 	 * Allocate an sd_uscsi_info struct and fill it with the info
10569 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
10570 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
10571 	 * since we allocate the buf here in this function, we do not
10572 	 * need to preserve the prior contents of b_private.
10573 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
10574 	 */
10575 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
10576 	uip->ui_flags = path_flag;
10577 	uip->ui_cmdp = uscmd;
10578 
10579 	/*
10580 	 * Commands sent with priority are intended for error recovery
10581 	 * situations, and do not have retries performed.
10582 	 */
10583 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
10584 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
10585 	}
10586 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
10587 
10588 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
10589 	    sd_uscsi_strategy, NULL, uip);
10590 
10591 #ifdef SDDEBUG
10592 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10593 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
10594 	    uscmd->uscsi_status, uscmd->uscsi_resid);
10595 	if (uscmd->uscsi_bufaddr != NULL) {
10596 		SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10597 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
10598 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
10599 		if (dataspace == UIO_SYSSPACE) {
10600 			SD_DUMP_MEMORY(un, SD_LOG_IO,
10601 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
10602 			    uscmd->uscsi_buflen, SD_LOG_HEX);
10603 		}
10604 	}
10605 #endif
10606 
10607 	if (format == 1) {
10608 		mutex_enter(SD_MUTEX(un));
10609 		un->un_f_format_in_progress = FALSE;
10610 		mutex_exit(SD_MUTEX(un));
10611 	}
10612 
10613 	(void) scsi_uscsi_copyout_and_free((intptr_t)incmd, uscmd);
10614 	kmem_free(uip, sizeof (struct sd_uscsi_info));
10615 
10616 	return (rval);
10617 }
10618 
10619 
10620 /*
10621  *    Function: sd_buf_iodone
10622  *
10623  * Description: Frees the sd_xbuf & returns the buf to its originator.
10624  *
10625  *     Context: May be called from interrupt context.
10626  */
10627 /* ARGSUSED */
10628 static void
10629 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
10630 {
10631 	struct sd_xbuf *xp;
10632 
10633 	ASSERT(un != NULL);
10634 	ASSERT(bp != NULL);
10635 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10636 
10637 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
10638 
10639 	xp = SD_GET_XBUF(bp);
10640 	ASSERT(xp != NULL);
10641 
10642 	mutex_enter(SD_MUTEX(un));
10643 
10644 	/*
10645 	 * Grab time when the cmd completed.
10646 	 * This is used for determining if the system has been
10647 	 * idle long enough to make it idle to the PM framework.
10648 	 * This is for lowering the overhead, and therefore improving
10649 	 * performance per I/O operation.
10650 	 */
10651 	un->un_pm_idle_time = ddi_get_time();
10652 
10653 	un->un_ncmds_in_driver--;
10654 	ASSERT(un->un_ncmds_in_driver >= 0);
10655 	SD_INFO(SD_LOG_IO, un, "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
10656 	    un->un_ncmds_in_driver);
10657 
10658 	mutex_exit(SD_MUTEX(un));
10659 
10660 	ddi_xbuf_done(bp, un->un_xbuf_attr);	/* xbuf is gone after this */
10661 	biodone(bp);				/* bp is gone after this */
10662 
10663 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
10664 }
10665 
10666 
10667 /*
10668  *    Function: sd_uscsi_iodone
10669  *
10670  * Description: Frees the sd_xbuf & returns the buf to its originator.
10671  *
10672  *     Context: May be called from interrupt context.
10673  */
10674 /* ARGSUSED */
10675 static void
10676 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
10677 {
10678 	struct sd_xbuf *xp;
10679 
10680 	ASSERT(un != NULL);
10681 	ASSERT(bp != NULL);
10682 
10683 	xp = SD_GET_XBUF(bp);
10684 	ASSERT(xp != NULL);
10685 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10686 
10687 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
10688 
10689 	bp->b_private = xp->xb_private;
10690 
10691 	mutex_enter(SD_MUTEX(un));
10692 
10693 	/*
10694 	 * Grab time when the cmd completed.
10695 	 * This is used for determining if the system has been
10696 	 * idle long enough to make it idle to the PM framework.
10697 	 * This is for lowering the overhead, and therefore improving
10698 	 * performance per I/O operation.
10699 	 */
10700 	un->un_pm_idle_time = ddi_get_time();
10701 
10702 	un->un_ncmds_in_driver--;
10703 	ASSERT(un->un_ncmds_in_driver >= 0);
10704 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
10705 	    un->un_ncmds_in_driver);
10706 
10707 	mutex_exit(SD_MUTEX(un));
10708 
10709 	kmem_free(xp, sizeof (struct sd_xbuf) - SENSE_LENGTH +
10710 	    (int)(((struct uscsi_cmd *)(xp->xb_pktinfo))->uscsi_rqlen));
10711 	biodone(bp);
10712 
10713 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
10714 }
10715 
10716 
10717 /*
10718  *    Function: sd_mapblockaddr_iostart
10719  *
10720  * Description: Verify request lies within the partition limits for
10721  *		the indicated minor device.  Issue "overrun" buf if
10722  *		request would exceed partition range.  Converts
10723  *		partition-relative block address to absolute.
10724  *
10725  *     Context: Can sleep
10726  *
10727  *      Issues: This follows what the old code did, in terms of accessing
10728  *		some of the partition info in the unit struct without holding
10729  *		the mutext.  This is a general issue, if the partition info
10730  *		can be altered while IO is in progress... as soon as we send
10731  *		a buf, its partitioning can be invalid before it gets to the
10732  *		device.  Probably the right fix is to move partitioning out
10733  *		of the driver entirely.
10734  */
10735 
10736 static void
10737 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
10738 {
10739 	diskaddr_t	nblocks;	/* #blocks in the given partition */
10740 	daddr_t	blocknum;	/* Block number specified by the buf */
10741 	size_t	requested_nblocks;
10742 	size_t	available_nblocks;
10743 	int	partition;
10744 	diskaddr_t	partition_offset;
10745 	struct sd_xbuf *xp;
10746 
10747 
10748 	ASSERT(un != NULL);
10749 	ASSERT(bp != NULL);
10750 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10751 
10752 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10753 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
10754 
10755 	xp = SD_GET_XBUF(bp);
10756 	ASSERT(xp != NULL);
10757 
10758 	/*
10759 	 * If the geometry is not indicated as valid, attempt to access
10760 	 * the unit & verify the geometry/label. This can be the case for
10761 	 * removable-media devices, of if the device was opened in
10762 	 * NDELAY/NONBLOCK mode.
10763 	 */
10764 	if (!SD_IS_VALID_LABEL(un) &&
10765 	    (sd_ready_and_valid(un) != SD_READY_VALID)) {
10766 		/*
10767 		 * For removable devices it is possible to start an I/O
10768 		 * without a media by opening the device in nodelay mode.
10769 		 * Also for writable CDs there can be many scenarios where
10770 		 * there is no geometry yet but volume manager is trying to
10771 		 * issue a read() just because it can see TOC on the CD. So
10772 		 * do not print a message for removables.
10773 		 */
10774 		if (!un->un_f_has_removable_media) {
10775 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10776 			    "i/o to invalid geometry\n");
10777 		}
10778 		bioerror(bp, EIO);
10779 		bp->b_resid = bp->b_bcount;
10780 		SD_BEGIN_IODONE(index, un, bp);
10781 		return;
10782 	}
10783 
10784 	partition = SDPART(bp->b_edev);
10785 
10786 	nblocks = 0;
10787 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
10788 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
10789 
10790 	/*
10791 	 * blocknum is the starting block number of the request. At this
10792 	 * point it is still relative to the start of the minor device.
10793 	 */
10794 	blocknum = xp->xb_blkno;
10795 
10796 	/*
10797 	 * Legacy: If the starting block number is one past the last block
10798 	 * in the partition, do not set B_ERROR in the buf.
10799 	 */
10800 	if (blocknum == nblocks)  {
10801 		goto error_exit;
10802 	}
10803 
10804 	/*
10805 	 * Confirm that the first block of the request lies within the
10806 	 * partition limits. Also the requested number of bytes must be
10807 	 * a multiple of the system block size.
10808 	 */
10809 	if ((blocknum < 0) || (blocknum >= nblocks) ||
10810 	    ((bp->b_bcount & (un->un_sys_blocksize - 1)) != 0)) {
10811 		bp->b_flags |= B_ERROR;
10812 		goto error_exit;
10813 	}
10814 
10815 	/*
10816 	 * If the requsted # blocks exceeds the available # blocks, that
10817 	 * is an overrun of the partition.
10818 	 */
10819 	requested_nblocks = SD_BYTES2SYSBLOCKS(un, bp->b_bcount);
10820 	available_nblocks = (size_t)(nblocks - blocknum);
10821 	ASSERT(nblocks >= blocknum);
10822 
10823 	if (requested_nblocks > available_nblocks) {
10824 		/*
10825 		 * Allocate an "overrun" buf to allow the request to proceed
10826 		 * for the amount of space available in the partition. The
10827 		 * amount not transferred will be added into the b_resid
10828 		 * when the operation is complete. The overrun buf
10829 		 * replaces the original buf here, and the original buf
10830 		 * is saved inside the overrun buf, for later use.
10831 		 */
10832 		size_t resid = SD_SYSBLOCKS2BYTES(un,
10833 		    (offset_t)(requested_nblocks - available_nblocks));
10834 		size_t count = bp->b_bcount - resid;
10835 		/*
10836 		 * Note: count is an unsigned entity thus it'll NEVER
10837 		 * be less than 0 so ASSERT the original values are
10838 		 * correct.
10839 		 */
10840 		ASSERT(bp->b_bcount >= resid);
10841 
10842 		bp = sd_bioclone_alloc(bp, count, blocknum,
10843 		    (int (*)(struct buf *)) sd_mapblockaddr_iodone);
10844 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
10845 		ASSERT(xp != NULL);
10846 	}
10847 
10848 	/* At this point there should be no residual for this buf. */
10849 	ASSERT(bp->b_resid == 0);
10850 
10851 	/* Convert the block number to an absolute address. */
10852 	xp->xb_blkno += partition_offset;
10853 
10854 	SD_NEXT_IOSTART(index, un, bp);
10855 
10856 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10857 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
10858 
10859 	return;
10860 
10861 error_exit:
10862 	bp->b_resid = bp->b_bcount;
10863 	SD_BEGIN_IODONE(index, un, bp);
10864 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10865 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
10866 }
10867 
10868 
10869 /*
10870  *    Function: sd_mapblockaddr_iodone
10871  *
10872  * Description: Completion-side processing for partition management.
10873  *
10874  *     Context: May be called under interrupt context
10875  */
10876 
10877 static void
10878 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
10879 {
10880 	/* int	partition; */	/* Not used, see below. */
10881 	ASSERT(un != NULL);
10882 	ASSERT(bp != NULL);
10883 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10884 
10885 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10886 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
10887 
10888 	if (bp->b_iodone == (int (*)(struct buf *)) sd_mapblockaddr_iodone) {
10889 		/*
10890 		 * We have an "overrun" buf to deal with...
10891 		 */
10892 		struct sd_xbuf	*xp;
10893 		struct buf	*obp;	/* ptr to the original buf */
10894 
10895 		xp = SD_GET_XBUF(bp);
10896 		ASSERT(xp != NULL);
10897 
10898 		/* Retrieve the pointer to the original buf */
10899 		obp = (struct buf *)xp->xb_private;
10900 		ASSERT(obp != NULL);
10901 
10902 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
10903 		bioerror(obp, bp->b_error);
10904 
10905 		sd_bioclone_free(bp);
10906 
10907 		/*
10908 		 * Get back the original buf.
10909 		 * Note that since the restoration of xb_blkno below
10910 		 * was removed, the sd_xbuf is not needed.
10911 		 */
10912 		bp = obp;
10913 		/*
10914 		 * xp = SD_GET_XBUF(bp);
10915 		 * ASSERT(xp != NULL);
10916 		 */
10917 	}
10918 
10919 	/*
10920 	 * Convert sd->xb_blkno back to a minor-device relative value.
10921 	 * Note: this has been commented out, as it is not needed in the
10922 	 * current implementation of the driver (ie, since this function
10923 	 * is at the top of the layering chains, so the info will be
10924 	 * discarded) and it is in the "hot" IO path.
10925 	 *
10926 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
10927 	 * xp->xb_blkno -= un->un_offset[partition];
10928 	 */
10929 
10930 	SD_NEXT_IODONE(index, un, bp);
10931 
10932 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10933 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
10934 }
10935 
10936 
10937 /*
10938  *    Function: sd_mapblocksize_iostart
10939  *
10940  * Description: Convert between system block size (un->un_sys_blocksize)
10941  *		and target block size (un->un_tgt_blocksize).
10942  *
10943  *     Context: Can sleep to allocate resources.
10944  *
10945  * Assumptions: A higher layer has already performed any partition validation,
10946  *		and converted the xp->xb_blkno to an absolute value relative
10947  *		to the start of the device.
10948  *
10949  *		It is also assumed that the higher layer has implemented
10950  *		an "overrun" mechanism for the case where the request would
10951  *		read/write beyond the end of a partition.  In this case we
10952  *		assume (and ASSERT) that bp->b_resid == 0.
10953  *
10954  *		Note: The implementation for this routine assumes the target
10955  *		block size remains constant between allocation and transport.
10956  */
10957 
10958 static void
10959 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
10960 {
10961 	struct sd_mapblocksize_info	*bsp;
10962 	struct sd_xbuf			*xp;
10963 	offset_t first_byte;
10964 	daddr_t	start_block, end_block;
10965 	daddr_t	request_bytes;
10966 	ushort_t is_aligned = FALSE;
10967 
10968 	ASSERT(un != NULL);
10969 	ASSERT(bp != NULL);
10970 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10971 	ASSERT(bp->b_resid == 0);
10972 
10973 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
10974 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
10975 
10976 	/*
10977 	 * For a non-writable CD, a write request is an error
10978 	 */
10979 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
10980 	    (un->un_f_mmc_writable_media == FALSE)) {
10981 		bioerror(bp, EIO);
10982 		bp->b_resid = bp->b_bcount;
10983 		SD_BEGIN_IODONE(index, un, bp);
10984 		return;
10985 	}
10986 
10987 	/*
10988 	 * We do not need a shadow buf if the device is using
10989 	 * un->un_sys_blocksize as its block size or if bcount == 0.
10990 	 * In this case there is no layer-private data block allocated.
10991 	 */
10992 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
10993 	    (bp->b_bcount == 0)) {
10994 		goto done;
10995 	}
10996 
10997 #if defined(__i386) || defined(__amd64)
10998 	/* We do not support non-block-aligned transfers for ROD devices */
10999 	ASSERT(!ISROD(un));
11000 #endif
11001 
11002 	xp = SD_GET_XBUF(bp);
11003 	ASSERT(xp != NULL);
11004 
11005 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11006 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
11007 	    un->un_tgt_blocksize, un->un_sys_blocksize);
11008 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11009 	    "request start block:0x%x\n", xp->xb_blkno);
11010 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11011 	    "request len:0x%x\n", bp->b_bcount);
11012 
11013 	/*
11014 	 * Allocate the layer-private data area for the mapblocksize layer.
11015 	 * Layers are allowed to use the xp_private member of the sd_xbuf
11016 	 * struct to store the pointer to their layer-private data block, but
11017 	 * each layer also has the responsibility of restoring the prior
11018 	 * contents of xb_private before returning the buf/xbuf to the
11019 	 * higher layer that sent it.
11020 	 *
11021 	 * Here we save the prior contents of xp->xb_private into the
11022 	 * bsp->mbs_oprivate field of our layer-private data area. This value
11023 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
11024 	 * the layer-private area and returning the buf/xbuf to the layer
11025 	 * that sent it.
11026 	 *
11027 	 * Note that here we use kmem_zalloc for the allocation as there are
11028 	 * parts of the mapblocksize code that expect certain fields to be
11029 	 * zero unless explicitly set to a required value.
11030 	 */
11031 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
11032 	bsp->mbs_oprivate = xp->xb_private;
11033 	xp->xb_private = bsp;
11034 
11035 	/*
11036 	 * This treats the data on the disk (target) as an array of bytes.
11037 	 * first_byte is the byte offset, from the beginning of the device,
11038 	 * to the location of the request. This is converted from a
11039 	 * un->un_sys_blocksize block address to a byte offset, and then back
11040 	 * to a block address based upon a un->un_tgt_blocksize block size.
11041 	 *
11042 	 * xp->xb_blkno should be absolute upon entry into this function,
11043 	 * but, but it is based upon partitions that use the "system"
11044 	 * block size. It must be adjusted to reflect the block size of
11045 	 * the target.
11046 	 *
11047 	 * Note that end_block is actually the block that follows the last
11048 	 * block of the request, but that's what is needed for the computation.
11049 	 */
11050 	first_byte  = SD_SYSBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
11051 	start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
11052 	end_block   = (first_byte + bp->b_bcount + un->un_tgt_blocksize - 1) /
11053 	    un->un_tgt_blocksize;
11054 
11055 	/* request_bytes is rounded up to a multiple of the target block size */
11056 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
11057 
11058 	/*
11059 	 * See if the starting address of the request and the request
11060 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
11061 	 * then we do not need to allocate a shadow buf to handle the request.
11062 	 */
11063 	if (((first_byte   % un->un_tgt_blocksize) == 0) &&
11064 	    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
11065 		is_aligned = TRUE;
11066 	}
11067 
11068 	if ((bp->b_flags & B_READ) == 0) {
11069 		/*
11070 		 * Lock the range for a write operation. An aligned request is
11071 		 * considered a simple write; otherwise the request must be a
11072 		 * read-modify-write.
11073 		 */
11074 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
11075 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
11076 	}
11077 
11078 	/*
11079 	 * Alloc a shadow buf if the request is not aligned. Also, this is
11080 	 * where the READ command is generated for a read-modify-write. (The
11081 	 * write phase is deferred until after the read completes.)
11082 	 */
11083 	if (is_aligned == FALSE) {
11084 
11085 		struct sd_mapblocksize_info	*shadow_bsp;
11086 		struct sd_xbuf	*shadow_xp;
11087 		struct buf	*shadow_bp;
11088 
11089 		/*
11090 		 * Allocate the shadow buf and it associated xbuf. Note that
11091 		 * after this call the xb_blkno value in both the original
11092 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
11093 		 * same: absolute relative to the start of the device, and
11094 		 * adjusted for the target block size. The b_blkno in the
11095 		 * shadow buf will also be set to this value. We should never
11096 		 * change b_blkno in the original bp however.
11097 		 *
11098 		 * Note also that the shadow buf will always need to be a
11099 		 * READ command, regardless of whether the incoming command
11100 		 * is a READ or a WRITE.
11101 		 */
11102 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
11103 		    xp->xb_blkno,
11104 		    (int (*)(struct buf *)) sd_mapblocksize_iodone);
11105 
11106 		shadow_xp = SD_GET_XBUF(shadow_bp);
11107 
11108 		/*
11109 		 * Allocate the layer-private data for the shadow buf.
11110 		 * (No need to preserve xb_private in the shadow xbuf.)
11111 		 */
11112 		shadow_xp->xb_private = shadow_bsp =
11113 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
11114 
11115 		/*
11116 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
11117 		 * to figure out where the start of the user data is (based upon
11118 		 * the system block size) in the data returned by the READ
11119 		 * command (which will be based upon the target blocksize). Note
11120 		 * that this is only really used if the request is unaligned.
11121 		 */
11122 		bsp->mbs_copy_offset = (ssize_t)(first_byte -
11123 		    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
11124 		ASSERT((bsp->mbs_copy_offset >= 0) &&
11125 		    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
11126 
11127 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
11128 
11129 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
11130 
11131 		/* Transfer the wmap (if any) to the shadow buf */
11132 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
11133 		bsp->mbs_wmp = NULL;
11134 
11135 		/*
11136 		 * The shadow buf goes on from here in place of the
11137 		 * original buf.
11138 		 */
11139 		shadow_bsp->mbs_orig_bp = bp;
11140 		bp = shadow_bp;
11141 	}
11142 
11143 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11144 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
11145 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11146 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
11147 	    request_bytes);
11148 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11149 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
11150 
11151 done:
11152 	SD_NEXT_IOSTART(index, un, bp);
11153 
11154 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11155 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
11156 }
11157 
11158 
11159 /*
11160  *    Function: sd_mapblocksize_iodone
11161  *
11162  * Description: Completion side processing for block-size mapping.
11163  *
11164  *     Context: May be called under interrupt context
11165  */
11166 
11167 static void
11168 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
11169 {
11170 	struct sd_mapblocksize_info	*bsp;
11171 	struct sd_xbuf	*xp;
11172 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
11173 	struct buf	*orig_bp;	/* ptr to the original buf */
11174 	offset_t	shadow_end;
11175 	offset_t	request_end;
11176 	offset_t	shadow_start;
11177 	ssize_t		copy_offset;
11178 	size_t		copy_length;
11179 	size_t		shortfall;
11180 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
11181 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
11182 
11183 	ASSERT(un != NULL);
11184 	ASSERT(bp != NULL);
11185 
11186 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11187 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
11188 
11189 	/*
11190 	 * There is no shadow buf or layer-private data if the target is
11191 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
11192 	 */
11193 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
11194 	    (bp->b_bcount == 0)) {
11195 		goto exit;
11196 	}
11197 
11198 	xp = SD_GET_XBUF(bp);
11199 	ASSERT(xp != NULL);
11200 
11201 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
11202 	bsp = xp->xb_private;
11203 
11204 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
11205 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
11206 
11207 	if (is_write) {
11208 		/*
11209 		 * For a WRITE request we must free up the block range that
11210 		 * we have locked up.  This holds regardless of whether this is
11211 		 * an aligned write request or a read-modify-write request.
11212 		 */
11213 		sd_range_unlock(un, bsp->mbs_wmp);
11214 		bsp->mbs_wmp = NULL;
11215 	}
11216 
11217 	if ((bp->b_iodone != (int(*)(struct buf *))sd_mapblocksize_iodone)) {
11218 		/*
11219 		 * An aligned read or write command will have no shadow buf;
11220 		 * there is not much else to do with it.
11221 		 */
11222 		goto done;
11223 	}
11224 
11225 	orig_bp = bsp->mbs_orig_bp;
11226 	ASSERT(orig_bp != NULL);
11227 	orig_xp = SD_GET_XBUF(orig_bp);
11228 	ASSERT(orig_xp != NULL);
11229 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11230 
11231 	if (!is_write && has_wmap) {
11232 		/*
11233 		 * A READ with a wmap means this is the READ phase of a
11234 		 * read-modify-write. If an error occurred on the READ then
11235 		 * we do not proceed with the WRITE phase or copy any data.
11236 		 * Just release the write maps and return with an error.
11237 		 */
11238 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
11239 			orig_bp->b_resid = orig_bp->b_bcount;
11240 			bioerror(orig_bp, bp->b_error);
11241 			sd_range_unlock(un, bsp->mbs_wmp);
11242 			goto freebuf_done;
11243 		}
11244 	}
11245 
11246 	/*
11247 	 * Here is where we set up to copy the data from the shadow buf
11248 	 * into the space associated with the original buf.
11249 	 *
11250 	 * To deal with the conversion between block sizes, these
11251 	 * computations treat the data as an array of bytes, with the
11252 	 * first byte (byte 0) corresponding to the first byte in the
11253 	 * first block on the disk.
11254 	 */
11255 
11256 	/*
11257 	 * shadow_start and shadow_len indicate the location and size of
11258 	 * the data returned with the shadow IO request.
11259 	 */
11260 	shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
11261 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
11262 
11263 	/*
11264 	 * copy_offset gives the offset (in bytes) from the start of the first
11265 	 * block of the READ request to the beginning of the data.  We retrieve
11266 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
11267 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
11268 	 * data to be copied (in bytes).
11269 	 */
11270 	copy_offset  = bsp->mbs_copy_offset;
11271 	ASSERT((copy_offset >= 0) && (copy_offset < un->un_tgt_blocksize));
11272 	copy_length  = orig_bp->b_bcount;
11273 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
11274 
11275 	/*
11276 	 * Set up the resid and error fields of orig_bp as appropriate.
11277 	 */
11278 	if (shadow_end >= request_end) {
11279 		/* We got all the requested data; set resid to zero */
11280 		orig_bp->b_resid = 0;
11281 	} else {
11282 		/*
11283 		 * We failed to get enough data to fully satisfy the original
11284 		 * request. Just copy back whatever data we got and set
11285 		 * up the residual and error code as required.
11286 		 *
11287 		 * 'shortfall' is the amount by which the data received with the
11288 		 * shadow buf has "fallen short" of the requested amount.
11289 		 */
11290 		shortfall = (size_t)(request_end - shadow_end);
11291 
11292 		if (shortfall > orig_bp->b_bcount) {
11293 			/*
11294 			 * We did not get enough data to even partially
11295 			 * fulfill the original request.  The residual is
11296 			 * equal to the amount requested.
11297 			 */
11298 			orig_bp->b_resid = orig_bp->b_bcount;
11299 		} else {
11300 			/*
11301 			 * We did not get all the data that we requested
11302 			 * from the device, but we will try to return what
11303 			 * portion we did get.
11304 			 */
11305 			orig_bp->b_resid = shortfall;
11306 		}
11307 		ASSERT(copy_length >= orig_bp->b_resid);
11308 		copy_length  -= orig_bp->b_resid;
11309 	}
11310 
11311 	/* Propagate the error code from the shadow buf to the original buf */
11312 	bioerror(orig_bp, bp->b_error);
11313 
11314 	if (is_write) {
11315 		goto freebuf_done;	/* No data copying for a WRITE */
11316 	}
11317 
11318 	if (has_wmap) {
11319 		/*
11320 		 * This is a READ command from the READ phase of a
11321 		 * read-modify-write request. We have to copy the data given
11322 		 * by the user OVER the data returned by the READ command,
11323 		 * then convert the command from a READ to a WRITE and send
11324 		 * it back to the target.
11325 		 */
11326 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
11327 		    copy_length);
11328 
11329 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
11330 
11331 		/*
11332 		 * Dispatch the WRITE command to the taskq thread, which
11333 		 * will in turn send the command to the target. When the
11334 		 * WRITE command completes, we (sd_mapblocksize_iodone())
11335 		 * will get called again as part of the iodone chain
11336 		 * processing for it. Note that we will still be dealing
11337 		 * with the shadow buf at that point.
11338 		 */
11339 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
11340 		    KM_NOSLEEP) != 0) {
11341 			/*
11342 			 * Dispatch was successful so we are done. Return
11343 			 * without going any higher up the iodone chain. Do
11344 			 * not free up any layer-private data until after the
11345 			 * WRITE completes.
11346 			 */
11347 			return;
11348 		}
11349 
11350 		/*
11351 		 * Dispatch of the WRITE command failed; set up the error
11352 		 * condition and send this IO back up the iodone chain.
11353 		 */
11354 		bioerror(orig_bp, EIO);
11355 		orig_bp->b_resid = orig_bp->b_bcount;
11356 
11357 	} else {
11358 		/*
11359 		 * This is a regular READ request (ie, not a RMW). Copy the
11360 		 * data from the shadow buf into the original buf. The
11361 		 * copy_offset compensates for any "misalignment" between the
11362 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
11363 		 * original buf (with its un->un_sys_blocksize blocks).
11364 		 */
11365 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
11366 		    copy_length);
11367 	}
11368 
11369 freebuf_done:
11370 
11371 	/*
11372 	 * At this point we still have both the shadow buf AND the original
11373 	 * buf to deal with, as well as the layer-private data area in each.
11374 	 * Local variables are as follows:
11375 	 *
11376 	 * bp -- points to shadow buf
11377 	 * xp -- points to xbuf of shadow buf
11378 	 * bsp -- points to layer-private data area of shadow buf
11379 	 * orig_bp -- points to original buf
11380 	 *
11381 	 * First free the shadow buf and its associated xbuf, then free the
11382 	 * layer-private data area from the shadow buf. There is no need to
11383 	 * restore xb_private in the shadow xbuf.
11384 	 */
11385 	sd_shadow_buf_free(bp);
11386 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11387 
11388 	/*
11389 	 * Now update the local variables to point to the original buf, xbuf,
11390 	 * and layer-private area.
11391 	 */
11392 	bp = orig_bp;
11393 	xp = SD_GET_XBUF(bp);
11394 	ASSERT(xp != NULL);
11395 	ASSERT(xp == orig_xp);
11396 	bsp = xp->xb_private;
11397 	ASSERT(bsp != NULL);
11398 
11399 done:
11400 	/*
11401 	 * Restore xb_private to whatever it was set to by the next higher
11402 	 * layer in the chain, then free the layer-private data area.
11403 	 */
11404 	xp->xb_private = bsp->mbs_oprivate;
11405 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11406 
11407 exit:
11408 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
11409 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
11410 
11411 	SD_NEXT_IODONE(index, un, bp);
11412 }
11413 
11414 
11415 /*
11416  *    Function: sd_checksum_iostart
11417  *
11418  * Description: A stub function for a layer that's currently not used.
11419  *		For now just a placeholder.
11420  *
11421  *     Context: Kernel thread context
11422  */
11423 
11424 static void
11425 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
11426 {
11427 	ASSERT(un != NULL);
11428 	ASSERT(bp != NULL);
11429 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11430 	SD_NEXT_IOSTART(index, un, bp);
11431 }
11432 
11433 
11434 /*
11435  *    Function: sd_checksum_iodone
11436  *
11437  * Description: A stub function for a layer that's currently not used.
11438  *		For now just a placeholder.
11439  *
11440  *     Context: May be called under interrupt context
11441  */
11442 
11443 static void
11444 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
11445 {
11446 	ASSERT(un != NULL);
11447 	ASSERT(bp != NULL);
11448 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11449 	SD_NEXT_IODONE(index, un, bp);
11450 }
11451 
11452 
11453 /*
11454  *    Function: sd_checksum_uscsi_iostart
11455  *
11456  * Description: A stub function for a layer that's currently not used.
11457  *		For now just a placeholder.
11458  *
11459  *     Context: Kernel thread context
11460  */
11461 
11462 static void
11463 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
11464 {
11465 	ASSERT(un != NULL);
11466 	ASSERT(bp != NULL);
11467 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11468 	SD_NEXT_IOSTART(index, un, bp);
11469 }
11470 
11471 
11472 /*
11473  *    Function: sd_checksum_uscsi_iodone
11474  *
11475  * Description: A stub function for a layer that's currently not used.
11476  *		For now just a placeholder.
11477  *
11478  *     Context: May be called under interrupt context
11479  */
11480 
11481 static void
11482 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
11483 {
11484 	ASSERT(un != NULL);
11485 	ASSERT(bp != NULL);
11486 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11487 	SD_NEXT_IODONE(index, un, bp);
11488 }
11489 
11490 
11491 /*
11492  *    Function: sd_pm_iostart
11493  *
11494  * Description: iostart-side routine for Power mangement.
11495  *
11496  *     Context: Kernel thread context
11497  */
11498 
11499 static void
11500 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
11501 {
11502 	ASSERT(un != NULL);
11503 	ASSERT(bp != NULL);
11504 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11505 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11506 
11507 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
11508 
11509 	if (sd_pm_entry(un) != DDI_SUCCESS) {
11510 		/*
11511 		 * Set up to return the failed buf back up the 'iodone'
11512 		 * side of the calling chain.
11513 		 */
11514 		bioerror(bp, EIO);
11515 		bp->b_resid = bp->b_bcount;
11516 
11517 		SD_BEGIN_IODONE(index, un, bp);
11518 
11519 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11520 		return;
11521 	}
11522 
11523 	SD_NEXT_IOSTART(index, un, bp);
11524 
11525 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11526 }
11527 
11528 
11529 /*
11530  *    Function: sd_pm_iodone
11531  *
11532  * Description: iodone-side routine for power mangement.
11533  *
11534  *     Context: may be called from interrupt context
11535  */
11536 
11537 static void
11538 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
11539 {
11540 	ASSERT(un != NULL);
11541 	ASSERT(bp != NULL);
11542 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11543 
11544 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
11545 
11546 	/*
11547 	 * After attach the following flag is only read, so don't
11548 	 * take the penalty of acquiring a mutex for it.
11549 	 */
11550 	if (un->un_f_pm_is_enabled == TRUE) {
11551 		sd_pm_exit(un);
11552 	}
11553 
11554 	SD_NEXT_IODONE(index, un, bp);
11555 
11556 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
11557 }
11558 
11559 
11560 /*
11561  *    Function: sd_core_iostart
11562  *
11563  * Description: Primary driver function for enqueuing buf(9S) structs from
11564  *		the system and initiating IO to the target device
11565  *
11566  *     Context: Kernel thread context. Can sleep.
11567  *
11568  * Assumptions:  - The given xp->xb_blkno is absolute
11569  *		   (ie, relative to the start of the device).
11570  *		 - The IO is to be done using the native blocksize of
11571  *		   the device, as specified in un->un_tgt_blocksize.
11572  */
11573 /* ARGSUSED */
11574 static void
11575 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
11576 {
11577 	struct sd_xbuf *xp;
11578 
11579 	ASSERT(un != NULL);
11580 	ASSERT(bp != NULL);
11581 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11582 	ASSERT(bp->b_resid == 0);
11583 
11584 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
11585 
11586 	xp = SD_GET_XBUF(bp);
11587 	ASSERT(xp != NULL);
11588 
11589 	mutex_enter(SD_MUTEX(un));
11590 
11591 	/*
11592 	 * If we are currently in the failfast state, fail any new IO
11593 	 * that has B_FAILFAST set, then return.
11594 	 */
11595 	if ((bp->b_flags & B_FAILFAST) &&
11596 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
11597 		mutex_exit(SD_MUTEX(un));
11598 		bioerror(bp, EIO);
11599 		bp->b_resid = bp->b_bcount;
11600 		SD_BEGIN_IODONE(index, un, bp);
11601 		return;
11602 	}
11603 
11604 	if (SD_IS_DIRECT_PRIORITY(xp)) {
11605 		/*
11606 		 * Priority command -- transport it immediately.
11607 		 *
11608 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
11609 		 * because all direct priority commands should be associated
11610 		 * with error recovery actions which we don't want to retry.
11611 		 */
11612 		sd_start_cmds(un, bp);
11613 	} else {
11614 		/*
11615 		 * Normal command -- add it to the wait queue, then start
11616 		 * transporting commands from the wait queue.
11617 		 */
11618 		sd_add_buf_to_waitq(un, bp);
11619 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
11620 		sd_start_cmds(un, NULL);
11621 	}
11622 
11623 	mutex_exit(SD_MUTEX(un));
11624 
11625 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
11626 }
11627 
11628 
11629 /*
11630  *    Function: sd_init_cdb_limits
11631  *
11632  * Description: This is to handle scsi_pkt initialization differences
11633  *		between the driver platforms.
11634  *
11635  *		Legacy behaviors:
11636  *
11637  *		If the block number or the sector count exceeds the
11638  *		capabilities of a Group 0 command, shift over to a
11639  *		Group 1 command. We don't blindly use Group 1
11640  *		commands because a) some drives (CDC Wren IVs) get a
11641  *		bit confused, and b) there is probably a fair amount
11642  *		of speed difference for a target to receive and decode
11643  *		a 10 byte command instead of a 6 byte command.
11644  *
11645  *		The xfer time difference of 6 vs 10 byte CDBs is
11646  *		still significant so this code is still worthwhile.
11647  *		10 byte CDBs are very inefficient with the fas HBA driver
11648  *		and older disks. Each CDB byte took 1 usec with some
11649  *		popular disks.
11650  *
11651  *     Context: Must be called at attach time
11652  */
11653 
11654 static void
11655 sd_init_cdb_limits(struct sd_lun *un)
11656 {
11657 	int hba_cdb_limit;
11658 
11659 	/*
11660 	 * Use CDB_GROUP1 commands for most devices except for
11661 	 * parallel SCSI fixed drives in which case we get better
11662 	 * performance using CDB_GROUP0 commands (where applicable).
11663 	 */
11664 	un->un_mincdb = SD_CDB_GROUP1;
11665 #if !defined(__fibre)
11666 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
11667 	    !un->un_f_has_removable_media) {
11668 		un->un_mincdb = SD_CDB_GROUP0;
11669 	}
11670 #endif
11671 
11672 	/*
11673 	 * Try to read the max-cdb-length supported by HBA.
11674 	 */
11675 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
11676 	if (0 >= un->un_max_hba_cdb) {
11677 		un->un_max_hba_cdb = CDB_GROUP4;
11678 		hba_cdb_limit = SD_CDB_GROUP4;
11679 	} else if (0 < un->un_max_hba_cdb &&
11680 	    un->un_max_hba_cdb < CDB_GROUP1) {
11681 		hba_cdb_limit = SD_CDB_GROUP0;
11682 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
11683 	    un->un_max_hba_cdb < CDB_GROUP5) {
11684 		hba_cdb_limit = SD_CDB_GROUP1;
11685 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
11686 	    un->un_max_hba_cdb < CDB_GROUP4) {
11687 		hba_cdb_limit = SD_CDB_GROUP5;
11688 	} else {
11689 		hba_cdb_limit = SD_CDB_GROUP4;
11690 	}
11691 
11692 	/*
11693 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
11694 	 * commands for fixed disks unless we are building for a 32 bit
11695 	 * kernel.
11696 	 */
11697 #ifdef _LP64
11698 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11699 	    min(hba_cdb_limit, SD_CDB_GROUP4);
11700 #else
11701 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11702 	    min(hba_cdb_limit, SD_CDB_GROUP1);
11703 #endif
11704 
11705 	/*
11706 	 * x86 systems require the PKT_DMA_PARTIAL flag
11707 	 */
11708 #if defined(__x86)
11709 	un->un_pkt_flags = PKT_DMA_PARTIAL;
11710 #else
11711 	un->un_pkt_flags = 0;
11712 #endif
11713 
11714 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
11715 	    ? sizeof (struct scsi_arq_status) : 1);
11716 	un->un_cmd_timeout = (ushort_t)sd_io_time;
11717 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
11718 }
11719 
11720 
11721 /*
11722  *    Function: sd_initpkt_for_buf
11723  *
11724  * Description: Allocate and initialize for transport a scsi_pkt struct,
11725  *		based upon the info specified in the given buf struct.
11726  *
11727  *		Assumes the xb_blkno in the request is absolute (ie,
11728  *		relative to the start of the device (NOT partition!).
11729  *		Also assumes that the request is using the native block
11730  *		size of the device (as returned by the READ CAPACITY
11731  *		command).
11732  *
11733  * Return Code: SD_PKT_ALLOC_SUCCESS
11734  *		SD_PKT_ALLOC_FAILURE
11735  *		SD_PKT_ALLOC_FAILURE_NO_DMA
11736  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11737  *
11738  *     Context: Kernel thread and may be called from software interrupt context
11739  *		as part of a sdrunout callback. This function may not block or
11740  *		call routines that block
11741  */
11742 
11743 static int
11744 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
11745 {
11746 	struct sd_xbuf	*xp;
11747 	struct scsi_pkt *pktp = NULL;
11748 	struct sd_lun	*un;
11749 	size_t		blockcount;
11750 	daddr_t		startblock;
11751 	int		rval;
11752 	int		cmd_flags;
11753 
11754 	ASSERT(bp != NULL);
11755 	ASSERT(pktpp != NULL);
11756 	xp = SD_GET_XBUF(bp);
11757 	ASSERT(xp != NULL);
11758 	un = SD_GET_UN(bp);
11759 	ASSERT(un != NULL);
11760 	ASSERT(mutex_owned(SD_MUTEX(un)));
11761 	ASSERT(bp->b_resid == 0);
11762 
11763 	SD_TRACE(SD_LOG_IO_CORE, un,
11764 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
11765 
11766 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11767 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
11768 		/*
11769 		 * Already have a scsi_pkt -- just need DMA resources.
11770 		 * We must recompute the CDB in case the mapping returns
11771 		 * a nonzero pkt_resid.
11772 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
11773 		 * that is being retried, the unmap/remap of the DMA resouces
11774 		 * will result in the entire transfer starting over again
11775 		 * from the very first block.
11776 		 */
11777 		ASSERT(xp->xb_pktp != NULL);
11778 		pktp = xp->xb_pktp;
11779 	} else {
11780 		pktp = NULL;
11781 	}
11782 #endif /* __i386 || __amd64 */
11783 
11784 	startblock = xp->xb_blkno;	/* Absolute block num. */
11785 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
11786 
11787 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11788 
11789 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
11790 
11791 #else
11792 
11793 	cmd_flags = un->un_pkt_flags | xp->xb_pkt_flags;
11794 
11795 #endif
11796 
11797 	/*
11798 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
11799 	 * call scsi_init_pkt, and build the CDB.
11800 	 */
11801 	rval = sd_setup_rw_pkt(un, &pktp, bp,
11802 	    cmd_flags, sdrunout, (caddr_t)un,
11803 	    startblock, blockcount);
11804 
11805 	if (rval == 0) {
11806 		/*
11807 		 * Success.
11808 		 *
11809 		 * If partial DMA is being used and required for this transfer.
11810 		 * set it up here.
11811 		 */
11812 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
11813 		    (pktp->pkt_resid != 0)) {
11814 
11815 			/*
11816 			 * Save the CDB length and pkt_resid for the
11817 			 * next xfer
11818 			 */
11819 			xp->xb_dma_resid = pktp->pkt_resid;
11820 
11821 			/* rezero resid */
11822 			pktp->pkt_resid = 0;
11823 
11824 		} else {
11825 			xp->xb_dma_resid = 0;
11826 		}
11827 
11828 		pktp->pkt_flags = un->un_tagflags;
11829 		pktp->pkt_time  = un->un_cmd_timeout;
11830 		pktp->pkt_comp  = sdintr;
11831 
11832 		pktp->pkt_private = bp;
11833 		*pktpp = pktp;
11834 
11835 		SD_TRACE(SD_LOG_IO_CORE, un,
11836 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
11837 
11838 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11839 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
11840 #endif
11841 
11842 		return (SD_PKT_ALLOC_SUCCESS);
11843 
11844 	}
11845 
11846 	/*
11847 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
11848 	 * from sd_setup_rw_pkt.
11849 	 */
11850 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
11851 
11852 	if (rval == SD_PKT_ALLOC_FAILURE) {
11853 		*pktpp = NULL;
11854 		/*
11855 		 * Set the driver state to RWAIT to indicate the driver
11856 		 * is waiting on resource allocations. The driver will not
11857 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
11858 		 */
11859 		New_state(un, SD_STATE_RWAIT);
11860 
11861 		SD_ERROR(SD_LOG_IO_CORE, un,
11862 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
11863 
11864 		if ((bp->b_flags & B_ERROR) != 0) {
11865 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
11866 		}
11867 		return (SD_PKT_ALLOC_FAILURE);
11868 	} else {
11869 		/*
11870 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11871 		 *
11872 		 * This should never happen.  Maybe someone messed with the
11873 		 * kernel's minphys?
11874 		 */
11875 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
11876 		    "Request rejected: too large for CDB: "
11877 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
11878 		SD_ERROR(SD_LOG_IO_CORE, un,
11879 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
11880 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
11881 
11882 	}
11883 }
11884 
11885 
11886 /*
11887  *    Function: sd_destroypkt_for_buf
11888  *
11889  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
11890  *
11891  *     Context: Kernel thread or interrupt context
11892  */
11893 
11894 static void
11895 sd_destroypkt_for_buf(struct buf *bp)
11896 {
11897 	ASSERT(bp != NULL);
11898 	ASSERT(SD_GET_UN(bp) != NULL);
11899 
11900 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11901 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
11902 
11903 	ASSERT(SD_GET_PKTP(bp) != NULL);
11904 	scsi_destroy_pkt(SD_GET_PKTP(bp));
11905 
11906 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11907 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
11908 }
11909 
11910 /*
11911  *    Function: sd_setup_rw_pkt
11912  *
11913  * Description: Determines appropriate CDB group for the requested LBA
11914  *		and transfer length, calls scsi_init_pkt, and builds
11915  *		the CDB.  Do not use for partial DMA transfers except
11916  *		for the initial transfer since the CDB size must
11917  *		remain constant.
11918  *
11919  *     Context: Kernel thread and may be called from software interrupt
11920  *		context as part of a sdrunout callback. This function may not
11921  *		block or call routines that block
11922  */
11923 
11924 
11925 int
11926 sd_setup_rw_pkt(struct sd_lun *un,
11927     struct scsi_pkt **pktpp, struct buf *bp, int flags,
11928     int (*callback)(caddr_t), caddr_t callback_arg,
11929     diskaddr_t lba, uint32_t blockcount)
11930 {
11931 	struct scsi_pkt *return_pktp;
11932 	union scsi_cdb *cdbp;
11933 	struct sd_cdbinfo *cp = NULL;
11934 	int i;
11935 
11936 	/*
11937 	 * See which size CDB to use, based upon the request.
11938 	 */
11939 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
11940 
11941 		/*
11942 		 * Check lba and block count against sd_cdbtab limits.
11943 		 * In the partial DMA case, we have to use the same size
11944 		 * CDB for all the transfers.  Check lba + blockcount
11945 		 * against the max LBA so we know that segment of the
11946 		 * transfer can use the CDB we select.
11947 		 */
11948 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
11949 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
11950 
11951 			/*
11952 			 * The command will fit into the CDB type
11953 			 * specified by sd_cdbtab[i].
11954 			 */
11955 			cp = sd_cdbtab + i;
11956 
11957 			/*
11958 			 * Call scsi_init_pkt so we can fill in the
11959 			 * CDB.
11960 			 */
11961 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
11962 			    bp, cp->sc_grpcode, un->un_status_len, 0,
11963 			    flags, callback, callback_arg);
11964 
11965 			if (return_pktp != NULL) {
11966 
11967 				/*
11968 				 * Return new value of pkt
11969 				 */
11970 				*pktpp = return_pktp;
11971 
11972 				/*
11973 				 * To be safe, zero the CDB insuring there is
11974 				 * no leftover data from a previous command.
11975 				 */
11976 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
11977 
11978 				/*
11979 				 * Handle partial DMA mapping
11980 				 */
11981 				if (return_pktp->pkt_resid != 0) {
11982 
11983 					/*
11984 					 * Not going to xfer as many blocks as
11985 					 * originally expected
11986 					 */
11987 					blockcount -=
11988 					    SD_BYTES2TGTBLOCKS(un,
11989 					    return_pktp->pkt_resid);
11990 				}
11991 
11992 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
11993 
11994 				/*
11995 				 * Set command byte based on the CDB
11996 				 * type we matched.
11997 				 */
11998 				cdbp->scc_cmd = cp->sc_grpmask |
11999 				    ((bp->b_flags & B_READ) ?
12000 				    SCMD_READ : SCMD_WRITE);
12001 
12002 				SD_FILL_SCSI1_LUN(un, return_pktp);
12003 
12004 				/*
12005 				 * Fill in LBA and length
12006 				 */
12007 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
12008 				    (cp->sc_grpcode == CDB_GROUP4) ||
12009 				    (cp->sc_grpcode == CDB_GROUP0) ||
12010 				    (cp->sc_grpcode == CDB_GROUP5));
12011 
12012 				if (cp->sc_grpcode == CDB_GROUP1) {
12013 					FORMG1ADDR(cdbp, lba);
12014 					FORMG1COUNT(cdbp, blockcount);
12015 					return (0);
12016 				} else if (cp->sc_grpcode == CDB_GROUP4) {
12017 					FORMG4LONGADDR(cdbp, lba);
12018 					FORMG4COUNT(cdbp, blockcount);
12019 					return (0);
12020 				} else if (cp->sc_grpcode == CDB_GROUP0) {
12021 					FORMG0ADDR(cdbp, lba);
12022 					FORMG0COUNT(cdbp, blockcount);
12023 					return (0);
12024 				} else if (cp->sc_grpcode == CDB_GROUP5) {
12025 					FORMG5ADDR(cdbp, lba);
12026 					FORMG5COUNT(cdbp, blockcount);
12027 					return (0);
12028 				}
12029 
12030 				/*
12031 				 * It should be impossible to not match one
12032 				 * of the CDB types above, so we should never
12033 				 * reach this point.  Set the CDB command byte
12034 				 * to test-unit-ready to avoid writing
12035 				 * to somewhere we don't intend.
12036 				 */
12037 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
12038 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12039 			} else {
12040 				/*
12041 				 * Couldn't get scsi_pkt
12042 				 */
12043 				return (SD_PKT_ALLOC_FAILURE);
12044 			}
12045 		}
12046 	}
12047 
12048 	/*
12049 	 * None of the available CDB types were suitable.  This really
12050 	 * should never happen:  on a 64 bit system we support
12051 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
12052 	 * and on a 32 bit system we will refuse to bind to a device
12053 	 * larger than 2TB so addresses will never be larger than 32 bits.
12054 	 */
12055 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12056 }
12057 
12058 #if defined(__i386) || defined(__amd64)
12059 /*
12060  *    Function: sd_setup_next_rw_pkt
12061  *
12062  * Description: Setup packet for partial DMA transfers, except for the
12063  * 		initial transfer.  sd_setup_rw_pkt should be used for
12064  *		the initial transfer.
12065  *
12066  *     Context: Kernel thread and may be called from interrupt context.
12067  */
12068 
12069 int
12070 sd_setup_next_rw_pkt(struct sd_lun *un,
12071     struct scsi_pkt *pktp, struct buf *bp,
12072     diskaddr_t lba, uint32_t blockcount)
12073 {
12074 	uchar_t com;
12075 	union scsi_cdb *cdbp;
12076 	uchar_t cdb_group_id;
12077 
12078 	ASSERT(pktp != NULL);
12079 	ASSERT(pktp->pkt_cdbp != NULL);
12080 
12081 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
12082 	com = cdbp->scc_cmd;
12083 	cdb_group_id = CDB_GROUPID(com);
12084 
12085 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
12086 	    (cdb_group_id == CDB_GROUPID_1) ||
12087 	    (cdb_group_id == CDB_GROUPID_4) ||
12088 	    (cdb_group_id == CDB_GROUPID_5));
12089 
12090 	/*
12091 	 * Move pkt to the next portion of the xfer.
12092 	 * func is NULL_FUNC so we do not have to release
12093 	 * the disk mutex here.
12094 	 */
12095 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
12096 	    NULL_FUNC, NULL) == pktp) {
12097 		/* Success.  Handle partial DMA */
12098 		if (pktp->pkt_resid != 0) {
12099 			blockcount -=
12100 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
12101 		}
12102 
12103 		cdbp->scc_cmd = com;
12104 		SD_FILL_SCSI1_LUN(un, pktp);
12105 		if (cdb_group_id == CDB_GROUPID_1) {
12106 			FORMG1ADDR(cdbp, lba);
12107 			FORMG1COUNT(cdbp, blockcount);
12108 			return (0);
12109 		} else if (cdb_group_id == CDB_GROUPID_4) {
12110 			FORMG4LONGADDR(cdbp, lba);
12111 			FORMG4COUNT(cdbp, blockcount);
12112 			return (0);
12113 		} else if (cdb_group_id == CDB_GROUPID_0) {
12114 			FORMG0ADDR(cdbp, lba);
12115 			FORMG0COUNT(cdbp, blockcount);
12116 			return (0);
12117 		} else if (cdb_group_id == CDB_GROUPID_5) {
12118 			FORMG5ADDR(cdbp, lba);
12119 			FORMG5COUNT(cdbp, blockcount);
12120 			return (0);
12121 		}
12122 
12123 		/* Unreachable */
12124 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12125 	}
12126 
12127 	/*
12128 	 * Error setting up next portion of cmd transfer.
12129 	 * Something is definitely very wrong and this
12130 	 * should not happen.
12131 	 */
12132 	return (SD_PKT_ALLOC_FAILURE);
12133 }
12134 #endif /* defined(__i386) || defined(__amd64) */
12135 
12136 /*
12137  *    Function: sd_initpkt_for_uscsi
12138  *
12139  * Description: Allocate and initialize for transport a scsi_pkt struct,
12140  *		based upon the info specified in the given uscsi_cmd struct.
12141  *
12142  * Return Code: SD_PKT_ALLOC_SUCCESS
12143  *		SD_PKT_ALLOC_FAILURE
12144  *		SD_PKT_ALLOC_FAILURE_NO_DMA
12145  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
12146  *
12147  *     Context: Kernel thread and may be called from software interrupt context
12148  *		as part of a sdrunout callback. This function may not block or
12149  *		call routines that block
12150  */
12151 
12152 static int
12153 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
12154 {
12155 	struct uscsi_cmd *uscmd;
12156 	struct sd_xbuf	*xp;
12157 	struct scsi_pkt	*pktp;
12158 	struct sd_lun	*un;
12159 	uint32_t	flags = 0;
12160 
12161 	ASSERT(bp != NULL);
12162 	ASSERT(pktpp != NULL);
12163 	xp = SD_GET_XBUF(bp);
12164 	ASSERT(xp != NULL);
12165 	un = SD_GET_UN(bp);
12166 	ASSERT(un != NULL);
12167 	ASSERT(mutex_owned(SD_MUTEX(un)));
12168 
12169 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12170 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12171 	ASSERT(uscmd != NULL);
12172 
12173 	SD_TRACE(SD_LOG_IO_CORE, un,
12174 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
12175 
12176 	/*
12177 	 * Allocate the scsi_pkt for the command.
12178 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
12179 	 *	 during scsi_init_pkt time and will continue to use the
12180 	 *	 same path as long as the same scsi_pkt is used without
12181 	 *	 intervening scsi_dma_free(). Since uscsi command does
12182 	 *	 not call scsi_dmafree() before retry failed command, it
12183 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
12184 	 *	 set such that scsi_vhci can use other available path for
12185 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
12186 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
12187 	 */
12188 	if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
12189 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
12190 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
12191 		    ((int)(uscmd->uscsi_rqlen) + sizeof (struct scsi_arq_status)
12192 		    - sizeof (struct scsi_extended_sense)), 0,
12193 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL) | PKT_XARQ,
12194 		    sdrunout, (caddr_t)un);
12195 	} else {
12196 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
12197 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
12198 		    sizeof (struct scsi_arq_status), 0,
12199 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
12200 		    sdrunout, (caddr_t)un);
12201 	}
12202 
12203 	if (pktp == NULL) {
12204 		*pktpp = NULL;
12205 		/*
12206 		 * Set the driver state to RWAIT to indicate the driver
12207 		 * is waiting on resource allocations. The driver will not
12208 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
12209 		 */
12210 		New_state(un, SD_STATE_RWAIT);
12211 
12212 		SD_ERROR(SD_LOG_IO_CORE, un,
12213 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
12214 
12215 		if ((bp->b_flags & B_ERROR) != 0) {
12216 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
12217 		}
12218 		return (SD_PKT_ALLOC_FAILURE);
12219 	}
12220 
12221 	/*
12222 	 * We do not do DMA breakup for USCSI commands, so return failure
12223 	 * here if all the needed DMA resources were not allocated.
12224 	 */
12225 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
12226 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
12227 		scsi_destroy_pkt(pktp);
12228 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
12229 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
12230 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
12231 	}
12232 
12233 	/* Init the cdb from the given uscsi struct */
12234 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
12235 	    uscmd->uscsi_cdb[0], 0, 0, 0);
12236 
12237 	SD_FILL_SCSI1_LUN(un, pktp);
12238 
12239 	/*
12240 	 * Set up the optional USCSI flags. See the uscsi (7I) man page
12241 	 * for listing of the supported flags.
12242 	 */
12243 
12244 	if (uscmd->uscsi_flags & USCSI_SILENT) {
12245 		flags |= FLAG_SILENT;
12246 	}
12247 
12248 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
12249 		flags |= FLAG_DIAGNOSE;
12250 	}
12251 
12252 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
12253 		flags |= FLAG_ISOLATE;
12254 	}
12255 
12256 	if (un->un_f_is_fibre == FALSE) {
12257 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
12258 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
12259 		}
12260 	}
12261 
12262 	/*
12263 	 * Set the pkt flags here so we save time later.
12264 	 * Note: These flags are NOT in the uscsi man page!!!
12265 	 */
12266 	if (uscmd->uscsi_flags & USCSI_HEAD) {
12267 		flags |= FLAG_HEAD;
12268 	}
12269 
12270 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
12271 		flags |= FLAG_NOINTR;
12272 	}
12273 
12274 	/*
12275 	 * For tagged queueing, things get a bit complicated.
12276 	 * Check first for head of queue and last for ordered queue.
12277 	 * If neither head nor order, use the default driver tag flags.
12278 	 */
12279 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
12280 		if (uscmd->uscsi_flags & USCSI_HTAG) {
12281 			flags |= FLAG_HTAG;
12282 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
12283 			flags |= FLAG_OTAG;
12284 		} else {
12285 			flags |= un->un_tagflags & FLAG_TAGMASK;
12286 		}
12287 	}
12288 
12289 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
12290 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
12291 	}
12292 
12293 	pktp->pkt_flags = flags;
12294 
12295 	/* Copy the caller's CDB into the pkt... */
12296 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
12297 
12298 	if (uscmd->uscsi_timeout == 0) {
12299 		pktp->pkt_time = un->un_uscsi_timeout;
12300 	} else {
12301 		pktp->pkt_time = uscmd->uscsi_timeout;
12302 	}
12303 
12304 	/* need it later to identify USCSI request in sdintr */
12305 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
12306 
12307 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
12308 
12309 	pktp->pkt_private = bp;
12310 	pktp->pkt_comp = sdintr;
12311 	*pktpp = pktp;
12312 
12313 	SD_TRACE(SD_LOG_IO_CORE, un,
12314 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
12315 
12316 	return (SD_PKT_ALLOC_SUCCESS);
12317 }
12318 
12319 
12320 /*
12321  *    Function: sd_destroypkt_for_uscsi
12322  *
12323  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
12324  *		IOs.. Also saves relevant info into the associated uscsi_cmd
12325  *		struct.
12326  *
12327  *     Context: May be called under interrupt context
12328  */
12329 
12330 static void
12331 sd_destroypkt_for_uscsi(struct buf *bp)
12332 {
12333 	struct uscsi_cmd *uscmd;
12334 	struct sd_xbuf	*xp;
12335 	struct scsi_pkt	*pktp;
12336 	struct sd_lun	*un;
12337 
12338 	ASSERT(bp != NULL);
12339 	xp = SD_GET_XBUF(bp);
12340 	ASSERT(xp != NULL);
12341 	un = SD_GET_UN(bp);
12342 	ASSERT(un != NULL);
12343 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12344 	pktp = SD_GET_PKTP(bp);
12345 	ASSERT(pktp != NULL);
12346 
12347 	SD_TRACE(SD_LOG_IO_CORE, un,
12348 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
12349 
12350 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12351 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12352 	ASSERT(uscmd != NULL);
12353 
12354 	/* Save the status and the residual into the uscsi_cmd struct */
12355 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
12356 	uscmd->uscsi_resid  = bp->b_resid;
12357 
12358 	/*
12359 	 * If enabled, copy any saved sense data into the area specified
12360 	 * by the uscsi command.
12361 	 */
12362 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
12363 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
12364 		/*
12365 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
12366 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
12367 		 */
12368 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
12369 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
12370 		bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
12371 		    uscmd->uscsi_rqlen);
12372 	}
12373 
12374 	/* We are done with the scsi_pkt; free it now */
12375 	ASSERT(SD_GET_PKTP(bp) != NULL);
12376 	scsi_destroy_pkt(SD_GET_PKTP(bp));
12377 
12378 	SD_TRACE(SD_LOG_IO_CORE, un,
12379 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
12380 }
12381 
12382 
12383 /*
12384  *    Function: sd_bioclone_alloc
12385  *
12386  * Description: Allocate a buf(9S) and init it as per the given buf
12387  *		and the various arguments.  The associated sd_xbuf
12388  *		struct is (nearly) duplicated.  The struct buf *bp
12389  *		argument is saved in new_xp->xb_private.
12390  *
12391  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12392  *		datalen - size of data area for the shadow bp
12393  *		blkno - starting LBA
12394  *		func - function pointer for b_iodone in the shadow buf. (May
12395  *			be NULL if none.)
12396  *
12397  * Return Code: Pointer to allocates buf(9S) struct
12398  *
12399  *     Context: Can sleep.
12400  */
12401 
12402 static struct buf *
12403 sd_bioclone_alloc(struct buf *bp, size_t datalen,
12404 	daddr_t blkno, int (*func)(struct buf *))
12405 {
12406 	struct	sd_lun	*un;
12407 	struct	sd_xbuf	*xp;
12408 	struct	sd_xbuf	*new_xp;
12409 	struct	buf	*new_bp;
12410 
12411 	ASSERT(bp != NULL);
12412 	xp = SD_GET_XBUF(bp);
12413 	ASSERT(xp != NULL);
12414 	un = SD_GET_UN(bp);
12415 	ASSERT(un != NULL);
12416 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12417 
12418 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
12419 	    NULL, KM_SLEEP);
12420 
12421 	new_bp->b_lblkno	= blkno;
12422 
12423 	/*
12424 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12425 	 * original xbuf into it.
12426 	 */
12427 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12428 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12429 
12430 	/*
12431 	 * The given bp is automatically saved in the xb_private member
12432 	 * of the new xbuf.  Callers are allowed to depend on this.
12433 	 */
12434 	new_xp->xb_private = bp;
12435 
12436 	new_bp->b_private  = new_xp;
12437 
12438 	return (new_bp);
12439 }
12440 
12441 /*
12442  *    Function: sd_shadow_buf_alloc
12443  *
12444  * Description: Allocate a buf(9S) and init it as per the given buf
12445  *		and the various arguments.  The associated sd_xbuf
12446  *		struct is (nearly) duplicated.  The struct buf *bp
12447  *		argument is saved in new_xp->xb_private.
12448  *
12449  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12450  *		datalen - size of data area for the shadow bp
12451  *		bflags - B_READ or B_WRITE (pseudo flag)
12452  *		blkno - starting LBA
12453  *		func - function pointer for b_iodone in the shadow buf. (May
12454  *			be NULL if none.)
12455  *
12456  * Return Code: Pointer to allocates buf(9S) struct
12457  *
12458  *     Context: Can sleep.
12459  */
12460 
12461 static struct buf *
12462 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
12463 	daddr_t blkno, int (*func)(struct buf *))
12464 {
12465 	struct	sd_lun	*un;
12466 	struct	sd_xbuf	*xp;
12467 	struct	sd_xbuf	*new_xp;
12468 	struct	buf	*new_bp;
12469 
12470 	ASSERT(bp != NULL);
12471 	xp = SD_GET_XBUF(bp);
12472 	ASSERT(xp != NULL);
12473 	un = SD_GET_UN(bp);
12474 	ASSERT(un != NULL);
12475 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12476 
12477 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
12478 		bp_mapin(bp);
12479 	}
12480 
12481 	bflags &= (B_READ | B_WRITE);
12482 #if defined(__i386) || defined(__amd64)
12483 	new_bp = getrbuf(KM_SLEEP);
12484 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
12485 	new_bp->b_bcount = datalen;
12486 	new_bp->b_flags = bflags |
12487 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
12488 #else
12489 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
12490 	    datalen, bflags, SLEEP_FUNC, NULL);
12491 #endif
12492 	new_bp->av_forw	= NULL;
12493 	new_bp->av_back	= NULL;
12494 	new_bp->b_dev	= bp->b_dev;
12495 	new_bp->b_blkno	= blkno;
12496 	new_bp->b_iodone = func;
12497 	new_bp->b_edev	= bp->b_edev;
12498 	new_bp->b_resid	= 0;
12499 
12500 	/* We need to preserve the B_FAILFAST flag */
12501 	if (bp->b_flags & B_FAILFAST) {
12502 		new_bp->b_flags |= B_FAILFAST;
12503 	}
12504 
12505 	/*
12506 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12507 	 * original xbuf into it.
12508 	 */
12509 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12510 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12511 
12512 	/* Need later to copy data between the shadow buf & original buf! */
12513 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
12514 
12515 	/*
12516 	 * The given bp is automatically saved in the xb_private member
12517 	 * of the new xbuf.  Callers are allowed to depend on this.
12518 	 */
12519 	new_xp->xb_private = bp;
12520 
12521 	new_bp->b_private  = new_xp;
12522 
12523 	return (new_bp);
12524 }
12525 
12526 /*
12527  *    Function: sd_bioclone_free
12528  *
12529  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
12530  *		in the larger than partition operation.
12531  *
12532  *     Context: May be called under interrupt context
12533  */
12534 
12535 static void
12536 sd_bioclone_free(struct buf *bp)
12537 {
12538 	struct sd_xbuf	*xp;
12539 
12540 	ASSERT(bp != NULL);
12541 	xp = SD_GET_XBUF(bp);
12542 	ASSERT(xp != NULL);
12543 
12544 	/*
12545 	 * Call bp_mapout() before freeing the buf,  in case a lower
12546 	 * layer or HBA  had done a bp_mapin().  we must do this here
12547 	 * as we are the "originator" of the shadow buf.
12548 	 */
12549 	bp_mapout(bp);
12550 
12551 	/*
12552 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12553 	 * never gets confused by a stale value in this field. (Just a little
12554 	 * extra defensiveness here.)
12555 	 */
12556 	bp->b_iodone = NULL;
12557 
12558 	freerbuf(bp);
12559 
12560 	kmem_free(xp, sizeof (struct sd_xbuf));
12561 }
12562 
12563 /*
12564  *    Function: sd_shadow_buf_free
12565  *
12566  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
12567  *
12568  *     Context: May be called under interrupt context
12569  */
12570 
12571 static void
12572 sd_shadow_buf_free(struct buf *bp)
12573 {
12574 	struct sd_xbuf	*xp;
12575 
12576 	ASSERT(bp != NULL);
12577 	xp = SD_GET_XBUF(bp);
12578 	ASSERT(xp != NULL);
12579 
12580 #if defined(__sparc)
12581 	/*
12582 	 * Call bp_mapout() before freeing the buf,  in case a lower
12583 	 * layer or HBA  had done a bp_mapin().  we must do this here
12584 	 * as we are the "originator" of the shadow buf.
12585 	 */
12586 	bp_mapout(bp);
12587 #endif
12588 
12589 	/*
12590 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12591 	 * never gets confused by a stale value in this field. (Just a little
12592 	 * extra defensiveness here.)
12593 	 */
12594 	bp->b_iodone = NULL;
12595 
12596 #if defined(__i386) || defined(__amd64)
12597 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
12598 	freerbuf(bp);
12599 #else
12600 	scsi_free_consistent_buf(bp);
12601 #endif
12602 
12603 	kmem_free(xp, sizeof (struct sd_xbuf));
12604 }
12605 
12606 
12607 /*
12608  *    Function: sd_print_transport_rejected_message
12609  *
12610  * Description: This implements the ludicrously complex rules for printing
12611  *		a "transport rejected" message.  This is to address the
12612  *		specific problem of having a flood of this error message
12613  *		produced when a failover occurs.
12614  *
12615  *     Context: Any.
12616  */
12617 
12618 static void
12619 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
12620 	int code)
12621 {
12622 	ASSERT(un != NULL);
12623 	ASSERT(mutex_owned(SD_MUTEX(un)));
12624 	ASSERT(xp != NULL);
12625 
12626 	/*
12627 	 * Print the "transport rejected" message under the following
12628 	 * conditions:
12629 	 *
12630 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
12631 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
12632 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
12633 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
12634 	 *   scsi_transport(9F) (which indicates that the target might have
12635 	 *   gone off-line).  This uses the un->un_tran_fatal_count
12636 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
12637 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
12638 	 *   from scsi_transport().
12639 	 *
12640 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
12641 	 * the preceeding cases in order for the message to be printed.
12642 	 */
12643 	if ((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) {
12644 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
12645 		    (code != TRAN_FATAL_ERROR) ||
12646 		    (un->un_tran_fatal_count == 1)) {
12647 			switch (code) {
12648 			case TRAN_BADPKT:
12649 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12650 				    "transport rejected bad packet\n");
12651 				break;
12652 			case TRAN_FATAL_ERROR:
12653 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12654 				    "transport rejected fatal error\n");
12655 				break;
12656 			default:
12657 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12658 				    "transport rejected (%d)\n", code);
12659 				break;
12660 			}
12661 		}
12662 	}
12663 }
12664 
12665 
12666 /*
12667  *    Function: sd_add_buf_to_waitq
12668  *
12669  * Description: Add the given buf(9S) struct to the wait queue for the
12670  *		instance.  If sorting is enabled, then the buf is added
12671  *		to the queue via an elevator sort algorithm (a la
12672  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
12673  *		If sorting is not enabled, then the buf is just added
12674  *		to the end of the wait queue.
12675  *
12676  * Return Code: void
12677  *
12678  *     Context: Does not sleep/block, therefore technically can be called
12679  *		from any context.  However if sorting is enabled then the
12680  *		execution time is indeterminate, and may take long if
12681  *		the wait queue grows large.
12682  */
12683 
12684 static void
12685 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
12686 {
12687 	struct buf *ap;
12688 
12689 	ASSERT(bp != NULL);
12690 	ASSERT(un != NULL);
12691 	ASSERT(mutex_owned(SD_MUTEX(un)));
12692 
12693 	/* If the queue is empty, add the buf as the only entry & return. */
12694 	if (un->un_waitq_headp == NULL) {
12695 		ASSERT(un->un_waitq_tailp == NULL);
12696 		un->un_waitq_headp = un->un_waitq_tailp = bp;
12697 		bp->av_forw = NULL;
12698 		return;
12699 	}
12700 
12701 	ASSERT(un->un_waitq_tailp != NULL);
12702 
12703 	/*
12704 	 * If sorting is disabled, just add the buf to the tail end of
12705 	 * the wait queue and return.
12706 	 */
12707 	if (un->un_f_disksort_disabled) {
12708 		un->un_waitq_tailp->av_forw = bp;
12709 		un->un_waitq_tailp = bp;
12710 		bp->av_forw = NULL;
12711 		return;
12712 	}
12713 
12714 	/*
12715 	 * Sort thru the list of requests currently on the wait queue
12716 	 * and add the new buf request at the appropriate position.
12717 	 *
12718 	 * The un->un_waitq_headp is an activity chain pointer on which
12719 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
12720 	 * first queue holds those requests which are positioned after
12721 	 * the current SD_GET_BLKNO() (in the first request); the second holds
12722 	 * requests which came in after their SD_GET_BLKNO() number was passed.
12723 	 * Thus we implement a one way scan, retracting after reaching
12724 	 * the end of the drive to the first request on the second
12725 	 * queue, at which time it becomes the first queue.
12726 	 * A one-way scan is natural because of the way UNIX read-ahead
12727 	 * blocks are allocated.
12728 	 *
12729 	 * If we lie after the first request, then we must locate the
12730 	 * second request list and add ourselves to it.
12731 	 */
12732 	ap = un->un_waitq_headp;
12733 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
12734 		while (ap->av_forw != NULL) {
12735 			/*
12736 			 * Look for an "inversion" in the (normally
12737 			 * ascending) block numbers. This indicates
12738 			 * the start of the second request list.
12739 			 */
12740 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
12741 				/*
12742 				 * Search the second request list for the
12743 				 * first request at a larger block number.
12744 				 * We go before that; however if there is
12745 				 * no such request, we go at the end.
12746 				 */
12747 				do {
12748 					if (SD_GET_BLKNO(bp) <
12749 					    SD_GET_BLKNO(ap->av_forw)) {
12750 						goto insert;
12751 					}
12752 					ap = ap->av_forw;
12753 				} while (ap->av_forw != NULL);
12754 				goto insert;		/* after last */
12755 			}
12756 			ap = ap->av_forw;
12757 		}
12758 
12759 		/*
12760 		 * No inversions... we will go after the last, and
12761 		 * be the first request in the second request list.
12762 		 */
12763 		goto insert;
12764 	}
12765 
12766 	/*
12767 	 * Request is at/after the current request...
12768 	 * sort in the first request list.
12769 	 */
12770 	while (ap->av_forw != NULL) {
12771 		/*
12772 		 * We want to go after the current request (1) if
12773 		 * there is an inversion after it (i.e. it is the end
12774 		 * of the first request list), or (2) if the next
12775 		 * request is a larger block no. than our request.
12776 		 */
12777 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
12778 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
12779 			goto insert;
12780 		}
12781 		ap = ap->av_forw;
12782 	}
12783 
12784 	/*
12785 	 * Neither a second list nor a larger request, therefore
12786 	 * we go at the end of the first list (which is the same
12787 	 * as the end of the whole schebang).
12788 	 */
12789 insert:
12790 	bp->av_forw = ap->av_forw;
12791 	ap->av_forw = bp;
12792 
12793 	/*
12794 	 * If we inserted onto the tail end of the waitq, make sure the
12795 	 * tail pointer is updated.
12796 	 */
12797 	if (ap == un->un_waitq_tailp) {
12798 		un->un_waitq_tailp = bp;
12799 	}
12800 }
12801 
12802 
12803 /*
12804  *    Function: sd_start_cmds
12805  *
12806  * Description: Remove and transport cmds from the driver queues.
12807  *
12808  *   Arguments: un - pointer to the unit (soft state) struct for the target.
12809  *
12810  *		immed_bp - ptr to a buf to be transported immediately. Only
12811  *		the immed_bp is transported; bufs on the waitq are not
12812  *		processed and the un_retry_bp is not checked.  If immed_bp is
12813  *		NULL, then normal queue processing is performed.
12814  *
12815  *     Context: May be called from kernel thread context, interrupt context,
12816  *		or runout callback context. This function may not block or
12817  *		call routines that block.
12818  */
12819 
12820 static void
12821 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
12822 {
12823 	struct	sd_xbuf	*xp;
12824 	struct	buf	*bp;
12825 	void	(*statp)(kstat_io_t *);
12826 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12827 	void	(*saved_statp)(kstat_io_t *);
12828 #endif
12829 	int	rval;
12830 
12831 	ASSERT(un != NULL);
12832 	ASSERT(mutex_owned(SD_MUTEX(un)));
12833 	ASSERT(un->un_ncmds_in_transport >= 0);
12834 	ASSERT(un->un_throttle >= 0);
12835 
12836 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
12837 
12838 	do {
12839 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12840 		saved_statp = NULL;
12841 #endif
12842 
12843 		/*
12844 		 * If we are syncing or dumping, fail the command to
12845 		 * avoid recursively calling back into scsi_transport().
12846 		 * The dump I/O itself uses a separate code path so this
12847 		 * only prevents non-dump I/O from being sent while dumping.
12848 		 * File system sync takes place before dumping begins.
12849 		 * During panic, filesystem I/O is allowed provided
12850 		 * un_in_callback is <= 1.  This is to prevent recursion
12851 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
12852 		 * sd_start_cmds and so on.  See panic.c for more information
12853 		 * about the states the system can be in during panic.
12854 		 */
12855 		if ((un->un_state == SD_STATE_DUMPING) ||
12856 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
12857 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12858 			    "sd_start_cmds: panicking\n");
12859 			goto exit;
12860 		}
12861 
12862 		if ((bp = immed_bp) != NULL) {
12863 			/*
12864 			 * We have a bp that must be transported immediately.
12865 			 * It's OK to transport the immed_bp here without doing
12866 			 * the throttle limit check because the immed_bp is
12867 			 * always used in a retry/recovery case. This means
12868 			 * that we know we are not at the throttle limit by
12869 			 * virtue of the fact that to get here we must have
12870 			 * already gotten a command back via sdintr(). This also
12871 			 * relies on (1) the command on un_retry_bp preventing
12872 			 * further commands from the waitq from being issued;
12873 			 * and (2) the code in sd_retry_command checking the
12874 			 * throttle limit before issuing a delayed or immediate
12875 			 * retry. This holds even if the throttle limit is
12876 			 * currently ratcheted down from its maximum value.
12877 			 */
12878 			statp = kstat_runq_enter;
12879 			if (bp == un->un_retry_bp) {
12880 				ASSERT((un->un_retry_statp == NULL) ||
12881 				    (un->un_retry_statp == kstat_waitq_enter) ||
12882 				    (un->un_retry_statp ==
12883 				    kstat_runq_back_to_waitq));
12884 				/*
12885 				 * If the waitq kstat was incremented when
12886 				 * sd_set_retry_bp() queued this bp for a retry,
12887 				 * then we must set up statp so that the waitq
12888 				 * count will get decremented correctly below.
12889 				 * Also we must clear un->un_retry_statp to
12890 				 * ensure that we do not act on a stale value
12891 				 * in this field.
12892 				 */
12893 				if ((un->un_retry_statp == kstat_waitq_enter) ||
12894 				    (un->un_retry_statp ==
12895 				    kstat_runq_back_to_waitq)) {
12896 					statp = kstat_waitq_to_runq;
12897 				}
12898 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12899 				saved_statp = un->un_retry_statp;
12900 #endif
12901 				un->un_retry_statp = NULL;
12902 
12903 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
12904 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
12905 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
12906 				    un, un->un_retry_bp, un->un_throttle,
12907 				    un->un_ncmds_in_transport);
12908 			} else {
12909 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
12910 				    "processing priority bp:0x%p\n", bp);
12911 			}
12912 
12913 		} else if ((bp = un->un_waitq_headp) != NULL) {
12914 			/*
12915 			 * A command on the waitq is ready to go, but do not
12916 			 * send it if:
12917 			 *
12918 			 * (1) the throttle limit has been reached, or
12919 			 * (2) a retry is pending, or
12920 			 * (3) a START_STOP_UNIT callback pending, or
12921 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
12922 			 *	command is pending.
12923 			 *
12924 			 * For all of these conditions, IO processing will
12925 			 * restart after the condition is cleared.
12926 			 */
12927 			if (un->un_ncmds_in_transport >= un->un_throttle) {
12928 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12929 				    "sd_start_cmds: exiting, "
12930 				    "throttle limit reached!\n");
12931 				goto exit;
12932 			}
12933 			if (un->un_retry_bp != NULL) {
12934 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12935 				    "sd_start_cmds: exiting, retry pending!\n");
12936 				goto exit;
12937 			}
12938 			if (un->un_startstop_timeid != NULL) {
12939 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12940 				    "sd_start_cmds: exiting, "
12941 				    "START_STOP pending!\n");
12942 				goto exit;
12943 			}
12944 			if (un->un_direct_priority_timeid != NULL) {
12945 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12946 				    "sd_start_cmds: exiting, "
12947 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
12948 				goto exit;
12949 			}
12950 
12951 			/* Dequeue the command */
12952 			un->un_waitq_headp = bp->av_forw;
12953 			if (un->un_waitq_headp == NULL) {
12954 				un->un_waitq_tailp = NULL;
12955 			}
12956 			bp->av_forw = NULL;
12957 			statp = kstat_waitq_to_runq;
12958 			SD_TRACE(SD_LOG_IO_CORE, un,
12959 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
12960 
12961 		} else {
12962 			/* No work to do so bail out now */
12963 			SD_TRACE(SD_LOG_IO_CORE, un,
12964 			    "sd_start_cmds: no more work, exiting!\n");
12965 			goto exit;
12966 		}
12967 
12968 		/*
12969 		 * Reset the state to normal. This is the mechanism by which
12970 		 * the state transitions from either SD_STATE_RWAIT or
12971 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
12972 		 * If state is SD_STATE_PM_CHANGING then this command is
12973 		 * part of the device power control and the state must
12974 		 * not be put back to normal. Doing so would would
12975 		 * allow new commands to proceed when they shouldn't,
12976 		 * the device may be going off.
12977 		 */
12978 		if ((un->un_state != SD_STATE_SUSPENDED) &&
12979 		    (un->un_state != SD_STATE_PM_CHANGING)) {
12980 			New_state(un, SD_STATE_NORMAL);
12981 		}
12982 
12983 		xp = SD_GET_XBUF(bp);
12984 		ASSERT(xp != NULL);
12985 
12986 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12987 		/*
12988 		 * Allocate the scsi_pkt if we need one, or attach DMA
12989 		 * resources if we have a scsi_pkt that needs them. The
12990 		 * latter should only occur for commands that are being
12991 		 * retried.
12992 		 */
12993 		if ((xp->xb_pktp == NULL) ||
12994 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
12995 #else
12996 		if (xp->xb_pktp == NULL) {
12997 #endif
12998 			/*
12999 			 * There is no scsi_pkt allocated for this buf. Call
13000 			 * the initpkt function to allocate & init one.
13001 			 *
13002 			 * The scsi_init_pkt runout callback functionality is
13003 			 * implemented as follows:
13004 			 *
13005 			 * 1) The initpkt function always calls
13006 			 *    scsi_init_pkt(9F) with sdrunout specified as the
13007 			 *    callback routine.
13008 			 * 2) A successful packet allocation is initialized and
13009 			 *    the I/O is transported.
13010 			 * 3) The I/O associated with an allocation resource
13011 			 *    failure is left on its queue to be retried via
13012 			 *    runout or the next I/O.
13013 			 * 4) The I/O associated with a DMA error is removed
13014 			 *    from the queue and failed with EIO. Processing of
13015 			 *    the transport queues is also halted to be
13016 			 *    restarted via runout or the next I/O.
13017 			 * 5) The I/O associated with a CDB size or packet
13018 			 *    size error is removed from the queue and failed
13019 			 *    with EIO. Processing of the transport queues is
13020 			 *    continued.
13021 			 *
13022 			 * Note: there is no interface for canceling a runout
13023 			 * callback. To prevent the driver from detaching or
13024 			 * suspending while a runout is pending the driver
13025 			 * state is set to SD_STATE_RWAIT
13026 			 *
13027 			 * Note: using the scsi_init_pkt callback facility can
13028 			 * result in an I/O request persisting at the head of
13029 			 * the list which cannot be satisfied even after
13030 			 * multiple retries. In the future the driver may
13031 			 * implement some kind of maximum runout count before
13032 			 * failing an I/O.
13033 			 *
13034 			 * Note: the use of funcp below may seem superfluous,
13035 			 * but it helps warlock figure out the correct
13036 			 * initpkt function calls (see [s]sd.wlcmd).
13037 			 */
13038 			struct scsi_pkt	*pktp;
13039 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
13040 
13041 			ASSERT(bp != un->un_rqs_bp);
13042 
13043 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
13044 			switch ((*funcp)(bp, &pktp)) {
13045 			case  SD_PKT_ALLOC_SUCCESS:
13046 				xp->xb_pktp = pktp;
13047 				SD_TRACE(SD_LOG_IO_CORE, un,
13048 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
13049 				    pktp);
13050 				goto got_pkt;
13051 
13052 			case SD_PKT_ALLOC_FAILURE:
13053 				/*
13054 				 * Temporary (hopefully) resource depletion.
13055 				 * Since retries and RQS commands always have a
13056 				 * scsi_pkt allocated, these cases should never
13057 				 * get here. So the only cases this needs to
13058 				 * handle is a bp from the waitq (which we put
13059 				 * back onto the waitq for sdrunout), or a bp
13060 				 * sent as an immed_bp (which we just fail).
13061 				 */
13062 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13063 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
13064 
13065 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13066 
13067 				if (bp == immed_bp) {
13068 					/*
13069 					 * If SD_XB_DMA_FREED is clear, then
13070 					 * this is a failure to allocate a
13071 					 * scsi_pkt, and we must fail the
13072 					 * command.
13073 					 */
13074 					if ((xp->xb_pkt_flags &
13075 					    SD_XB_DMA_FREED) == 0) {
13076 						break;
13077 					}
13078 
13079 					/*
13080 					 * If this immediate command is NOT our
13081 					 * un_retry_bp, then we must fail it.
13082 					 */
13083 					if (bp != un->un_retry_bp) {
13084 						break;
13085 					}
13086 
13087 					/*
13088 					 * We get here if this cmd is our
13089 					 * un_retry_bp that was DMAFREED, but
13090 					 * scsi_init_pkt() failed to reallocate
13091 					 * DMA resources when we attempted to
13092 					 * retry it. This can happen when an
13093 					 * mpxio failover is in progress, but
13094 					 * we don't want to just fail the
13095 					 * command in this case.
13096 					 *
13097 					 * Use timeout(9F) to restart it after
13098 					 * a 100ms delay.  We don't want to
13099 					 * let sdrunout() restart it, because
13100 					 * sdrunout() is just supposed to start
13101 					 * commands that are sitting on the
13102 					 * wait queue.  The un_retry_bp stays
13103 					 * set until the command completes, but
13104 					 * sdrunout can be called many times
13105 					 * before that happens.  Since sdrunout
13106 					 * cannot tell if the un_retry_bp is
13107 					 * already in the transport, it could
13108 					 * end up calling scsi_transport() for
13109 					 * the un_retry_bp multiple times.
13110 					 *
13111 					 * Also: don't schedule the callback
13112 					 * if some other callback is already
13113 					 * pending.
13114 					 */
13115 					if (un->un_retry_statp == NULL) {
13116 						/*
13117 						 * restore the kstat pointer to
13118 						 * keep kstat counts coherent
13119 						 * when we do retry the command.
13120 						 */
13121 						un->un_retry_statp =
13122 						    saved_statp;
13123 					}
13124 
13125 					if ((un->un_startstop_timeid == NULL) &&
13126 					    (un->un_retry_timeid == NULL) &&
13127 					    (un->un_direct_priority_timeid ==
13128 					    NULL)) {
13129 
13130 						un->un_retry_timeid =
13131 						    timeout(
13132 						    sd_start_retry_command,
13133 						    un, SD_RESTART_TIMEOUT);
13134 					}
13135 					goto exit;
13136 				}
13137 
13138 #else
13139 				if (bp == immed_bp) {
13140 					break;	/* Just fail the command */
13141 				}
13142 #endif
13143 
13144 				/* Add the buf back to the head of the waitq */
13145 				bp->av_forw = un->un_waitq_headp;
13146 				un->un_waitq_headp = bp;
13147 				if (un->un_waitq_tailp == NULL) {
13148 					un->un_waitq_tailp = bp;
13149 				}
13150 				goto exit;
13151 
13152 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
13153 				/*
13154 				 * HBA DMA resource failure. Fail the command
13155 				 * and continue processing of the queues.
13156 				 */
13157 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13158 				    "sd_start_cmds: "
13159 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
13160 				break;
13161 
13162 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
13163 				/*
13164 				 * Note:x86: Partial DMA mapping not supported
13165 				 * for USCSI commands, and all the needed DMA
13166 				 * resources were not allocated.
13167 				 */
13168 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13169 				    "sd_start_cmds: "
13170 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
13171 				break;
13172 
13173 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
13174 				/*
13175 				 * Note:x86: Request cannot fit into CDB based
13176 				 * on lba and len.
13177 				 */
13178 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13179 				    "sd_start_cmds: "
13180 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
13181 				break;
13182 
13183 			default:
13184 				/* Should NEVER get here! */
13185 				panic("scsi_initpkt error");
13186 				/*NOTREACHED*/
13187 			}
13188 
13189 			/*
13190 			 * Fatal error in allocating a scsi_pkt for this buf.
13191 			 * Update kstats & return the buf with an error code.
13192 			 * We must use sd_return_failed_command_no_restart() to
13193 			 * avoid a recursive call back into sd_start_cmds().
13194 			 * However this also means that we must keep processing
13195 			 * the waitq here in order to avoid stalling.
13196 			 */
13197 			if (statp == kstat_waitq_to_runq) {
13198 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
13199 			}
13200 			sd_return_failed_command_no_restart(un, bp, EIO);
13201 			if (bp == immed_bp) {
13202 				/* immed_bp is gone by now, so clear this */
13203 				immed_bp = NULL;
13204 			}
13205 			continue;
13206 		}
13207 got_pkt:
13208 		if (bp == immed_bp) {
13209 			/* goto the head of the class.... */
13210 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13211 		}
13212 
13213 		un->un_ncmds_in_transport++;
13214 		SD_UPDATE_KSTATS(un, statp, bp);
13215 
13216 		/*
13217 		 * Call scsi_transport() to send the command to the target.
13218 		 * According to SCSA architecture, we must drop the mutex here
13219 		 * before calling scsi_transport() in order to avoid deadlock.
13220 		 * Note that the scsi_pkt's completion routine can be executed
13221 		 * (from interrupt context) even before the call to
13222 		 * scsi_transport() returns.
13223 		 */
13224 		SD_TRACE(SD_LOG_IO_CORE, un,
13225 		    "sd_start_cmds: calling scsi_transport()\n");
13226 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
13227 
13228 		mutex_exit(SD_MUTEX(un));
13229 		rval = scsi_transport(xp->xb_pktp);
13230 		mutex_enter(SD_MUTEX(un));
13231 
13232 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13233 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
13234 
13235 		switch (rval) {
13236 		case TRAN_ACCEPT:
13237 			/* Clear this with every pkt accepted by the HBA */
13238 			un->un_tran_fatal_count = 0;
13239 			break;	/* Success; try the next cmd (if any) */
13240 
13241 		case TRAN_BUSY:
13242 			un->un_ncmds_in_transport--;
13243 			ASSERT(un->un_ncmds_in_transport >= 0);
13244 
13245 			/*
13246 			 * Don't retry request sense, the sense data
13247 			 * is lost when another request is sent.
13248 			 * Free up the rqs buf and retry
13249 			 * the original failed cmd.  Update kstat.
13250 			 */
13251 			if (bp == un->un_rqs_bp) {
13252 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13253 				bp = sd_mark_rqs_idle(un, xp);
13254 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
13255 				    NULL, NULL, EIO, SD_BSY_TIMEOUT / 500,
13256 				    kstat_waitq_enter);
13257 				goto exit;
13258 			}
13259 
13260 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13261 			/*
13262 			 * Free the DMA resources for the  scsi_pkt. This will
13263 			 * allow mpxio to select another path the next time
13264 			 * we call scsi_transport() with this scsi_pkt.
13265 			 * See sdintr() for the rationalization behind this.
13266 			 */
13267 			if ((un->un_f_is_fibre == TRUE) &&
13268 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
13269 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
13270 				scsi_dmafree(xp->xb_pktp);
13271 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
13272 			}
13273 #endif
13274 
13275 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
13276 				/*
13277 				 * Commands that are SD_PATH_DIRECT_PRIORITY
13278 				 * are for error recovery situations. These do
13279 				 * not use the normal command waitq, so if they
13280 				 * get a TRAN_BUSY we cannot put them back onto
13281 				 * the waitq for later retry. One possible
13282 				 * problem is that there could already be some
13283 				 * other command on un_retry_bp that is waiting
13284 				 * for this one to complete, so we would be
13285 				 * deadlocked if we put this command back onto
13286 				 * the waitq for later retry (since un_retry_bp
13287 				 * must complete before the driver gets back to
13288 				 * commands on the waitq).
13289 				 *
13290 				 * To avoid deadlock we must schedule a callback
13291 				 * that will restart this command after a set
13292 				 * interval.  This should keep retrying for as
13293 				 * long as the underlying transport keeps
13294 				 * returning TRAN_BUSY (just like for other
13295 				 * commands).  Use the same timeout interval as
13296 				 * for the ordinary TRAN_BUSY retry.
13297 				 */
13298 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13299 				    "sd_start_cmds: scsi_transport() returned "
13300 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
13301 
13302 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13303 				un->un_direct_priority_timeid =
13304 				    timeout(sd_start_direct_priority_command,
13305 				    bp, SD_BSY_TIMEOUT / 500);
13306 
13307 				goto exit;
13308 			}
13309 
13310 			/*
13311 			 * For TRAN_BUSY, we want to reduce the throttle value,
13312 			 * unless we are retrying a command.
13313 			 */
13314 			if (bp != un->un_retry_bp) {
13315 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
13316 			}
13317 
13318 			/*
13319 			 * Set up the bp to be tried again 10 ms later.
13320 			 * Note:x86: Is there a timeout value in the sd_lun
13321 			 * for this condition?
13322 			 */
13323 			sd_set_retry_bp(un, bp, SD_BSY_TIMEOUT / 500,
13324 			    kstat_runq_back_to_waitq);
13325 			goto exit;
13326 
13327 		case TRAN_FATAL_ERROR:
13328 			un->un_tran_fatal_count++;
13329 			/* FALLTHRU */
13330 
13331 		case TRAN_BADPKT:
13332 		default:
13333 			un->un_ncmds_in_transport--;
13334 			ASSERT(un->un_ncmds_in_transport >= 0);
13335 
13336 			/*
13337 			 * If this is our REQUEST SENSE command with a
13338 			 * transport error, we must get back the pointers
13339 			 * to the original buf, and mark the REQUEST
13340 			 * SENSE command as "available".
13341 			 */
13342 			if (bp == un->un_rqs_bp) {
13343 				bp = sd_mark_rqs_idle(un, xp);
13344 				xp = SD_GET_XBUF(bp);
13345 			} else {
13346 				/*
13347 				 * Legacy behavior: do not update transport
13348 				 * error count for request sense commands.
13349 				 */
13350 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
13351 			}
13352 
13353 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13354 			sd_print_transport_rejected_message(un, xp, rval);
13355 
13356 			/*
13357 			 * We must use sd_return_failed_command_no_restart() to
13358 			 * avoid a recursive call back into sd_start_cmds().
13359 			 * However this also means that we must keep processing
13360 			 * the waitq here in order to avoid stalling.
13361 			 */
13362 			sd_return_failed_command_no_restart(un, bp, EIO);
13363 
13364 			/*
13365 			 * Notify any threads waiting in sd_ddi_suspend() that
13366 			 * a command completion has occurred.
13367 			 */
13368 			if (un->un_state == SD_STATE_SUSPENDED) {
13369 				cv_broadcast(&un->un_disk_busy_cv);
13370 			}
13371 
13372 			if (bp == immed_bp) {
13373 				/* immed_bp is gone by now, so clear this */
13374 				immed_bp = NULL;
13375 			}
13376 			break;
13377 		}
13378 
13379 	} while (immed_bp == NULL);
13380 
13381 exit:
13382 	ASSERT(mutex_owned(SD_MUTEX(un)));
13383 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
13384 }
13385 
13386 
13387 /*
13388  *    Function: sd_return_command
13389  *
13390  * Description: Returns a command to its originator (with or without an
13391  *		error).  Also starts commands waiting to be transported
13392  *		to the target.
13393  *
13394  *     Context: May be called from interrupt, kernel, or timeout context
13395  */
13396 
13397 static void
13398 sd_return_command(struct sd_lun *un, struct buf *bp)
13399 {
13400 	struct sd_xbuf *xp;
13401 #if defined(__i386) || defined(__amd64)
13402 	struct scsi_pkt *pktp;
13403 #endif
13404 
13405 	ASSERT(bp != NULL);
13406 	ASSERT(un != NULL);
13407 	ASSERT(mutex_owned(SD_MUTEX(un)));
13408 	ASSERT(bp != un->un_rqs_bp);
13409 	xp = SD_GET_XBUF(bp);
13410 	ASSERT(xp != NULL);
13411 
13412 #if defined(__i386) || defined(__amd64)
13413 	pktp = SD_GET_PKTP(bp);
13414 #endif
13415 
13416 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
13417 
13418 #if defined(__i386) || defined(__amd64)
13419 	/*
13420 	 * Note:x86: check for the "sdrestart failed" case.
13421 	 */
13422 	if (((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
13423 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
13424 	    (xp->xb_pktp->pkt_resid == 0)) {
13425 
13426 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
13427 			/*
13428 			 * Successfully set up next portion of cmd
13429 			 * transfer, try sending it
13430 			 */
13431 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
13432 			    NULL, NULL, 0, (clock_t)0, NULL);
13433 			sd_start_cmds(un, NULL);
13434 			return;	/* Note:x86: need a return here? */
13435 		}
13436 	}
13437 #endif
13438 
13439 	/*
13440 	 * If this is the failfast bp, clear it from un_failfast_bp. This
13441 	 * can happen if upon being re-tried the failfast bp either
13442 	 * succeeded or encountered another error (possibly even a different
13443 	 * error than the one that precipitated the failfast state, but in
13444 	 * that case it would have had to exhaust retries as well). Regardless,
13445 	 * this should not occur whenever the instance is in the active
13446 	 * failfast state.
13447 	 */
13448 	if (bp == un->un_failfast_bp) {
13449 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13450 		un->un_failfast_bp = NULL;
13451 	}
13452 
13453 	/*
13454 	 * Clear the failfast state upon successful completion of ANY cmd.
13455 	 */
13456 	if (bp->b_error == 0) {
13457 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13458 	}
13459 
13460 	/*
13461 	 * This is used if the command was retried one or more times. Show that
13462 	 * we are done with it, and allow processing of the waitq to resume.
13463 	 */
13464 	if (bp == un->un_retry_bp) {
13465 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13466 		    "sd_return_command: un:0x%p: "
13467 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13468 		un->un_retry_bp = NULL;
13469 		un->un_retry_statp = NULL;
13470 	}
13471 
13472 	SD_UPDATE_RDWR_STATS(un, bp);
13473 	SD_UPDATE_PARTITION_STATS(un, bp);
13474 
13475 	switch (un->un_state) {
13476 	case SD_STATE_SUSPENDED:
13477 		/*
13478 		 * Notify any threads waiting in sd_ddi_suspend() that
13479 		 * a command completion has occurred.
13480 		 */
13481 		cv_broadcast(&un->un_disk_busy_cv);
13482 		break;
13483 	default:
13484 		sd_start_cmds(un, NULL);
13485 		break;
13486 	}
13487 
13488 	/* Return this command up the iodone chain to its originator. */
13489 	mutex_exit(SD_MUTEX(un));
13490 
13491 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13492 	xp->xb_pktp = NULL;
13493 
13494 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13495 
13496 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13497 	mutex_enter(SD_MUTEX(un));
13498 
13499 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
13500 }
13501 
13502 
13503 /*
13504  *    Function: sd_return_failed_command
13505  *
13506  * Description: Command completion when an error occurred.
13507  *
13508  *     Context: May be called from interrupt context
13509  */
13510 
13511 static void
13512 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
13513 {
13514 	ASSERT(bp != NULL);
13515 	ASSERT(un != NULL);
13516 	ASSERT(mutex_owned(SD_MUTEX(un)));
13517 
13518 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13519 	    "sd_return_failed_command: entry\n");
13520 
13521 	/*
13522 	 * b_resid could already be nonzero due to a partial data
13523 	 * transfer, so do not change it here.
13524 	 */
13525 	SD_BIOERROR(bp, errcode);
13526 
13527 	sd_return_command(un, bp);
13528 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13529 	    "sd_return_failed_command: exit\n");
13530 }
13531 
13532 
13533 /*
13534  *    Function: sd_return_failed_command_no_restart
13535  *
13536  * Description: Same as sd_return_failed_command, but ensures that no
13537  *		call back into sd_start_cmds will be issued.
13538  *
13539  *     Context: May be called from interrupt context
13540  */
13541 
13542 static void
13543 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
13544 	int errcode)
13545 {
13546 	struct sd_xbuf *xp;
13547 
13548 	ASSERT(bp != NULL);
13549 	ASSERT(un != NULL);
13550 	ASSERT(mutex_owned(SD_MUTEX(un)));
13551 	xp = SD_GET_XBUF(bp);
13552 	ASSERT(xp != NULL);
13553 	ASSERT(errcode != 0);
13554 
13555 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13556 	    "sd_return_failed_command_no_restart: entry\n");
13557 
13558 	/*
13559 	 * b_resid could already be nonzero due to a partial data
13560 	 * transfer, so do not change it here.
13561 	 */
13562 	SD_BIOERROR(bp, errcode);
13563 
13564 	/*
13565 	 * If this is the failfast bp, clear it. This can happen if the
13566 	 * failfast bp encounterd a fatal error when we attempted to
13567 	 * re-try it (such as a scsi_transport(9F) failure).  However
13568 	 * we should NOT be in an active failfast state if the failfast
13569 	 * bp is not NULL.
13570 	 */
13571 	if (bp == un->un_failfast_bp) {
13572 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13573 		un->un_failfast_bp = NULL;
13574 	}
13575 
13576 	if (bp == un->un_retry_bp) {
13577 		/*
13578 		 * This command was retried one or more times. Show that we are
13579 		 * done with it, and allow processing of the waitq to resume.
13580 		 */
13581 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13582 		    "sd_return_failed_command_no_restart: "
13583 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13584 		un->un_retry_bp = NULL;
13585 		un->un_retry_statp = NULL;
13586 	}
13587 
13588 	SD_UPDATE_RDWR_STATS(un, bp);
13589 	SD_UPDATE_PARTITION_STATS(un, bp);
13590 
13591 	mutex_exit(SD_MUTEX(un));
13592 
13593 	if (xp->xb_pktp != NULL) {
13594 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13595 		xp->xb_pktp = NULL;
13596 	}
13597 
13598 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13599 
13600 	mutex_enter(SD_MUTEX(un));
13601 
13602 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13603 	    "sd_return_failed_command_no_restart: exit\n");
13604 }
13605 
13606 
13607 /*
13608  *    Function: sd_retry_command
13609  *
13610  * Description: queue up a command for retry, or (optionally) fail it
13611  *		if retry counts are exhausted.
13612  *
13613  *   Arguments: un - Pointer to the sd_lun struct for the target.
13614  *
13615  *		bp - Pointer to the buf for the command to be retried.
13616  *
13617  *		retry_check_flag - Flag to see which (if any) of the retry
13618  *		   counts should be decremented/checked. If the indicated
13619  *		   retry count is exhausted, then the command will not be
13620  *		   retried; it will be failed instead. This should use a
13621  *		   value equal to one of the following:
13622  *
13623  *			SD_RETRIES_NOCHECK
13624  *			SD_RESD_RETRIES_STANDARD
13625  *			SD_RETRIES_VICTIM
13626  *
13627  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
13628  *		   if the check should be made to see of FLAG_ISOLATE is set
13629  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
13630  *		   not retried, it is simply failed.
13631  *
13632  *		user_funcp - Ptr to function to call before dispatching the
13633  *		   command. May be NULL if no action needs to be performed.
13634  *		   (Primarily intended for printing messages.)
13635  *
13636  *		user_arg - Optional argument to be passed along to
13637  *		   the user_funcp call.
13638  *
13639  *		failure_code - errno return code to set in the bp if the
13640  *		   command is going to be failed.
13641  *
13642  *		retry_delay - Retry delay interval in (clock_t) units. May
13643  *		   be zero which indicates that the retry should be retried
13644  *		   immediately (ie, without an intervening delay).
13645  *
13646  *		statp - Ptr to kstat function to be updated if the command
13647  *		   is queued for a delayed retry. May be NULL if no kstat
13648  *		   update is desired.
13649  *
13650  *     Context: May be called from interrupt context.
13651  */
13652 
13653 static void
13654 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
13655 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int
13656 	code), void *user_arg, int failure_code,  clock_t retry_delay,
13657 	void (*statp)(kstat_io_t *))
13658 {
13659 	struct sd_xbuf	*xp;
13660 	struct scsi_pkt	*pktp;
13661 
13662 	ASSERT(un != NULL);
13663 	ASSERT(mutex_owned(SD_MUTEX(un)));
13664 	ASSERT(bp != NULL);
13665 	xp = SD_GET_XBUF(bp);
13666 	ASSERT(xp != NULL);
13667 	pktp = SD_GET_PKTP(bp);
13668 	ASSERT(pktp != NULL);
13669 
13670 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
13671 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
13672 
13673 	/*
13674 	 * If we are syncing or dumping, fail the command to avoid
13675 	 * recursively calling back into scsi_transport().
13676 	 */
13677 	if (ddi_in_panic()) {
13678 		goto fail_command_no_log;
13679 	}
13680 
13681 	/*
13682 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
13683 	 * log an error and fail the command.
13684 	 */
13685 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
13686 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
13687 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
13688 		sd_dump_memory(un, SD_LOG_IO, "CDB",
13689 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
13690 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
13691 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
13692 		goto fail_command;
13693 	}
13694 
13695 	/*
13696 	 * If we are suspended, then put the command onto head of the
13697 	 * wait queue since we don't want to start more commands, and
13698 	 * clear the un_retry_bp. Next time when we are resumed, will
13699 	 * handle the command in the wait queue.
13700 	 */
13701 	switch (un->un_state) {
13702 	case SD_STATE_SUSPENDED:
13703 	case SD_STATE_DUMPING:
13704 		bp->av_forw = un->un_waitq_headp;
13705 		un->un_waitq_headp = bp;
13706 		if (un->un_waitq_tailp == NULL) {
13707 			un->un_waitq_tailp = bp;
13708 		}
13709 		if (bp == un->un_retry_bp) {
13710 			un->un_retry_bp = NULL;
13711 			un->un_retry_statp = NULL;
13712 		}
13713 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13714 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
13715 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
13716 		return;
13717 	default:
13718 		break;
13719 	}
13720 
13721 	/*
13722 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
13723 	 * is set; if it is then we do not want to retry the command.
13724 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
13725 	 */
13726 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
13727 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
13728 			goto fail_command;
13729 		}
13730 	}
13731 
13732 
13733 	/*
13734 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
13735 	 * command timeout or a selection timeout has occurred. This means
13736 	 * that we were unable to establish an kind of communication with
13737 	 * the target, and subsequent retries and/or commands are likely
13738 	 * to encounter similar results and take a long time to complete.
13739 	 *
13740 	 * If this is a failfast error condition, we need to update the
13741 	 * failfast state, even if this bp does not have B_FAILFAST set.
13742 	 */
13743 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
13744 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
13745 			ASSERT(un->un_failfast_bp == NULL);
13746 			/*
13747 			 * If we are already in the active failfast state, and
13748 			 * another failfast error condition has been detected,
13749 			 * then fail this command if it has B_FAILFAST set.
13750 			 * If B_FAILFAST is clear, then maintain the legacy
13751 			 * behavior of retrying heroically, even tho this will
13752 			 * take a lot more time to fail the command.
13753 			 */
13754 			if (bp->b_flags & B_FAILFAST) {
13755 				goto fail_command;
13756 			}
13757 		} else {
13758 			/*
13759 			 * We're not in the active failfast state, but we
13760 			 * have a failfast error condition, so we must begin
13761 			 * transition to the next state. We do this regardless
13762 			 * of whether or not this bp has B_FAILFAST set.
13763 			 */
13764 			if (un->un_failfast_bp == NULL) {
13765 				/*
13766 				 * This is the first bp to meet a failfast
13767 				 * condition so save it on un_failfast_bp &
13768 				 * do normal retry processing. Do not enter
13769 				 * active failfast state yet. This marks
13770 				 * entry into the "failfast pending" state.
13771 				 */
13772 				un->un_failfast_bp = bp;
13773 
13774 			} else if (un->un_failfast_bp == bp) {
13775 				/*
13776 				 * This is the second time *this* bp has
13777 				 * encountered a failfast error condition,
13778 				 * so enter active failfast state & flush
13779 				 * queues as appropriate.
13780 				 */
13781 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
13782 				un->un_failfast_bp = NULL;
13783 				sd_failfast_flushq(un);
13784 
13785 				/*
13786 				 * Fail this bp now if B_FAILFAST set;
13787 				 * otherwise continue with retries. (It would
13788 				 * be pretty ironic if this bp succeeded on a
13789 				 * subsequent retry after we just flushed all
13790 				 * the queues).
13791 				 */
13792 				if (bp->b_flags & B_FAILFAST) {
13793 					goto fail_command;
13794 				}
13795 
13796 #if !defined(lint) && !defined(__lint)
13797 			} else {
13798 				/*
13799 				 * If neither of the preceeding conditionals
13800 				 * was true, it means that there is some
13801 				 * *other* bp that has met an inital failfast
13802 				 * condition and is currently either being
13803 				 * retried or is waiting to be retried. In
13804 				 * that case we should perform normal retry
13805 				 * processing on *this* bp, since there is a
13806 				 * chance that the current failfast condition
13807 				 * is transient and recoverable. If that does
13808 				 * not turn out to be the case, then retries
13809 				 * will be cleared when the wait queue is
13810 				 * flushed anyway.
13811 				 */
13812 #endif
13813 			}
13814 		}
13815 	} else {
13816 		/*
13817 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
13818 		 * likely were able to at least establish some level of
13819 		 * communication with the target and subsequent commands
13820 		 * and/or retries are likely to get through to the target,
13821 		 * In this case we want to be aggressive about clearing
13822 		 * the failfast state. Note that this does not affect
13823 		 * the "failfast pending" condition.
13824 		 */
13825 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13826 	}
13827 
13828 
13829 	/*
13830 	 * Check the specified retry count to see if we can still do
13831 	 * any retries with this pkt before we should fail it.
13832 	 */
13833 	switch (retry_check_flag & SD_RETRIES_MASK) {
13834 	case SD_RETRIES_VICTIM:
13835 		/*
13836 		 * Check the victim retry count. If exhausted, then fall
13837 		 * thru & check against the standard retry count.
13838 		 */
13839 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
13840 			/* Increment count & proceed with the retry */
13841 			xp->xb_victim_retry_count++;
13842 			break;
13843 		}
13844 		/* Victim retries exhausted, fall back to std. retries... */
13845 		/* FALLTHRU */
13846 
13847 	case SD_RETRIES_STANDARD:
13848 		if (xp->xb_retry_count >= un->un_retry_count) {
13849 			/* Retries exhausted, fail the command */
13850 			SD_TRACE(SD_LOG_IO_CORE, un,
13851 			    "sd_retry_command: retries exhausted!\n");
13852 			/*
13853 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
13854 			 * commands with nonzero pkt_resid.
13855 			 */
13856 			if ((pktp->pkt_reason == CMD_CMPLT) &&
13857 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
13858 			    (pktp->pkt_resid != 0)) {
13859 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
13860 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
13861 					SD_UPDATE_B_RESID(bp, pktp);
13862 				}
13863 			}
13864 			goto fail_command;
13865 		}
13866 		xp->xb_retry_count++;
13867 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13868 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13869 		break;
13870 
13871 	case SD_RETRIES_UA:
13872 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
13873 			/* Retries exhausted, fail the command */
13874 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13875 			    "Unit Attention retries exhausted. "
13876 			    "Check the target.\n");
13877 			goto fail_command;
13878 		}
13879 		xp->xb_ua_retry_count++;
13880 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13881 		    "sd_retry_command: retry count:%d\n",
13882 		    xp->xb_ua_retry_count);
13883 		break;
13884 
13885 	case SD_RETRIES_BUSY:
13886 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
13887 			/* Retries exhausted, fail the command */
13888 			SD_TRACE(SD_LOG_IO_CORE, un,
13889 			    "sd_retry_command: retries exhausted!\n");
13890 			goto fail_command;
13891 		}
13892 		xp->xb_retry_count++;
13893 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13894 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13895 		break;
13896 
13897 	case SD_RETRIES_NOCHECK:
13898 	default:
13899 		/* No retry count to check. Just proceed with the retry */
13900 		break;
13901 	}
13902 
13903 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13904 
13905 	/*
13906 	 * If we were given a zero timeout, we must attempt to retry the
13907 	 * command immediately (ie, without a delay).
13908 	 */
13909 	if (retry_delay == 0) {
13910 		/*
13911 		 * Check some limiting conditions to see if we can actually
13912 		 * do the immediate retry.  If we cannot, then we must
13913 		 * fall back to queueing up a delayed retry.
13914 		 */
13915 		if (un->un_ncmds_in_transport >= un->un_throttle) {
13916 			/*
13917 			 * We are at the throttle limit for the target,
13918 			 * fall back to delayed retry.
13919 			 */
13920 			retry_delay = SD_BSY_TIMEOUT;
13921 			statp = kstat_waitq_enter;
13922 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13923 			    "sd_retry_command: immed. retry hit "
13924 			    "throttle!\n");
13925 		} else {
13926 			/*
13927 			 * We're clear to proceed with the immediate retry.
13928 			 * First call the user-provided function (if any)
13929 			 */
13930 			if (user_funcp != NULL) {
13931 				(*user_funcp)(un, bp, user_arg,
13932 				    SD_IMMEDIATE_RETRY_ISSUED);
13933 #ifdef __lock_lint
13934 				sd_print_incomplete_msg(un, bp, user_arg,
13935 				    SD_IMMEDIATE_RETRY_ISSUED);
13936 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
13937 				    SD_IMMEDIATE_RETRY_ISSUED);
13938 				sd_print_sense_failed_msg(un, bp, user_arg,
13939 				    SD_IMMEDIATE_RETRY_ISSUED);
13940 #endif
13941 			}
13942 
13943 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13944 			    "sd_retry_command: issuing immediate retry\n");
13945 
13946 			/*
13947 			 * Call sd_start_cmds() to transport the command to
13948 			 * the target.
13949 			 */
13950 			sd_start_cmds(un, bp);
13951 
13952 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13953 			    "sd_retry_command exit\n");
13954 			return;
13955 		}
13956 	}
13957 
13958 	/*
13959 	 * Set up to retry the command after a delay.
13960 	 * First call the user-provided function (if any)
13961 	 */
13962 	if (user_funcp != NULL) {
13963 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
13964 	}
13965 
13966 	sd_set_retry_bp(un, bp, retry_delay, statp);
13967 
13968 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
13969 	return;
13970 
13971 fail_command:
13972 
13973 	if (user_funcp != NULL) {
13974 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
13975 	}
13976 
13977 fail_command_no_log:
13978 
13979 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13980 	    "sd_retry_command: returning failed command\n");
13981 
13982 	sd_return_failed_command(un, bp, failure_code);
13983 
13984 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
13985 }
13986 
13987 
13988 /*
13989  *    Function: sd_set_retry_bp
13990  *
13991  * Description: Set up the given bp for retry.
13992  *
13993  *   Arguments: un - ptr to associated softstate
13994  *		bp - ptr to buf(9S) for the command
13995  *		retry_delay - time interval before issuing retry (may be 0)
13996  *		statp - optional pointer to kstat function
13997  *
13998  *     Context: May be called under interrupt context
13999  */
14000 
14001 static void
14002 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
14003 	void (*statp)(kstat_io_t *))
14004 {
14005 	ASSERT(un != NULL);
14006 	ASSERT(mutex_owned(SD_MUTEX(un)));
14007 	ASSERT(bp != NULL);
14008 
14009 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14010 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
14011 
14012 	/*
14013 	 * Indicate that the command is being retried. This will not allow any
14014 	 * other commands on the wait queue to be transported to the target
14015 	 * until this command has been completed (success or failure). The
14016 	 * "retry command" is not transported to the target until the given
14017 	 * time delay expires, unless the user specified a 0 retry_delay.
14018 	 *
14019 	 * Note: the timeout(9F) callback routine is what actually calls
14020 	 * sd_start_cmds() to transport the command, with the exception of a
14021 	 * zero retry_delay. The only current implementor of a zero retry delay
14022 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
14023 	 */
14024 	if (un->un_retry_bp == NULL) {
14025 		ASSERT(un->un_retry_statp == NULL);
14026 		un->un_retry_bp = bp;
14027 
14028 		/*
14029 		 * If the user has not specified a delay the command should
14030 		 * be queued and no timeout should be scheduled.
14031 		 */
14032 		if (retry_delay == 0) {
14033 			/*
14034 			 * Save the kstat pointer that will be used in the
14035 			 * call to SD_UPDATE_KSTATS() below, so that
14036 			 * sd_start_cmds() can correctly decrement the waitq
14037 			 * count when it is time to transport this command.
14038 			 */
14039 			un->un_retry_statp = statp;
14040 			goto done;
14041 		}
14042 	}
14043 
14044 	if (un->un_retry_bp == bp) {
14045 		/*
14046 		 * Save the kstat pointer that will be used in the call to
14047 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
14048 		 * correctly decrement the waitq count when it is time to
14049 		 * transport this command.
14050 		 */
14051 		un->un_retry_statp = statp;
14052 
14053 		/*
14054 		 * Schedule a timeout if:
14055 		 *   1) The user has specified a delay.
14056 		 *   2) There is not a START_STOP_UNIT callback pending.
14057 		 *
14058 		 * If no delay has been specified, then it is up to the caller
14059 		 * to ensure that IO processing continues without stalling.
14060 		 * Effectively, this means that the caller will issue the
14061 		 * required call to sd_start_cmds(). The START_STOP_UNIT
14062 		 * callback does this after the START STOP UNIT command has
14063 		 * completed. In either of these cases we should not schedule
14064 		 * a timeout callback here.  Also don't schedule the timeout if
14065 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
14066 		 */
14067 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
14068 		    (un->un_direct_priority_timeid == NULL)) {
14069 			un->un_retry_timeid =
14070 			    timeout(sd_start_retry_command, un, retry_delay);
14071 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14072 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
14073 			    " bp:0x%p un_retry_timeid:0x%p\n",
14074 			    un, bp, un->un_retry_timeid);
14075 		}
14076 	} else {
14077 		/*
14078 		 * We only get in here if there is already another command
14079 		 * waiting to be retried.  In this case, we just put the
14080 		 * given command onto the wait queue, so it can be transported
14081 		 * after the current retry command has completed.
14082 		 *
14083 		 * Also we have to make sure that if the command at the head
14084 		 * of the wait queue is the un_failfast_bp, that we do not
14085 		 * put ahead of it any other commands that are to be retried.
14086 		 */
14087 		if ((un->un_failfast_bp != NULL) &&
14088 		    (un->un_failfast_bp == un->un_waitq_headp)) {
14089 			/*
14090 			 * Enqueue this command AFTER the first command on
14091 			 * the wait queue (which is also un_failfast_bp).
14092 			 */
14093 			bp->av_forw = un->un_waitq_headp->av_forw;
14094 			un->un_waitq_headp->av_forw = bp;
14095 			if (un->un_waitq_headp == un->un_waitq_tailp) {
14096 				un->un_waitq_tailp = bp;
14097 			}
14098 		} else {
14099 			/* Enqueue this command at the head of the waitq. */
14100 			bp->av_forw = un->un_waitq_headp;
14101 			un->un_waitq_headp = bp;
14102 			if (un->un_waitq_tailp == NULL) {
14103 				un->un_waitq_tailp = bp;
14104 			}
14105 		}
14106 
14107 		if (statp == NULL) {
14108 			statp = kstat_waitq_enter;
14109 		}
14110 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14111 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
14112 	}
14113 
14114 done:
14115 	if (statp != NULL) {
14116 		SD_UPDATE_KSTATS(un, statp, bp);
14117 	}
14118 
14119 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14120 	    "sd_set_retry_bp: exit un:0x%p\n", un);
14121 }
14122 
14123 
14124 /*
14125  *    Function: sd_start_retry_command
14126  *
14127  * Description: Start the command that has been waiting on the target's
14128  *		retry queue.  Called from timeout(9F) context after the
14129  *		retry delay interval has expired.
14130  *
14131  *   Arguments: arg - pointer to associated softstate for the device.
14132  *
14133  *     Context: timeout(9F) thread context.  May not sleep.
14134  */
14135 
14136 static void
14137 sd_start_retry_command(void *arg)
14138 {
14139 	struct sd_lun *un = arg;
14140 
14141 	ASSERT(un != NULL);
14142 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14143 
14144 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14145 	    "sd_start_retry_command: entry\n");
14146 
14147 	mutex_enter(SD_MUTEX(un));
14148 
14149 	un->un_retry_timeid = NULL;
14150 
14151 	if (un->un_retry_bp != NULL) {
14152 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14153 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
14154 		    un, un->un_retry_bp);
14155 		sd_start_cmds(un, un->un_retry_bp);
14156 	}
14157 
14158 	mutex_exit(SD_MUTEX(un));
14159 
14160 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14161 	    "sd_start_retry_command: exit\n");
14162 }
14163 
14164 
14165 /*
14166  *    Function: sd_start_direct_priority_command
14167  *
14168  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
14169  *		received TRAN_BUSY when we called scsi_transport() to send it
14170  *		to the underlying HBA. This function is called from timeout(9F)
14171  *		context after the delay interval has expired.
14172  *
14173  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
14174  *
14175  *     Context: timeout(9F) thread context.  May not sleep.
14176  */
14177 
14178 static void
14179 sd_start_direct_priority_command(void *arg)
14180 {
14181 	struct buf	*priority_bp = arg;
14182 	struct sd_lun	*un;
14183 
14184 	ASSERT(priority_bp != NULL);
14185 	un = SD_GET_UN(priority_bp);
14186 	ASSERT(un != NULL);
14187 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14188 
14189 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14190 	    "sd_start_direct_priority_command: entry\n");
14191 
14192 	mutex_enter(SD_MUTEX(un));
14193 	un->un_direct_priority_timeid = NULL;
14194 	sd_start_cmds(un, priority_bp);
14195 	mutex_exit(SD_MUTEX(un));
14196 
14197 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14198 	    "sd_start_direct_priority_command: exit\n");
14199 }
14200 
14201 
14202 /*
14203  *    Function: sd_send_request_sense_command
14204  *
14205  * Description: Sends a REQUEST SENSE command to the target
14206  *
14207  *     Context: May be called from interrupt context.
14208  */
14209 
14210 static void
14211 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
14212 	struct scsi_pkt *pktp)
14213 {
14214 	ASSERT(bp != NULL);
14215 	ASSERT(un != NULL);
14216 	ASSERT(mutex_owned(SD_MUTEX(un)));
14217 
14218 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
14219 	    "entry: buf:0x%p\n", bp);
14220 
14221 	/*
14222 	 * If we are syncing or dumping, then fail the command to avoid a
14223 	 * recursive callback into scsi_transport(). Also fail the command
14224 	 * if we are suspended (legacy behavior).
14225 	 */
14226 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
14227 	    (un->un_state == SD_STATE_DUMPING)) {
14228 		sd_return_failed_command(un, bp, EIO);
14229 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14230 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
14231 		return;
14232 	}
14233 
14234 	/*
14235 	 * Retry the failed command and don't issue the request sense if:
14236 	 *    1) the sense buf is busy
14237 	 *    2) we have 1 or more outstanding commands on the target
14238 	 *    (the sense data will be cleared or invalidated any way)
14239 	 *
14240 	 * Note: There could be an issue with not checking a retry limit here,
14241 	 * the problem is determining which retry limit to check.
14242 	 */
14243 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
14244 		/* Don't retry if the command is flagged as non-retryable */
14245 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
14246 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
14247 			    NULL, NULL, 0, SD_BSY_TIMEOUT, kstat_waitq_enter);
14248 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14249 			    "sd_send_request_sense_command: "
14250 			    "at full throttle, retrying exit\n");
14251 		} else {
14252 			sd_return_failed_command(un, bp, EIO);
14253 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14254 			    "sd_send_request_sense_command: "
14255 			    "at full throttle, non-retryable exit\n");
14256 		}
14257 		return;
14258 	}
14259 
14260 	sd_mark_rqs_busy(un, bp);
14261 	sd_start_cmds(un, un->un_rqs_bp);
14262 
14263 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14264 	    "sd_send_request_sense_command: exit\n");
14265 }
14266 
14267 
14268 /*
14269  *    Function: sd_mark_rqs_busy
14270  *
14271  * Description: Indicate that the request sense bp for this instance is
14272  *		in use.
14273  *
14274  *     Context: May be called under interrupt context
14275  */
14276 
14277 static void
14278 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
14279 {
14280 	struct sd_xbuf	*sense_xp;
14281 
14282 	ASSERT(un != NULL);
14283 	ASSERT(bp != NULL);
14284 	ASSERT(mutex_owned(SD_MUTEX(un)));
14285 	ASSERT(un->un_sense_isbusy == 0);
14286 
14287 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
14288 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
14289 
14290 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
14291 	ASSERT(sense_xp != NULL);
14292 
14293 	SD_INFO(SD_LOG_IO, un,
14294 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
14295 
14296 	ASSERT(sense_xp->xb_pktp != NULL);
14297 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
14298 	    == (FLAG_SENSING | FLAG_HEAD));
14299 
14300 	un->un_sense_isbusy = 1;
14301 	un->un_rqs_bp->b_resid = 0;
14302 	sense_xp->xb_pktp->pkt_resid  = 0;
14303 	sense_xp->xb_pktp->pkt_reason = 0;
14304 
14305 	/* So we can get back the bp at interrupt time! */
14306 	sense_xp->xb_sense_bp = bp;
14307 
14308 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
14309 
14310 	/*
14311 	 * Mark this buf as awaiting sense data. (This is already set in
14312 	 * the pkt_flags for the RQS packet.)
14313 	 */
14314 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
14315 
14316 	sense_xp->xb_retry_count	= 0;
14317 	sense_xp->xb_victim_retry_count = 0;
14318 	sense_xp->xb_ua_retry_count	= 0;
14319 	sense_xp->xb_nr_retry_count 	= 0;
14320 	sense_xp->xb_dma_resid  = 0;
14321 
14322 	/* Clean up the fields for auto-request sense */
14323 	sense_xp->xb_sense_status = 0;
14324 	sense_xp->xb_sense_state  = 0;
14325 	sense_xp->xb_sense_resid  = 0;
14326 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
14327 
14328 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
14329 }
14330 
14331 
14332 /*
14333  *    Function: sd_mark_rqs_idle
14334  *
14335  * Description: SD_MUTEX must be held continuously through this routine
14336  *		to prevent reuse of the rqs struct before the caller can
14337  *		complete it's processing.
14338  *
14339  * Return Code: Pointer to the RQS buf
14340  *
14341  *     Context: May be called under interrupt context
14342  */
14343 
14344 static struct buf *
14345 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
14346 {
14347 	struct buf *bp;
14348 	ASSERT(un != NULL);
14349 	ASSERT(sense_xp != NULL);
14350 	ASSERT(mutex_owned(SD_MUTEX(un)));
14351 	ASSERT(un->un_sense_isbusy != 0);
14352 
14353 	un->un_sense_isbusy = 0;
14354 	bp = sense_xp->xb_sense_bp;
14355 	sense_xp->xb_sense_bp = NULL;
14356 
14357 	/* This pkt is no longer interested in getting sense data */
14358 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
14359 
14360 	return (bp);
14361 }
14362 
14363 
14364 
14365 /*
14366  *    Function: sd_alloc_rqs
14367  *
14368  * Description: Set up the unit to receive auto request sense data
14369  *
14370  * Return Code: DDI_SUCCESS or DDI_FAILURE
14371  *
14372  *     Context: Called under attach(9E) context
14373  */
14374 
14375 static int
14376 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
14377 {
14378 	struct sd_xbuf *xp;
14379 
14380 	ASSERT(un != NULL);
14381 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14382 	ASSERT(un->un_rqs_bp == NULL);
14383 	ASSERT(un->un_rqs_pktp == NULL);
14384 
14385 	/*
14386 	 * First allocate the required buf and scsi_pkt structs, then set up
14387 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
14388 	 */
14389 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
14390 	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
14391 	if (un->un_rqs_bp == NULL) {
14392 		return (DDI_FAILURE);
14393 	}
14394 
14395 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
14396 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
14397 
14398 	if (un->un_rqs_pktp == NULL) {
14399 		sd_free_rqs(un);
14400 		return (DDI_FAILURE);
14401 	}
14402 
14403 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
14404 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
14405 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
14406 
14407 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
14408 
14409 	/* Set up the other needed members in the ARQ scsi_pkt. */
14410 	un->un_rqs_pktp->pkt_comp   = sdintr;
14411 	un->un_rqs_pktp->pkt_time   = sd_io_time;
14412 	un->un_rqs_pktp->pkt_flags |=
14413 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
14414 
14415 	/*
14416 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
14417 	 * provide any intpkt, destroypkt routines as we take care of
14418 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
14419 	 */
14420 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14421 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
14422 	xp->xb_pktp = un->un_rqs_pktp;
14423 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
14424 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
14425 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
14426 
14427 	/*
14428 	 * Save the pointer to the request sense private bp so it can
14429 	 * be retrieved in sdintr.
14430 	 */
14431 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
14432 	ASSERT(un->un_rqs_bp->b_private == xp);
14433 
14434 	/*
14435 	 * See if the HBA supports auto-request sense for the specified
14436 	 * target/lun. If it does, then try to enable it (if not already
14437 	 * enabled).
14438 	 *
14439 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
14440 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
14441 	 * return success.  However, in both of these cases ARQ is always
14442 	 * enabled and scsi_ifgetcap will always return true. The best approach
14443 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
14444 	 *
14445 	 * The 3rd case is the HBA (adp) always return enabled on
14446 	 * scsi_ifgetgetcap even when it's not enable, the best approach
14447 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
14448 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
14449 	 */
14450 
14451 	if (un->un_f_is_fibre == TRUE) {
14452 		un->un_f_arq_enabled = TRUE;
14453 	} else {
14454 #if defined(__i386) || defined(__amd64)
14455 		/*
14456 		 * Circumvent the Adaptec bug, remove this code when
14457 		 * the bug is fixed
14458 		 */
14459 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
14460 #endif
14461 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
14462 		case 0:
14463 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14464 			    "sd_alloc_rqs: HBA supports ARQ\n");
14465 			/*
14466 			 * ARQ is supported by this HBA but currently is not
14467 			 * enabled. Attempt to enable it and if successful then
14468 			 * mark this instance as ARQ enabled.
14469 			 */
14470 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
14471 			    == 1) {
14472 				/* Successfully enabled ARQ in the HBA */
14473 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14474 				    "sd_alloc_rqs: ARQ enabled\n");
14475 				un->un_f_arq_enabled = TRUE;
14476 			} else {
14477 				/* Could not enable ARQ in the HBA */
14478 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14479 				    "sd_alloc_rqs: failed ARQ enable\n");
14480 				un->un_f_arq_enabled = FALSE;
14481 			}
14482 			break;
14483 		case 1:
14484 			/*
14485 			 * ARQ is supported by this HBA and is already enabled.
14486 			 * Just mark ARQ as enabled for this instance.
14487 			 */
14488 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14489 			    "sd_alloc_rqs: ARQ already enabled\n");
14490 			un->un_f_arq_enabled = TRUE;
14491 			break;
14492 		default:
14493 			/*
14494 			 * ARQ is not supported by this HBA; disable it for this
14495 			 * instance.
14496 			 */
14497 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14498 			    "sd_alloc_rqs: HBA does not support ARQ\n");
14499 			un->un_f_arq_enabled = FALSE;
14500 			break;
14501 		}
14502 	}
14503 
14504 	return (DDI_SUCCESS);
14505 }
14506 
14507 
14508 /*
14509  *    Function: sd_free_rqs
14510  *
14511  * Description: Cleanup for the pre-instance RQS command.
14512  *
14513  *     Context: Kernel thread context
14514  */
14515 
14516 static void
14517 sd_free_rqs(struct sd_lun *un)
14518 {
14519 	ASSERT(un != NULL);
14520 
14521 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
14522 
14523 	/*
14524 	 * If consistent memory is bound to a scsi_pkt, the pkt
14525 	 * has to be destroyed *before* freeing the consistent memory.
14526 	 * Don't change the sequence of this operations.
14527 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
14528 	 * after it was freed in scsi_free_consistent_buf().
14529 	 */
14530 	if (un->un_rqs_pktp != NULL) {
14531 		scsi_destroy_pkt(un->un_rqs_pktp);
14532 		un->un_rqs_pktp = NULL;
14533 	}
14534 
14535 	if (un->un_rqs_bp != NULL) {
14536 		kmem_free(SD_GET_XBUF(un->un_rqs_bp), sizeof (struct sd_xbuf));
14537 		scsi_free_consistent_buf(un->un_rqs_bp);
14538 		un->un_rqs_bp = NULL;
14539 	}
14540 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
14541 }
14542 
14543 
14544 
14545 /*
14546  *    Function: sd_reduce_throttle
14547  *
14548  * Description: Reduces the maximum # of outstanding commands on a
14549  *		target to the current number of outstanding commands.
14550  *		Queues a tiemout(9F) callback to restore the limit
14551  *		after a specified interval has elapsed.
14552  *		Typically used when we get a TRAN_BUSY return code
14553  *		back from scsi_transport().
14554  *
14555  *   Arguments: un - ptr to the sd_lun softstate struct
14556  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
14557  *
14558  *     Context: May be called from interrupt context
14559  */
14560 
14561 static void
14562 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
14563 {
14564 	ASSERT(un != NULL);
14565 	ASSERT(mutex_owned(SD_MUTEX(un)));
14566 	ASSERT(un->un_ncmds_in_transport >= 0);
14567 
14568 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14569 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
14570 	    un, un->un_throttle, un->un_ncmds_in_transport);
14571 
14572 	if (un->un_throttle > 1) {
14573 		if (un->un_f_use_adaptive_throttle == TRUE) {
14574 			switch (throttle_type) {
14575 			case SD_THROTTLE_TRAN_BUSY:
14576 				if (un->un_busy_throttle == 0) {
14577 					un->un_busy_throttle = un->un_throttle;
14578 				}
14579 				break;
14580 			case SD_THROTTLE_QFULL:
14581 				un->un_busy_throttle = 0;
14582 				break;
14583 			default:
14584 				ASSERT(FALSE);
14585 			}
14586 
14587 			if (un->un_ncmds_in_transport > 0) {
14588 				un->un_throttle = un->un_ncmds_in_transport;
14589 			}
14590 
14591 		} else {
14592 			if (un->un_ncmds_in_transport == 0) {
14593 				un->un_throttle = 1;
14594 			} else {
14595 				un->un_throttle = un->un_ncmds_in_transport;
14596 			}
14597 		}
14598 	}
14599 
14600 	/* Reschedule the timeout if none is currently active */
14601 	if (un->un_reset_throttle_timeid == NULL) {
14602 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
14603 		    un, SD_THROTTLE_RESET_INTERVAL);
14604 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14605 		    "sd_reduce_throttle: timeout scheduled!\n");
14606 	}
14607 
14608 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14609 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14610 }
14611 
14612 
14613 
14614 /*
14615  *    Function: sd_restore_throttle
14616  *
14617  * Description: Callback function for timeout(9F).  Resets the current
14618  *		value of un->un_throttle to its default.
14619  *
14620  *   Arguments: arg - pointer to associated softstate for the device.
14621  *
14622  *     Context: May be called from interrupt context
14623  */
14624 
14625 static void
14626 sd_restore_throttle(void *arg)
14627 {
14628 	struct sd_lun	*un = arg;
14629 
14630 	ASSERT(un != NULL);
14631 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14632 
14633 	mutex_enter(SD_MUTEX(un));
14634 
14635 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14636 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14637 
14638 	un->un_reset_throttle_timeid = NULL;
14639 
14640 	if (un->un_f_use_adaptive_throttle == TRUE) {
14641 		/*
14642 		 * If un_busy_throttle is nonzero, then it contains the
14643 		 * value that un_throttle was when we got a TRAN_BUSY back
14644 		 * from scsi_transport(). We want to revert back to this
14645 		 * value.
14646 		 *
14647 		 * In the QFULL case, the throttle limit will incrementally
14648 		 * increase until it reaches max throttle.
14649 		 */
14650 		if (un->un_busy_throttle > 0) {
14651 			un->un_throttle = un->un_busy_throttle;
14652 			un->un_busy_throttle = 0;
14653 		} else {
14654 			/*
14655 			 * increase throttle by 10% open gate slowly, schedule
14656 			 * another restore if saved throttle has not been
14657 			 * reached
14658 			 */
14659 			short throttle;
14660 			if (sd_qfull_throttle_enable) {
14661 				throttle = un->un_throttle +
14662 				    max((un->un_throttle / 10), 1);
14663 				un->un_throttle =
14664 				    (throttle < un->un_saved_throttle) ?
14665 				    throttle : un->un_saved_throttle;
14666 				if (un->un_throttle < un->un_saved_throttle) {
14667 					un->un_reset_throttle_timeid =
14668 					    timeout(sd_restore_throttle,
14669 					    un,
14670 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
14671 				}
14672 			}
14673 		}
14674 
14675 		/*
14676 		 * If un_throttle has fallen below the low-water mark, we
14677 		 * restore the maximum value here (and allow it to ratchet
14678 		 * down again if necessary).
14679 		 */
14680 		if (un->un_throttle < un->un_min_throttle) {
14681 			un->un_throttle = un->un_saved_throttle;
14682 		}
14683 	} else {
14684 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14685 		    "restoring limit from 0x%x to 0x%x\n",
14686 		    un->un_throttle, un->un_saved_throttle);
14687 		un->un_throttle = un->un_saved_throttle;
14688 	}
14689 
14690 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14691 	    "sd_restore_throttle: calling sd_start_cmds!\n");
14692 
14693 	sd_start_cmds(un, NULL);
14694 
14695 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14696 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
14697 	    un, un->un_throttle);
14698 
14699 	mutex_exit(SD_MUTEX(un));
14700 
14701 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
14702 }
14703 
14704 /*
14705  *    Function: sdrunout
14706  *
14707  * Description: Callback routine for scsi_init_pkt when a resource allocation
14708  *		fails.
14709  *
14710  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
14711  *		soft state instance.
14712  *
14713  * Return Code: The scsi_init_pkt routine allows for the callback function to
14714  *		return a 0 indicating the callback should be rescheduled or a 1
14715  *		indicating not to reschedule. This routine always returns 1
14716  *		because the driver always provides a callback function to
14717  *		scsi_init_pkt. This results in a callback always being scheduled
14718  *		(via the scsi_init_pkt callback implementation) if a resource
14719  *		failure occurs.
14720  *
14721  *     Context: This callback function may not block or call routines that block
14722  *
14723  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
14724  *		request persisting at the head of the list which cannot be
14725  *		satisfied even after multiple retries. In the future the driver
14726  *		may implement some time of maximum runout count before failing
14727  *		an I/O.
14728  */
14729 
14730 static int
14731 sdrunout(caddr_t arg)
14732 {
14733 	struct sd_lun	*un = (struct sd_lun *)arg;
14734 
14735 	ASSERT(un != NULL);
14736 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14737 
14738 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
14739 
14740 	mutex_enter(SD_MUTEX(un));
14741 	sd_start_cmds(un, NULL);
14742 	mutex_exit(SD_MUTEX(un));
14743 	/*
14744 	 * This callback routine always returns 1 (i.e. do not reschedule)
14745 	 * because we always specify sdrunout as the callback handler for
14746 	 * scsi_init_pkt inside the call to sd_start_cmds.
14747 	 */
14748 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
14749 	return (1);
14750 }
14751 
14752 
14753 /*
14754  *    Function: sdintr
14755  *
14756  * Description: Completion callback routine for scsi_pkt(9S) structs
14757  *		sent to the HBA driver via scsi_transport(9F).
14758  *
14759  *     Context: Interrupt context
14760  */
14761 
14762 static void
14763 sdintr(struct scsi_pkt *pktp)
14764 {
14765 	struct buf	*bp;
14766 	struct sd_xbuf	*xp;
14767 	struct sd_lun	*un;
14768 	size_t		actual_len;
14769 
14770 	ASSERT(pktp != NULL);
14771 	bp = (struct buf *)pktp->pkt_private;
14772 	ASSERT(bp != NULL);
14773 	xp = SD_GET_XBUF(bp);
14774 	ASSERT(xp != NULL);
14775 	ASSERT(xp->xb_pktp != NULL);
14776 	un = SD_GET_UN(bp);
14777 	ASSERT(un != NULL);
14778 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14779 
14780 #ifdef SD_FAULT_INJECTION
14781 
14782 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
14783 	/* SD FaultInjection */
14784 	sd_faultinjection(pktp);
14785 
14786 #endif /* SD_FAULT_INJECTION */
14787 
14788 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
14789 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
14790 
14791 	mutex_enter(SD_MUTEX(un));
14792 
14793 	/* Reduce the count of the #commands currently in transport */
14794 	un->un_ncmds_in_transport--;
14795 	ASSERT(un->un_ncmds_in_transport >= 0);
14796 
14797 	/* Increment counter to indicate that the callback routine is active */
14798 	un->un_in_callback++;
14799 
14800 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14801 
14802 #ifdef	SDDEBUG
14803 	if (bp == un->un_retry_bp) {
14804 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
14805 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
14806 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
14807 	}
14808 #endif
14809 
14810 	/*
14811 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
14812 	 * state if needed.
14813 	 */
14814 	if (pktp->pkt_reason == CMD_DEV_GONE) {
14815 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
14816 		    "Device is gone\n");
14817 		if (un->un_mediastate != DKIO_DEV_GONE) {
14818 			un->un_mediastate = DKIO_DEV_GONE;
14819 			cv_broadcast(&un->un_state_cv);
14820 		}
14821 		sd_return_failed_command(un, bp, EIO);
14822 		goto exit;
14823 	}
14824 
14825 	if (pktp->pkt_state & STATE_XARQ_DONE) {
14826 		SD_TRACE(SD_LOG_COMMON, un,
14827 		    "sdintr: extra sense data received. pkt=%p\n", pktp);
14828 	}
14829 
14830 	/*
14831 	 * First see if the pkt has auto-request sense data with it....
14832 	 * Look at the packet state first so we don't take a performance
14833 	 * hit looking at the arq enabled flag unless absolutely necessary.
14834 	 */
14835 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
14836 	    (un->un_f_arq_enabled == TRUE)) {
14837 		/*
14838 		 * The HBA did an auto request sense for this command so check
14839 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
14840 		 * driver command that should not be retried.
14841 		 */
14842 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
14843 			/*
14844 			 * Save the relevant sense info into the xp for the
14845 			 * original cmd.
14846 			 */
14847 			struct scsi_arq_status *asp;
14848 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
14849 			xp->xb_sense_status =
14850 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
14851 			xp->xb_sense_state  = asp->sts_rqpkt_state;
14852 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
14853 			if (pktp->pkt_state & STATE_XARQ_DONE) {
14854 				actual_len = MAX_SENSE_LENGTH -
14855 				    xp->xb_sense_resid;
14856 			} else {
14857 				if (xp->xb_sense_resid > SENSE_LENGTH) {
14858 					actual_len = MAX_SENSE_LENGTH -
14859 					    xp->xb_sense_resid;
14860 				} else {
14861 					actual_len = SENSE_LENGTH -
14862 					    xp->xb_sense_resid;
14863 				}
14864 				if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
14865 					xp->xb_sense_resid =
14866 					    (int)(((struct uscsi_cmd *)
14867 					    (xp->xb_pktinfo))->
14868 					    uscsi_rqlen) - actual_len;
14869 				}
14870 			}
14871 			bcopy(&asp->sts_sensedata, xp->xb_sense_data,
14872 			    actual_len);
14873 
14874 			/* fail the command */
14875 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14876 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
14877 			sd_return_failed_command(un, bp, EIO);
14878 			goto exit;
14879 		}
14880 
14881 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
14882 		/*
14883 		 * We want to either retry or fail this command, so free
14884 		 * the DMA resources here.  If we retry the command then
14885 		 * the DMA resources will be reallocated in sd_start_cmds().
14886 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
14887 		 * causes the *entire* transfer to start over again from the
14888 		 * beginning of the request, even for PARTIAL chunks that
14889 		 * have already transferred successfully.
14890 		 */
14891 		if ((un->un_f_is_fibre == TRUE) &&
14892 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14893 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
14894 			scsi_dmafree(pktp);
14895 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
14896 		}
14897 #endif
14898 
14899 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14900 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
14901 
14902 		sd_handle_auto_request_sense(un, bp, xp, pktp);
14903 		goto exit;
14904 	}
14905 
14906 	/* Next see if this is the REQUEST SENSE pkt for the instance */
14907 	if (pktp->pkt_flags & FLAG_SENSING)  {
14908 		/* This pktp is from the unit's REQUEST_SENSE command */
14909 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14910 		    "sdintr: sd_handle_request_sense\n");
14911 		sd_handle_request_sense(un, bp, xp, pktp);
14912 		goto exit;
14913 	}
14914 
14915 	/*
14916 	 * Check to see if the command successfully completed as requested;
14917 	 * this is the most common case (and also the hot performance path).
14918 	 *
14919 	 * Requirements for successful completion are:
14920 	 * pkt_reason is CMD_CMPLT and packet status is status good.
14921 	 * In addition:
14922 	 * - A residual of zero indicates successful completion no matter what
14923 	 *   the command is.
14924 	 * - If the residual is not zero and the command is not a read or
14925 	 *   write, then it's still defined as successful completion. In other
14926 	 *   words, if the command is a read or write the residual must be
14927 	 *   zero for successful completion.
14928 	 * - If the residual is not zero and the command is a read or
14929 	 *   write, and it's a USCSICMD, then it's still defined as
14930 	 *   successful completion.
14931 	 */
14932 	if ((pktp->pkt_reason == CMD_CMPLT) &&
14933 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
14934 
14935 		/*
14936 		 * Since this command is returned with a good status, we
14937 		 * can reset the count for Sonoma failover.
14938 		 */
14939 		un->un_sonoma_failure_count = 0;
14940 
14941 		/*
14942 		 * Return all USCSI commands on good status
14943 		 */
14944 		if (pktp->pkt_resid == 0) {
14945 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14946 			    "sdintr: returning command for resid == 0\n");
14947 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
14948 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
14949 			SD_UPDATE_B_RESID(bp, pktp);
14950 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14951 			    "sdintr: returning command for resid != 0\n");
14952 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
14953 			SD_UPDATE_B_RESID(bp, pktp);
14954 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14955 			    "sdintr: returning uscsi command\n");
14956 		} else {
14957 			goto not_successful;
14958 		}
14959 		sd_return_command(un, bp);
14960 
14961 		/*
14962 		 * Decrement counter to indicate that the callback routine
14963 		 * is done.
14964 		 */
14965 		un->un_in_callback--;
14966 		ASSERT(un->un_in_callback >= 0);
14967 		mutex_exit(SD_MUTEX(un));
14968 
14969 		return;
14970 	}
14971 
14972 not_successful:
14973 
14974 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
14975 	/*
14976 	 * The following is based upon knowledge of the underlying transport
14977 	 * and its use of DMA resources.  This code should be removed when
14978 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
14979 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
14980 	 * and sd_start_cmds().
14981 	 *
14982 	 * Free any DMA resources associated with this command if there
14983 	 * is a chance it could be retried or enqueued for later retry.
14984 	 * If we keep the DMA binding then mpxio cannot reissue the
14985 	 * command on another path whenever a path failure occurs.
14986 	 *
14987 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
14988 	 * causes the *entire* transfer to start over again from the
14989 	 * beginning of the request, even for PARTIAL chunks that
14990 	 * have already transferred successfully.
14991 	 *
14992 	 * This is only done for non-uscsi commands (and also skipped for the
14993 	 * driver's internal RQS command). Also just do this for Fibre Channel
14994 	 * devices as these are the only ones that support mpxio.
14995 	 */
14996 	if ((un->un_f_is_fibre == TRUE) &&
14997 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14998 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
14999 		scsi_dmafree(pktp);
15000 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
15001 	}
15002 #endif
15003 
15004 	/*
15005 	 * The command did not successfully complete as requested so check
15006 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
15007 	 * driver command that should not be retried so just return. If
15008 	 * FLAG_DIAGNOSE is not set the error will be processed below.
15009 	 */
15010 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
15011 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15012 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
15013 		/*
15014 		 * Issue a request sense if a check condition caused the error
15015 		 * (we handle the auto request sense case above), otherwise
15016 		 * just fail the command.
15017 		 */
15018 		if ((pktp->pkt_reason == CMD_CMPLT) &&
15019 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
15020 			sd_send_request_sense_command(un, bp, pktp);
15021 		} else {
15022 			sd_return_failed_command(un, bp, EIO);
15023 		}
15024 		goto exit;
15025 	}
15026 
15027 	/*
15028 	 * The command did not successfully complete as requested so process
15029 	 * the error, retry, and/or attempt recovery.
15030 	 */
15031 	switch (pktp->pkt_reason) {
15032 	case CMD_CMPLT:
15033 		switch (SD_GET_PKT_STATUS(pktp)) {
15034 		case STATUS_GOOD:
15035 			/*
15036 			 * The command completed successfully with a non-zero
15037 			 * residual
15038 			 */
15039 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15040 			    "sdintr: STATUS_GOOD \n");
15041 			sd_pkt_status_good(un, bp, xp, pktp);
15042 			break;
15043 
15044 		case STATUS_CHECK:
15045 		case STATUS_TERMINATED:
15046 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15047 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
15048 			sd_pkt_status_check_condition(un, bp, xp, pktp);
15049 			break;
15050 
15051 		case STATUS_BUSY:
15052 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15053 			    "sdintr: STATUS_BUSY\n");
15054 			sd_pkt_status_busy(un, bp, xp, pktp);
15055 			break;
15056 
15057 		case STATUS_RESERVATION_CONFLICT:
15058 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15059 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
15060 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
15061 			break;
15062 
15063 		case STATUS_QFULL:
15064 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15065 			    "sdintr: STATUS_QFULL\n");
15066 			sd_pkt_status_qfull(un, bp, xp, pktp);
15067 			break;
15068 
15069 		case STATUS_MET:
15070 		case STATUS_INTERMEDIATE:
15071 		case STATUS_SCSI2:
15072 		case STATUS_INTERMEDIATE_MET:
15073 		case STATUS_ACA_ACTIVE:
15074 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
15075 			    "Unexpected SCSI status received: 0x%x\n",
15076 			    SD_GET_PKT_STATUS(pktp));
15077 			sd_return_failed_command(un, bp, EIO);
15078 			break;
15079 
15080 		default:
15081 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
15082 			    "Invalid SCSI status received: 0x%x\n",
15083 			    SD_GET_PKT_STATUS(pktp));
15084 			sd_return_failed_command(un, bp, EIO);
15085 			break;
15086 
15087 		}
15088 		break;
15089 
15090 	case CMD_INCOMPLETE:
15091 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15092 		    "sdintr:  CMD_INCOMPLETE\n");
15093 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
15094 		break;
15095 	case CMD_TRAN_ERR:
15096 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15097 		    "sdintr: CMD_TRAN_ERR\n");
15098 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
15099 		break;
15100 	case CMD_RESET:
15101 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15102 		    "sdintr: CMD_RESET \n");
15103 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
15104 		break;
15105 	case CMD_ABORTED:
15106 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15107 		    "sdintr: CMD_ABORTED \n");
15108 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
15109 		break;
15110 	case CMD_TIMEOUT:
15111 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15112 		    "sdintr: CMD_TIMEOUT\n");
15113 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
15114 		break;
15115 	case CMD_UNX_BUS_FREE:
15116 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15117 		    "sdintr: CMD_UNX_BUS_FREE \n");
15118 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
15119 		break;
15120 	case CMD_TAG_REJECT:
15121 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15122 		    "sdintr: CMD_TAG_REJECT\n");
15123 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
15124 		break;
15125 	default:
15126 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15127 		    "sdintr: default\n");
15128 		sd_pkt_reason_default(un, bp, xp, pktp);
15129 		break;
15130 	}
15131 
15132 exit:
15133 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
15134 
15135 	/* Decrement counter to indicate that the callback routine is done. */
15136 	un->un_in_callback--;
15137 	ASSERT(un->un_in_callback >= 0);
15138 
15139 	/*
15140 	 * At this point, the pkt has been dispatched, ie, it is either
15141 	 * being re-tried or has been returned to its caller and should
15142 	 * not be referenced.
15143 	 */
15144 
15145 	mutex_exit(SD_MUTEX(un));
15146 }
15147 
15148 
15149 /*
15150  *    Function: sd_print_incomplete_msg
15151  *
15152  * Description: Prints the error message for a CMD_INCOMPLETE error.
15153  *
15154  *   Arguments: un - ptr to associated softstate for the device.
15155  *		bp - ptr to the buf(9S) for the command.
15156  *		arg - message string ptr
15157  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
15158  *			or SD_NO_RETRY_ISSUED.
15159  *
15160  *     Context: May be called under interrupt context
15161  */
15162 
15163 static void
15164 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
15165 {
15166 	struct scsi_pkt	*pktp;
15167 	char	*msgp;
15168 	char	*cmdp = arg;
15169 
15170 	ASSERT(un != NULL);
15171 	ASSERT(mutex_owned(SD_MUTEX(un)));
15172 	ASSERT(bp != NULL);
15173 	ASSERT(arg != NULL);
15174 	pktp = SD_GET_PKTP(bp);
15175 	ASSERT(pktp != NULL);
15176 
15177 	switch (code) {
15178 	case SD_DELAYED_RETRY_ISSUED:
15179 	case SD_IMMEDIATE_RETRY_ISSUED:
15180 		msgp = "retrying";
15181 		break;
15182 	case SD_NO_RETRY_ISSUED:
15183 	default:
15184 		msgp = "giving up";
15185 		break;
15186 	}
15187 
15188 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
15189 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15190 		    "incomplete %s- %s\n", cmdp, msgp);
15191 	}
15192 }
15193 
15194 
15195 
15196 /*
15197  *    Function: sd_pkt_status_good
15198  *
15199  * Description: Processing for a STATUS_GOOD code in pkt_status.
15200  *
15201  *     Context: May be called under interrupt context
15202  */
15203 
15204 static void
15205 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
15206 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15207 {
15208 	char	*cmdp;
15209 
15210 	ASSERT(un != NULL);
15211 	ASSERT(mutex_owned(SD_MUTEX(un)));
15212 	ASSERT(bp != NULL);
15213 	ASSERT(xp != NULL);
15214 	ASSERT(pktp != NULL);
15215 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
15216 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
15217 	ASSERT(pktp->pkt_resid != 0);
15218 
15219 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
15220 
15221 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
15222 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
15223 	case SCMD_READ:
15224 		cmdp = "read";
15225 		break;
15226 	case SCMD_WRITE:
15227 		cmdp = "write";
15228 		break;
15229 	default:
15230 		SD_UPDATE_B_RESID(bp, pktp);
15231 		sd_return_command(un, bp);
15232 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15233 		return;
15234 	}
15235 
15236 	/*
15237 	 * See if we can retry the read/write, preferrably immediately.
15238 	 * If retries are exhaused, then sd_retry_command() will update
15239 	 * the b_resid count.
15240 	 */
15241 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
15242 	    cmdp, EIO, (clock_t)0, NULL);
15243 
15244 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15245 }
15246 
15247 
15248 
15249 
15250 
15251 /*
15252  *    Function: sd_handle_request_sense
15253  *
15254  * Description: Processing for non-auto Request Sense command.
15255  *
15256  *   Arguments: un - ptr to associated softstate
15257  *		sense_bp - ptr to buf(9S) for the RQS command
15258  *		sense_xp - ptr to the sd_xbuf for the RQS command
15259  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
15260  *
15261  *     Context: May be called under interrupt context
15262  */
15263 
15264 static void
15265 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
15266 	struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
15267 {
15268 	struct buf	*cmd_bp;	/* buf for the original command */
15269 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
15270 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
15271 	size_t		actual_len;	/* actual sense data length */
15272 
15273 	ASSERT(un != NULL);
15274 	ASSERT(mutex_owned(SD_MUTEX(un)));
15275 	ASSERT(sense_bp != NULL);
15276 	ASSERT(sense_xp != NULL);
15277 	ASSERT(sense_pktp != NULL);
15278 
15279 	/*
15280 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
15281 	 * RQS command and not the original command.
15282 	 */
15283 	ASSERT(sense_pktp == un->un_rqs_pktp);
15284 	ASSERT(sense_bp   == un->un_rqs_bp);
15285 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
15286 	    (FLAG_SENSING | FLAG_HEAD));
15287 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
15288 	    FLAG_SENSING) == FLAG_SENSING);
15289 
15290 	/* These are the bp, xp, and pktp for the original command */
15291 	cmd_bp = sense_xp->xb_sense_bp;
15292 	cmd_xp = SD_GET_XBUF(cmd_bp);
15293 	cmd_pktp = SD_GET_PKTP(cmd_bp);
15294 
15295 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
15296 		/*
15297 		 * The REQUEST SENSE command failed.  Release the REQUEST
15298 		 * SENSE command for re-use, get back the bp for the original
15299 		 * command, and attempt to re-try the original command if
15300 		 * FLAG_DIAGNOSE is not set in the original packet.
15301 		 */
15302 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
15303 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15304 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
15305 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
15306 			    NULL, NULL, EIO, (clock_t)0, NULL);
15307 			return;
15308 		}
15309 	}
15310 
15311 	/*
15312 	 * Save the relevant sense info into the xp for the original cmd.
15313 	 *
15314 	 * Note: if the request sense failed the state info will be zero
15315 	 * as set in sd_mark_rqs_busy()
15316 	 */
15317 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
15318 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
15319 	actual_len = MAX_SENSE_LENGTH - sense_pktp->pkt_resid;
15320 	if ((cmd_xp->xb_pkt_flags & SD_XB_USCSICMD) &&
15321 	    (((struct uscsi_cmd *)cmd_xp->xb_pktinfo)->uscsi_rqlen >
15322 	    SENSE_LENGTH)) {
15323 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
15324 		    min(actual_len, MAX_SENSE_LENGTH));
15325 		cmd_xp->xb_sense_resid = sense_pktp->pkt_resid;
15326 	} else {
15327 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
15328 		    min(actual_len, SENSE_LENGTH));
15329 		if (actual_len < SENSE_LENGTH) {
15330 			cmd_xp->xb_sense_resid = SENSE_LENGTH - actual_len;
15331 		} else {
15332 			cmd_xp->xb_sense_resid = 0;
15333 		}
15334 	}
15335 
15336 	/*
15337 	 *  Free up the RQS command....
15338 	 *  NOTE:
15339 	 *	Must do this BEFORE calling sd_validate_sense_data!
15340 	 *	sd_validate_sense_data may return the original command in
15341 	 *	which case the pkt will be freed and the flags can no
15342 	 *	longer be touched.
15343 	 *	SD_MUTEX is held through this process until the command
15344 	 *	is dispatched based upon the sense data, so there are
15345 	 *	no race conditions.
15346 	 */
15347 	(void) sd_mark_rqs_idle(un, sense_xp);
15348 
15349 	/*
15350 	 * For a retryable command see if we have valid sense data, if so then
15351 	 * turn it over to sd_decode_sense() to figure out the right course of
15352 	 * action. Just fail a non-retryable command.
15353 	 */
15354 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15355 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp, actual_len) ==
15356 		    SD_SENSE_DATA_IS_VALID) {
15357 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
15358 		}
15359 	} else {
15360 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
15361 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15362 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
15363 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15364 		sd_return_failed_command(un, cmd_bp, EIO);
15365 	}
15366 }
15367 
15368 
15369 
15370 
15371 /*
15372  *    Function: sd_handle_auto_request_sense
15373  *
15374  * Description: Processing for auto-request sense information.
15375  *
15376  *   Arguments: un - ptr to associated softstate
15377  *		bp - ptr to buf(9S) for the command
15378  *		xp - ptr to the sd_xbuf for the command
15379  *		pktp - ptr to the scsi_pkt(9S) for the command
15380  *
15381  *     Context: May be called under interrupt context
15382  */
15383 
15384 static void
15385 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
15386 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15387 {
15388 	struct scsi_arq_status *asp;
15389 	size_t actual_len;
15390 
15391 	ASSERT(un != NULL);
15392 	ASSERT(mutex_owned(SD_MUTEX(un)));
15393 	ASSERT(bp != NULL);
15394 	ASSERT(xp != NULL);
15395 	ASSERT(pktp != NULL);
15396 	ASSERT(pktp != un->un_rqs_pktp);
15397 	ASSERT(bp   != un->un_rqs_bp);
15398 
15399 	/*
15400 	 * For auto-request sense, we get a scsi_arq_status back from
15401 	 * the HBA, with the sense data in the sts_sensedata member.
15402 	 * The pkt_scbp of the packet points to this scsi_arq_status.
15403 	 */
15404 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
15405 
15406 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
15407 		/*
15408 		 * The auto REQUEST SENSE failed; see if we can re-try
15409 		 * the original command.
15410 		 */
15411 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15412 		    "auto request sense failed (reason=%s)\n",
15413 		    scsi_rname(asp->sts_rqpkt_reason));
15414 
15415 		sd_reset_target(un, pktp);
15416 
15417 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15418 		    NULL, NULL, EIO, (clock_t)0, NULL);
15419 		return;
15420 	}
15421 
15422 	/* Save the relevant sense info into the xp for the original cmd. */
15423 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
15424 	xp->xb_sense_state  = asp->sts_rqpkt_state;
15425 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
15426 	if (xp->xb_sense_state & STATE_XARQ_DONE) {
15427 		actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
15428 	} else {
15429 		if (xp->xb_sense_resid > SENSE_LENGTH) {
15430 			actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
15431 		} else {
15432 			actual_len = SENSE_LENGTH - xp->xb_sense_resid;
15433 		}
15434 		if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
15435 			xp->xb_sense_resid = (int)(((struct uscsi_cmd *)
15436 			    (xp->xb_pktinfo))->uscsi_rqlen) - actual_len;
15437 		}
15438 	}
15439 	bcopy(&asp->sts_sensedata, xp->xb_sense_data, actual_len);
15440 
15441 	/*
15442 	 * See if we have valid sense data, if so then turn it over to
15443 	 * sd_decode_sense() to figure out the right course of action.
15444 	 */
15445 	if (sd_validate_sense_data(un, bp, xp, actual_len) ==
15446 	    SD_SENSE_DATA_IS_VALID) {
15447 		sd_decode_sense(un, bp, xp, pktp);
15448 	}
15449 }
15450 
15451 
15452 /*
15453  *    Function: sd_print_sense_failed_msg
15454  *
15455  * Description: Print log message when RQS has failed.
15456  *
15457  *   Arguments: un - ptr to associated softstate
15458  *		bp - ptr to buf(9S) for the command
15459  *		arg - generic message string ptr
15460  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15461  *			or SD_NO_RETRY_ISSUED
15462  *
15463  *     Context: May be called from interrupt context
15464  */
15465 
15466 static void
15467 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
15468 	int code)
15469 {
15470 	char	*msgp = arg;
15471 
15472 	ASSERT(un != NULL);
15473 	ASSERT(mutex_owned(SD_MUTEX(un)));
15474 	ASSERT(bp != NULL);
15475 
15476 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
15477 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
15478 	}
15479 }
15480 
15481 
15482 /*
15483  *    Function: sd_validate_sense_data
15484  *
15485  * Description: Check the given sense data for validity.
15486  *		If the sense data is not valid, the command will
15487  *		be either failed or retried!
15488  *
15489  * Return Code: SD_SENSE_DATA_IS_INVALID
15490  *		SD_SENSE_DATA_IS_VALID
15491  *
15492  *     Context: May be called from interrupt context
15493  */
15494 
15495 static int
15496 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
15497 	size_t actual_len)
15498 {
15499 	struct scsi_extended_sense *esp;
15500 	struct	scsi_pkt *pktp;
15501 	char	*msgp = NULL;
15502 
15503 	ASSERT(un != NULL);
15504 	ASSERT(mutex_owned(SD_MUTEX(un)));
15505 	ASSERT(bp != NULL);
15506 	ASSERT(bp != un->un_rqs_bp);
15507 	ASSERT(xp != NULL);
15508 
15509 	pktp = SD_GET_PKTP(bp);
15510 	ASSERT(pktp != NULL);
15511 
15512 	/*
15513 	 * Check the status of the RQS command (auto or manual).
15514 	 */
15515 	switch (xp->xb_sense_status & STATUS_MASK) {
15516 	case STATUS_GOOD:
15517 		break;
15518 
15519 	case STATUS_RESERVATION_CONFLICT:
15520 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
15521 		return (SD_SENSE_DATA_IS_INVALID);
15522 
15523 	case STATUS_BUSY:
15524 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15525 		    "Busy Status on REQUEST SENSE\n");
15526 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
15527 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15528 		return (SD_SENSE_DATA_IS_INVALID);
15529 
15530 	case STATUS_QFULL:
15531 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15532 		    "QFULL Status on REQUEST SENSE\n");
15533 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
15534 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15535 		return (SD_SENSE_DATA_IS_INVALID);
15536 
15537 	case STATUS_CHECK:
15538 	case STATUS_TERMINATED:
15539 		msgp = "Check Condition on REQUEST SENSE\n";
15540 		goto sense_failed;
15541 
15542 	default:
15543 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
15544 		goto sense_failed;
15545 	}
15546 
15547 	/*
15548 	 * See if we got the minimum required amount of sense data.
15549 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
15550 	 * or less.
15551 	 */
15552 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
15553 	    (actual_len == 0)) {
15554 		msgp = "Request Sense couldn't get sense data\n";
15555 		goto sense_failed;
15556 	}
15557 
15558 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
15559 		msgp = "Not enough sense information\n";
15560 		goto sense_failed;
15561 	}
15562 
15563 	/*
15564 	 * We require the extended sense data
15565 	 */
15566 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
15567 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
15568 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
15569 			static char tmp[8];
15570 			static char buf[148];
15571 			char *p = (char *)(xp->xb_sense_data);
15572 			int i;
15573 
15574 			mutex_enter(&sd_sense_mutex);
15575 			(void) strcpy(buf, "undecodable sense information:");
15576 			for (i = 0; i < actual_len; i++) {
15577 				(void) sprintf(tmp, " 0x%x", *(p++)&0xff);
15578 				(void) strcpy(&buf[strlen(buf)], tmp);
15579 			}
15580 			i = strlen(buf);
15581 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
15582 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, buf);
15583 			mutex_exit(&sd_sense_mutex);
15584 		}
15585 		/* Note: Legacy behavior, fail the command with no retry */
15586 		sd_return_failed_command(un, bp, EIO);
15587 		return (SD_SENSE_DATA_IS_INVALID);
15588 	}
15589 
15590 	/*
15591 	 * Check that es_code is valid (es_class concatenated with es_code
15592 	 * make up the "response code" field.  es_class will always be 7, so
15593 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
15594 	 * format.
15595 	 */
15596 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
15597 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
15598 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
15599 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
15600 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
15601 		goto sense_failed;
15602 	}
15603 
15604 	return (SD_SENSE_DATA_IS_VALID);
15605 
15606 sense_failed:
15607 	/*
15608 	 * If the request sense failed (for whatever reason), attempt
15609 	 * to retry the original command.
15610 	 */
15611 #if defined(__i386) || defined(__amd64)
15612 	/*
15613 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
15614 	 * sddef.h for Sparc platform, and x86 uses 1 binary
15615 	 * for both SCSI/FC.
15616 	 * The SD_RETRY_DELAY value need to be adjusted here
15617 	 * when SD_RETRY_DELAY change in sddef.h
15618 	 */
15619 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15620 	    sd_print_sense_failed_msg, msgp, EIO,
15621 	    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0, NULL);
15622 #else
15623 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15624 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
15625 #endif
15626 
15627 	return (SD_SENSE_DATA_IS_INVALID);
15628 }
15629 
15630 
15631 
15632 /*
15633  *    Function: sd_decode_sense
15634  *
15635  * Description: Take recovery action(s) when SCSI Sense Data is received.
15636  *
15637  *     Context: Interrupt context.
15638  */
15639 
15640 static void
15641 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
15642 	struct scsi_pkt *pktp)
15643 {
15644 	uint8_t sense_key;
15645 
15646 	ASSERT(un != NULL);
15647 	ASSERT(mutex_owned(SD_MUTEX(un)));
15648 	ASSERT(bp != NULL);
15649 	ASSERT(bp != un->un_rqs_bp);
15650 	ASSERT(xp != NULL);
15651 	ASSERT(pktp != NULL);
15652 
15653 	sense_key = scsi_sense_key(xp->xb_sense_data);
15654 
15655 	switch (sense_key) {
15656 	case KEY_NO_SENSE:
15657 		sd_sense_key_no_sense(un, bp, xp, pktp);
15658 		break;
15659 	case KEY_RECOVERABLE_ERROR:
15660 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
15661 		    bp, xp, pktp);
15662 		break;
15663 	case KEY_NOT_READY:
15664 		sd_sense_key_not_ready(un, xp->xb_sense_data,
15665 		    bp, xp, pktp);
15666 		break;
15667 	case KEY_MEDIUM_ERROR:
15668 	case KEY_HARDWARE_ERROR:
15669 		sd_sense_key_medium_or_hardware_error(un,
15670 		    xp->xb_sense_data, bp, xp, pktp);
15671 		break;
15672 	case KEY_ILLEGAL_REQUEST:
15673 		sd_sense_key_illegal_request(un, bp, xp, pktp);
15674 		break;
15675 	case KEY_UNIT_ATTENTION:
15676 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
15677 		    bp, xp, pktp);
15678 		break;
15679 	case KEY_WRITE_PROTECT:
15680 	case KEY_VOLUME_OVERFLOW:
15681 	case KEY_MISCOMPARE:
15682 		sd_sense_key_fail_command(un, bp, xp, pktp);
15683 		break;
15684 	case KEY_BLANK_CHECK:
15685 		sd_sense_key_blank_check(un, bp, xp, pktp);
15686 		break;
15687 	case KEY_ABORTED_COMMAND:
15688 		sd_sense_key_aborted_command(un, bp, xp, pktp);
15689 		break;
15690 	case KEY_VENDOR_UNIQUE:
15691 	case KEY_COPY_ABORTED:
15692 	case KEY_EQUAL:
15693 	case KEY_RESERVED:
15694 	default:
15695 		sd_sense_key_default(un, xp->xb_sense_data,
15696 		    bp, xp, pktp);
15697 		break;
15698 	}
15699 }
15700 
15701 
15702 /*
15703  *    Function: sd_dump_memory
15704  *
15705  * Description: Debug logging routine to print the contents of a user provided
15706  *		buffer. The output of the buffer is broken up into 256 byte
15707  *		segments due to a size constraint of the scsi_log.
15708  *		implementation.
15709  *
15710  *   Arguments: un - ptr to softstate
15711  *		comp - component mask
15712  *		title - "title" string to preceed data when printed
15713  *		data - ptr to data block to be printed
15714  *		len - size of data block to be printed
15715  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
15716  *
15717  *     Context: May be called from interrupt context
15718  */
15719 
15720 #define	SD_DUMP_MEMORY_BUF_SIZE	256
15721 
15722 static char *sd_dump_format_string[] = {
15723 		" 0x%02x",
15724 		" %c"
15725 };
15726 
15727 static void
15728 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
15729     int len, int fmt)
15730 {
15731 	int	i, j;
15732 	int	avail_count;
15733 	int	start_offset;
15734 	int	end_offset;
15735 	size_t	entry_len;
15736 	char	*bufp;
15737 	char	*local_buf;
15738 	char	*format_string;
15739 
15740 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
15741 
15742 	/*
15743 	 * In the debug version of the driver, this function is called from a
15744 	 * number of places which are NOPs in the release driver.
15745 	 * The debug driver therefore has additional methods of filtering
15746 	 * debug output.
15747 	 */
15748 #ifdef SDDEBUG
15749 	/*
15750 	 * In the debug version of the driver we can reduce the amount of debug
15751 	 * messages by setting sd_error_level to something other than
15752 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
15753 	 * sd_component_mask.
15754 	 */
15755 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
15756 	    (sd_error_level != SCSI_ERR_ALL)) {
15757 		return;
15758 	}
15759 	if (((sd_component_mask & comp) == 0) ||
15760 	    (sd_error_level != SCSI_ERR_ALL)) {
15761 		return;
15762 	}
15763 #else
15764 	if (sd_error_level != SCSI_ERR_ALL) {
15765 		return;
15766 	}
15767 #endif
15768 
15769 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
15770 	bufp = local_buf;
15771 	/*
15772 	 * Available length is the length of local_buf[], minus the
15773 	 * length of the title string, minus one for the ":", minus
15774 	 * one for the newline, minus one for the NULL terminator.
15775 	 * This gives the #bytes available for holding the printed
15776 	 * values from the given data buffer.
15777 	 */
15778 	if (fmt == SD_LOG_HEX) {
15779 		format_string = sd_dump_format_string[0];
15780 	} else /* SD_LOG_CHAR */ {
15781 		format_string = sd_dump_format_string[1];
15782 	}
15783 	/*
15784 	 * Available count is the number of elements from the given
15785 	 * data buffer that we can fit into the available length.
15786 	 * This is based upon the size of the format string used.
15787 	 * Make one entry and find it's size.
15788 	 */
15789 	(void) sprintf(bufp, format_string, data[0]);
15790 	entry_len = strlen(bufp);
15791 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
15792 
15793 	j = 0;
15794 	while (j < len) {
15795 		bufp = local_buf;
15796 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
15797 		start_offset = j;
15798 
15799 		end_offset = start_offset + avail_count;
15800 
15801 		(void) sprintf(bufp, "%s:", title);
15802 		bufp += strlen(bufp);
15803 		for (i = start_offset; ((i < end_offset) && (j < len));
15804 		    i++, j++) {
15805 			(void) sprintf(bufp, format_string, data[i]);
15806 			bufp += entry_len;
15807 		}
15808 		(void) sprintf(bufp, "\n");
15809 
15810 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
15811 	}
15812 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
15813 }
15814 
15815 /*
15816  *    Function: sd_print_sense_msg
15817  *
15818  * Description: Log a message based upon the given sense data.
15819  *
15820  *   Arguments: un - ptr to associated softstate
15821  *		bp - ptr to buf(9S) for the command
15822  *		arg - ptr to associate sd_sense_info struct
15823  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15824  *			or SD_NO_RETRY_ISSUED
15825  *
15826  *     Context: May be called from interrupt context
15827  */
15828 
15829 static void
15830 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
15831 {
15832 	struct sd_xbuf	*xp;
15833 	struct scsi_pkt	*pktp;
15834 	uint8_t *sensep;
15835 	daddr_t request_blkno;
15836 	diskaddr_t err_blkno;
15837 	int severity;
15838 	int pfa_flag;
15839 	extern struct scsi_key_strings scsi_cmds[];
15840 
15841 	ASSERT(un != NULL);
15842 	ASSERT(mutex_owned(SD_MUTEX(un)));
15843 	ASSERT(bp != NULL);
15844 	xp = SD_GET_XBUF(bp);
15845 	ASSERT(xp != NULL);
15846 	pktp = SD_GET_PKTP(bp);
15847 	ASSERT(pktp != NULL);
15848 	ASSERT(arg != NULL);
15849 
15850 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
15851 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
15852 
15853 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
15854 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
15855 		severity = SCSI_ERR_RETRYABLE;
15856 	}
15857 
15858 	/* Use absolute block number for the request block number */
15859 	request_blkno = xp->xb_blkno;
15860 
15861 	/*
15862 	 * Now try to get the error block number from the sense data
15863 	 */
15864 	sensep = xp->xb_sense_data;
15865 
15866 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
15867 	    (uint64_t *)&err_blkno)) {
15868 		/*
15869 		 * We retrieved the error block number from the information
15870 		 * portion of the sense data.
15871 		 *
15872 		 * For USCSI commands we are better off using the error
15873 		 * block no. as the requested block no. (This is the best
15874 		 * we can estimate.)
15875 		 */
15876 		if ((SD_IS_BUFIO(xp) == FALSE) &&
15877 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
15878 			request_blkno = err_blkno;
15879 		}
15880 	} else {
15881 		/*
15882 		 * Without the es_valid bit set (for fixed format) or an
15883 		 * information descriptor (for descriptor format) we cannot
15884 		 * be certain of the error blkno, so just use the
15885 		 * request_blkno.
15886 		 */
15887 		err_blkno = (diskaddr_t)request_blkno;
15888 	}
15889 
15890 	/*
15891 	 * The following will log the buffer contents for the release driver
15892 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
15893 	 * level is set to verbose.
15894 	 */
15895 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
15896 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15897 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15898 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
15899 
15900 	if (pfa_flag == FALSE) {
15901 		/* This is normally only set for USCSI */
15902 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
15903 			return;
15904 		}
15905 
15906 		if ((SD_IS_BUFIO(xp) == TRUE) &&
15907 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
15908 		    (severity < sd_error_level))) {
15909 			return;
15910 		}
15911 	}
15912 
15913 	/*
15914 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
15915 	 */
15916 	if ((SD_IS_LSI(un)) &&
15917 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
15918 	    (scsi_sense_asc(sensep) == 0x94) &&
15919 	    (scsi_sense_ascq(sensep) == 0x01)) {
15920 		un->un_sonoma_failure_count++;
15921 		if (un->un_sonoma_failure_count > 1) {
15922 			return;
15923 		}
15924 	}
15925 
15926 	scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
15927 	    request_blkno, err_blkno, scsi_cmds,
15928 	    (struct scsi_extended_sense *)sensep,
15929 	    un->un_additional_codes, NULL);
15930 }
15931 
15932 /*
15933  *    Function: sd_sense_key_no_sense
15934  *
15935  * Description: Recovery action when sense data was not received.
15936  *
15937  *     Context: May be called from interrupt context
15938  */
15939 
15940 static void
15941 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
15942 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15943 {
15944 	struct sd_sense_info	si;
15945 
15946 	ASSERT(un != NULL);
15947 	ASSERT(mutex_owned(SD_MUTEX(un)));
15948 	ASSERT(bp != NULL);
15949 	ASSERT(xp != NULL);
15950 	ASSERT(pktp != NULL);
15951 
15952 	si.ssi_severity = SCSI_ERR_FATAL;
15953 	si.ssi_pfa_flag = FALSE;
15954 
15955 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
15956 
15957 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
15958 	    &si, EIO, (clock_t)0, NULL);
15959 }
15960 
15961 
15962 /*
15963  *    Function: sd_sense_key_recoverable_error
15964  *
15965  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
15966  *
15967  *     Context: May be called from interrupt context
15968  */
15969 
15970 static void
15971 sd_sense_key_recoverable_error(struct sd_lun *un,
15972 	uint8_t *sense_datap,
15973 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
15974 {
15975 	struct sd_sense_info	si;
15976 	uint8_t asc = scsi_sense_asc(sense_datap);
15977 
15978 	ASSERT(un != NULL);
15979 	ASSERT(mutex_owned(SD_MUTEX(un)));
15980 	ASSERT(bp != NULL);
15981 	ASSERT(xp != NULL);
15982 	ASSERT(pktp != NULL);
15983 
15984 	/*
15985 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
15986 	 */
15987 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
15988 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
15989 		si.ssi_severity = SCSI_ERR_INFO;
15990 		si.ssi_pfa_flag = TRUE;
15991 	} else {
15992 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
15993 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
15994 		si.ssi_severity = SCSI_ERR_RECOVERED;
15995 		si.ssi_pfa_flag = FALSE;
15996 	}
15997 
15998 	if (pktp->pkt_resid == 0) {
15999 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16000 		sd_return_command(un, bp);
16001 		return;
16002 	}
16003 
16004 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16005 	    &si, EIO, (clock_t)0, NULL);
16006 }
16007 
16008 
16009 
16010 
16011 /*
16012  *    Function: sd_sense_key_not_ready
16013  *
16014  * Description: Recovery actions for a SCSI "Not Ready" sense key.
16015  *
16016  *     Context: May be called from interrupt context
16017  */
16018 
16019 static void
16020 sd_sense_key_not_ready(struct sd_lun *un,
16021 	uint8_t *sense_datap,
16022 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16023 {
16024 	struct sd_sense_info	si;
16025 	uint8_t asc = scsi_sense_asc(sense_datap);
16026 	uint8_t ascq = scsi_sense_ascq(sense_datap);
16027 
16028 	ASSERT(un != NULL);
16029 	ASSERT(mutex_owned(SD_MUTEX(un)));
16030 	ASSERT(bp != NULL);
16031 	ASSERT(xp != NULL);
16032 	ASSERT(pktp != NULL);
16033 
16034 	si.ssi_severity = SCSI_ERR_FATAL;
16035 	si.ssi_pfa_flag = FALSE;
16036 
16037 	/*
16038 	 * Update error stats after first NOT READY error. Disks may have
16039 	 * been powered down and may need to be restarted.  For CDROMs,
16040 	 * report NOT READY errors only if media is present.
16041 	 */
16042 	if ((ISCD(un) && (asc == 0x3A)) ||
16043 	    (xp->xb_nr_retry_count > 0)) {
16044 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16045 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
16046 	}
16047 
16048 	/*
16049 	 * Just fail if the "not ready" retry limit has been reached.
16050 	 */
16051 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
16052 		/* Special check for error message printing for removables. */
16053 		if (un->un_f_has_removable_media && (asc == 0x04) &&
16054 		    (ascq >= 0x04)) {
16055 			si.ssi_severity = SCSI_ERR_ALL;
16056 		}
16057 		goto fail_command;
16058 	}
16059 
16060 	/*
16061 	 * Check the ASC and ASCQ in the sense data as needed, to determine
16062 	 * what to do.
16063 	 */
16064 	switch (asc) {
16065 	case 0x04:	/* LOGICAL UNIT NOT READY */
16066 		/*
16067 		 * disk drives that don't spin up result in a very long delay
16068 		 * in format without warning messages. We will log a message
16069 		 * if the error level is set to verbose.
16070 		 */
16071 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16072 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16073 			    "logical unit not ready, resetting disk\n");
16074 		}
16075 
16076 		/*
16077 		 * There are different requirements for CDROMs and disks for
16078 		 * the number of retries.  If a CD-ROM is giving this, it is
16079 		 * probably reading TOC and is in the process of getting
16080 		 * ready, so we should keep on trying for a long time to make
16081 		 * sure that all types of media are taken in account (for
16082 		 * some media the drive takes a long time to read TOC).  For
16083 		 * disks we do not want to retry this too many times as this
16084 		 * can cause a long hang in format when the drive refuses to
16085 		 * spin up (a very common failure).
16086 		 */
16087 		switch (ascq) {
16088 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
16089 			/*
16090 			 * Disk drives frequently refuse to spin up which
16091 			 * results in a very long hang in format without
16092 			 * warning messages.
16093 			 *
16094 			 * Note: This code preserves the legacy behavior of
16095 			 * comparing xb_nr_retry_count against zero for fibre
16096 			 * channel targets instead of comparing against the
16097 			 * un_reset_retry_count value.  The reason for this
16098 			 * discrepancy has been so utterly lost beneath the
16099 			 * Sands of Time that even Indiana Jones could not
16100 			 * find it.
16101 			 */
16102 			if (un->un_f_is_fibre == TRUE) {
16103 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
16104 				    (xp->xb_nr_retry_count > 0)) &&
16105 				    (un->un_startstop_timeid == NULL)) {
16106 					scsi_log(SD_DEVINFO(un), sd_label,
16107 					    CE_WARN, "logical unit not ready, "
16108 					    "resetting disk\n");
16109 					sd_reset_target(un, pktp);
16110 				}
16111 			} else {
16112 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
16113 				    (xp->xb_nr_retry_count >
16114 				    un->un_reset_retry_count)) &&
16115 				    (un->un_startstop_timeid == NULL)) {
16116 					scsi_log(SD_DEVINFO(un), sd_label,
16117 					    CE_WARN, "logical unit not ready, "
16118 					    "resetting disk\n");
16119 					sd_reset_target(un, pktp);
16120 				}
16121 			}
16122 			break;
16123 
16124 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
16125 			/*
16126 			 * If the target is in the process of becoming
16127 			 * ready, just proceed with the retry. This can
16128 			 * happen with CD-ROMs that take a long time to
16129 			 * read TOC after a power cycle or reset.
16130 			 */
16131 			goto do_retry;
16132 
16133 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
16134 			break;
16135 
16136 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
16137 			/*
16138 			 * Retries cannot help here so just fail right away.
16139 			 */
16140 			goto fail_command;
16141 
16142 		case 0x88:
16143 			/*
16144 			 * Vendor-unique code for T3/T4: it indicates a
16145 			 * path problem in a mutipathed config, but as far as
16146 			 * the target driver is concerned it equates to a fatal
16147 			 * error, so we should just fail the command right away
16148 			 * (without printing anything to the console). If this
16149 			 * is not a T3/T4, fall thru to the default recovery
16150 			 * action.
16151 			 * T3/T4 is FC only, don't need to check is_fibre
16152 			 */
16153 			if (SD_IS_T3(un) || SD_IS_T4(un)) {
16154 				sd_return_failed_command(un, bp, EIO);
16155 				return;
16156 			}
16157 			/* FALLTHRU */
16158 
16159 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
16160 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
16161 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
16162 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
16163 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
16164 		default:    /* Possible future codes in SCSI spec? */
16165 			/*
16166 			 * For removable-media devices, do not retry if
16167 			 * ASCQ > 2 as these result mostly from USCSI commands
16168 			 * on MMC devices issued to check status of an
16169 			 * operation initiated in immediate mode.  Also for
16170 			 * ASCQ >= 4 do not print console messages as these
16171 			 * mainly represent a user-initiated operation
16172 			 * instead of a system failure.
16173 			 */
16174 			if (un->un_f_has_removable_media) {
16175 				si.ssi_severity = SCSI_ERR_ALL;
16176 				goto fail_command;
16177 			}
16178 			break;
16179 		}
16180 
16181 		/*
16182 		 * As part of our recovery attempt for the NOT READY
16183 		 * condition, we issue a START STOP UNIT command. However
16184 		 * we want to wait for a short delay before attempting this
16185 		 * as there may still be more commands coming back from the
16186 		 * target with the check condition. To do this we use
16187 		 * timeout(9F) to call sd_start_stop_unit_callback() after
16188 		 * the delay interval expires. (sd_start_stop_unit_callback()
16189 		 * dispatches sd_start_stop_unit_task(), which will issue
16190 		 * the actual START STOP UNIT command. The delay interval
16191 		 * is one-half of the delay that we will use to retry the
16192 		 * command that generated the NOT READY condition.
16193 		 *
16194 		 * Note that we could just dispatch sd_start_stop_unit_task()
16195 		 * from here and allow it to sleep for the delay interval,
16196 		 * but then we would be tying up the taskq thread
16197 		 * uncesessarily for the duration of the delay.
16198 		 *
16199 		 * Do not issue the START STOP UNIT if the current command
16200 		 * is already a START STOP UNIT.
16201 		 */
16202 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
16203 			break;
16204 		}
16205 
16206 		/*
16207 		 * Do not schedule the timeout if one is already pending.
16208 		 */
16209 		if (un->un_startstop_timeid != NULL) {
16210 			SD_INFO(SD_LOG_ERROR, un,
16211 			    "sd_sense_key_not_ready: restart already issued to"
16212 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
16213 			    ddi_get_instance(SD_DEVINFO(un)));
16214 			break;
16215 		}
16216 
16217 		/*
16218 		 * Schedule the START STOP UNIT command, then queue the command
16219 		 * for a retry.
16220 		 *
16221 		 * Note: A timeout is not scheduled for this retry because we
16222 		 * want the retry to be serial with the START_STOP_UNIT. The
16223 		 * retry will be started when the START_STOP_UNIT is completed
16224 		 * in sd_start_stop_unit_task.
16225 		 */
16226 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
16227 		    un, SD_BSY_TIMEOUT / 2);
16228 		xp->xb_nr_retry_count++;
16229 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
16230 		return;
16231 
16232 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
16233 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16234 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16235 			    "unit does not respond to selection\n");
16236 		}
16237 		break;
16238 
16239 	case 0x3A:	/* MEDIUM NOT PRESENT */
16240 		if (sd_error_level >= SCSI_ERR_FATAL) {
16241 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16242 			    "Caddy not inserted in drive\n");
16243 		}
16244 
16245 		sr_ejected(un);
16246 		un->un_mediastate = DKIO_EJECTED;
16247 		/* The state has changed, inform the media watch routines */
16248 		cv_broadcast(&un->un_state_cv);
16249 		/* Just fail if no media is present in the drive. */
16250 		goto fail_command;
16251 
16252 	default:
16253 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16254 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
16255 			    "Unit not Ready. Additional sense code 0x%x\n",
16256 			    asc);
16257 		}
16258 		break;
16259 	}
16260 
16261 do_retry:
16262 
16263 	/*
16264 	 * Retry the command, as some targets may report NOT READY for
16265 	 * several seconds after being reset.
16266 	 */
16267 	xp->xb_nr_retry_count++;
16268 	si.ssi_severity = SCSI_ERR_RETRYABLE;
16269 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
16270 	    &si, EIO, SD_BSY_TIMEOUT, NULL);
16271 
16272 	return;
16273 
16274 fail_command:
16275 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16276 	sd_return_failed_command(un, bp, EIO);
16277 }
16278 
16279 
16280 
16281 /*
16282  *    Function: sd_sense_key_medium_or_hardware_error
16283  *
16284  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
16285  *		sense key.
16286  *
16287  *     Context: May be called from interrupt context
16288  */
16289 
16290 static void
16291 sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
16292 	uint8_t *sense_datap,
16293 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16294 {
16295 	struct sd_sense_info	si;
16296 	uint8_t sense_key = scsi_sense_key(sense_datap);
16297 	uint8_t asc = scsi_sense_asc(sense_datap);
16298 
16299 	ASSERT(un != NULL);
16300 	ASSERT(mutex_owned(SD_MUTEX(un)));
16301 	ASSERT(bp != NULL);
16302 	ASSERT(xp != NULL);
16303 	ASSERT(pktp != NULL);
16304 
16305 	si.ssi_severity = SCSI_ERR_FATAL;
16306 	si.ssi_pfa_flag = FALSE;
16307 
16308 	if (sense_key == KEY_MEDIUM_ERROR) {
16309 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
16310 	}
16311 
16312 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16313 
16314 	if ((un->un_reset_retry_count != 0) &&
16315 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
16316 		mutex_exit(SD_MUTEX(un));
16317 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
16318 		if (un->un_f_allow_bus_device_reset == TRUE) {
16319 
16320 			boolean_t try_resetting_target = B_TRUE;
16321 
16322 			/*
16323 			 * We need to be able to handle specific ASC when we are
16324 			 * handling a KEY_HARDWARE_ERROR. In particular
16325 			 * taking the default action of resetting the target may
16326 			 * not be the appropriate way to attempt recovery.
16327 			 * Resetting a target because of a single LUN failure
16328 			 * victimizes all LUNs on that target.
16329 			 *
16330 			 * This is true for the LSI arrays, if an LSI
16331 			 * array controller returns an ASC of 0x84 (LUN Dead) we
16332 			 * should trust it.
16333 			 */
16334 
16335 			if (sense_key == KEY_HARDWARE_ERROR) {
16336 				switch (asc) {
16337 				case 0x84:
16338 					if (SD_IS_LSI(un)) {
16339 						try_resetting_target = B_FALSE;
16340 					}
16341 					break;
16342 				default:
16343 					break;
16344 				}
16345 			}
16346 
16347 			if (try_resetting_target == B_TRUE) {
16348 				int reset_retval = 0;
16349 				if (un->un_f_lun_reset_enabled == TRUE) {
16350 					SD_TRACE(SD_LOG_IO_CORE, un,
16351 					    "sd_sense_key_medium_or_hardware_"
16352 					    "error: issuing RESET_LUN\n");
16353 					reset_retval =
16354 					    scsi_reset(SD_ADDRESS(un),
16355 					    RESET_LUN);
16356 				}
16357 				if (reset_retval == 0) {
16358 					SD_TRACE(SD_LOG_IO_CORE, un,
16359 					    "sd_sense_key_medium_or_hardware_"
16360 					    "error: issuing RESET_TARGET\n");
16361 					(void) scsi_reset(SD_ADDRESS(un),
16362 					    RESET_TARGET);
16363 				}
16364 			}
16365 		}
16366 		mutex_enter(SD_MUTEX(un));
16367 	}
16368 
16369 	/*
16370 	 * This really ought to be a fatal error, but we will retry anyway
16371 	 * as some drives report this as a spurious error.
16372 	 */
16373 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16374 	    &si, EIO, (clock_t)0, NULL);
16375 }
16376 
16377 
16378 
16379 /*
16380  *    Function: sd_sense_key_illegal_request
16381  *
16382  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
16383  *
16384  *     Context: May be called from interrupt context
16385  */
16386 
16387 static void
16388 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
16389 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16390 {
16391 	struct sd_sense_info	si;
16392 
16393 	ASSERT(un != NULL);
16394 	ASSERT(mutex_owned(SD_MUTEX(un)));
16395 	ASSERT(bp != NULL);
16396 	ASSERT(xp != NULL);
16397 	ASSERT(pktp != NULL);
16398 
16399 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
16400 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
16401 
16402 	si.ssi_severity = SCSI_ERR_INFO;
16403 	si.ssi_pfa_flag = FALSE;
16404 
16405 	/* Pointless to retry if the target thinks it's an illegal request */
16406 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16407 	sd_return_failed_command(un, bp, EIO);
16408 }
16409 
16410 
16411 
16412 
16413 /*
16414  *    Function: sd_sense_key_unit_attention
16415  *
16416  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
16417  *
16418  *     Context: May be called from interrupt context
16419  */
16420 
16421 static void
16422 sd_sense_key_unit_attention(struct sd_lun *un,
16423 	uint8_t *sense_datap,
16424 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16425 {
16426 	/*
16427 	 * For UNIT ATTENTION we allow retries for one minute. Devices
16428 	 * like Sonoma can return UNIT ATTENTION close to a minute
16429 	 * under certain conditions.
16430 	 */
16431 	int	retry_check_flag = SD_RETRIES_UA;
16432 	boolean_t	kstat_updated = B_FALSE;
16433 	struct	sd_sense_info		si;
16434 	uint8_t asc = scsi_sense_asc(sense_datap);
16435 
16436 	ASSERT(un != NULL);
16437 	ASSERT(mutex_owned(SD_MUTEX(un)));
16438 	ASSERT(bp != NULL);
16439 	ASSERT(xp != NULL);
16440 	ASSERT(pktp != NULL);
16441 
16442 	si.ssi_severity = SCSI_ERR_INFO;
16443 	si.ssi_pfa_flag = FALSE;
16444 
16445 
16446 	switch (asc) {
16447 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
16448 		if (sd_report_pfa != 0) {
16449 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
16450 			si.ssi_pfa_flag = TRUE;
16451 			retry_check_flag = SD_RETRIES_STANDARD;
16452 			goto do_retry;
16453 		}
16454 
16455 		break;
16456 
16457 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
16458 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
16459 			un->un_resvd_status |=
16460 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
16461 		}
16462 #ifdef _LP64
16463 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
16464 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
16465 			    un, KM_NOSLEEP) == 0) {
16466 				/*
16467 				 * If we can't dispatch the task we'll just
16468 				 * live without descriptor sense.  We can
16469 				 * try again on the next "unit attention"
16470 				 */
16471 				SD_ERROR(SD_LOG_ERROR, un,
16472 				    "sd_sense_key_unit_attention: "
16473 				    "Could not dispatch "
16474 				    "sd_reenable_dsense_task\n");
16475 			}
16476 		}
16477 #endif /* _LP64 */
16478 		/* FALLTHRU */
16479 
16480 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
16481 		if (!un->un_f_has_removable_media) {
16482 			break;
16483 		}
16484 
16485 		/*
16486 		 * When we get a unit attention from a removable-media device,
16487 		 * it may be in a state that will take a long time to recover
16488 		 * (e.g., from a reset).  Since we are executing in interrupt
16489 		 * context here, we cannot wait around for the device to come
16490 		 * back. So hand this command off to sd_media_change_task()
16491 		 * for deferred processing under taskq thread context. (Note
16492 		 * that the command still may be failed if a problem is
16493 		 * encountered at a later time.)
16494 		 */
16495 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
16496 		    KM_NOSLEEP) == 0) {
16497 			/*
16498 			 * Cannot dispatch the request so fail the command.
16499 			 */
16500 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
16501 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16502 			si.ssi_severity = SCSI_ERR_FATAL;
16503 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16504 			sd_return_failed_command(un, bp, EIO);
16505 		}
16506 
16507 		/*
16508 		 * If failed to dispatch sd_media_change_task(), we already
16509 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
16510 		 * we should update kstat later if it encounters an error. So,
16511 		 * we update kstat_updated flag here.
16512 		 */
16513 		kstat_updated = B_TRUE;
16514 
16515 		/*
16516 		 * Either the command has been successfully dispatched to a
16517 		 * task Q for retrying, or the dispatch failed. In either case
16518 		 * do NOT retry again by calling sd_retry_command. This sets up
16519 		 * two retries of the same command and when one completes and
16520 		 * frees the resources the other will access freed memory,
16521 		 * a bad thing.
16522 		 */
16523 		return;
16524 
16525 	default:
16526 		break;
16527 	}
16528 
16529 	/*
16530 	 * Update kstat if we haven't done that.
16531 	 */
16532 	if (!kstat_updated) {
16533 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16534 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16535 	}
16536 
16537 do_retry:
16538 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
16539 	    EIO, SD_UA_RETRY_DELAY, NULL);
16540 }
16541 
16542 
16543 
16544 /*
16545  *    Function: sd_sense_key_fail_command
16546  *
16547  * Description: Use to fail a command when we don't like the sense key that
16548  *		was returned.
16549  *
16550  *     Context: May be called from interrupt context
16551  */
16552 
16553 static void
16554 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
16555 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16556 {
16557 	struct sd_sense_info	si;
16558 
16559 	ASSERT(un != NULL);
16560 	ASSERT(mutex_owned(SD_MUTEX(un)));
16561 	ASSERT(bp != NULL);
16562 	ASSERT(xp != NULL);
16563 	ASSERT(pktp != NULL);
16564 
16565 	si.ssi_severity = SCSI_ERR_FATAL;
16566 	si.ssi_pfa_flag = FALSE;
16567 
16568 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16569 	sd_return_failed_command(un, bp, EIO);
16570 }
16571 
16572 
16573 
16574 /*
16575  *    Function: sd_sense_key_blank_check
16576  *
16577  * Description: Recovery actions for a SCSI "Blank Check" sense key.
16578  *		Has no monetary connotation.
16579  *
16580  *     Context: May be called from interrupt context
16581  */
16582 
16583 static void
16584 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
16585 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16586 {
16587 	struct sd_sense_info	si;
16588 
16589 	ASSERT(un != NULL);
16590 	ASSERT(mutex_owned(SD_MUTEX(un)));
16591 	ASSERT(bp != NULL);
16592 	ASSERT(xp != NULL);
16593 	ASSERT(pktp != NULL);
16594 
16595 	/*
16596 	 * Blank check is not fatal for removable devices, therefore
16597 	 * it does not require a console message.
16598 	 */
16599 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
16600 	    SCSI_ERR_FATAL;
16601 	si.ssi_pfa_flag = FALSE;
16602 
16603 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16604 	sd_return_failed_command(un, bp, EIO);
16605 }
16606 
16607 
16608 
16609 
16610 /*
16611  *    Function: sd_sense_key_aborted_command
16612  *
16613  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
16614  *
16615  *     Context: May be called from interrupt context
16616  */
16617 
16618 static void
16619 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
16620 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16621 {
16622 	struct sd_sense_info	si;
16623 
16624 	ASSERT(un != NULL);
16625 	ASSERT(mutex_owned(SD_MUTEX(un)));
16626 	ASSERT(bp != NULL);
16627 	ASSERT(xp != NULL);
16628 	ASSERT(pktp != NULL);
16629 
16630 	si.ssi_severity = SCSI_ERR_FATAL;
16631 	si.ssi_pfa_flag = FALSE;
16632 
16633 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16634 
16635 	/*
16636 	 * This really ought to be a fatal error, but we will retry anyway
16637 	 * as some drives report this as a spurious error.
16638 	 */
16639 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16640 	    &si, EIO, drv_usectohz(100000), NULL);
16641 }
16642 
16643 
16644 
16645 /*
16646  *    Function: sd_sense_key_default
16647  *
16648  * Description: Default recovery action for several SCSI sense keys (basically
16649  *		attempts a retry).
16650  *
16651  *     Context: May be called from interrupt context
16652  */
16653 
16654 static void
16655 sd_sense_key_default(struct sd_lun *un,
16656 	uint8_t *sense_datap,
16657 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16658 {
16659 	struct sd_sense_info	si;
16660 	uint8_t sense_key = scsi_sense_key(sense_datap);
16661 
16662 	ASSERT(un != NULL);
16663 	ASSERT(mutex_owned(SD_MUTEX(un)));
16664 	ASSERT(bp != NULL);
16665 	ASSERT(xp != NULL);
16666 	ASSERT(pktp != NULL);
16667 
16668 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16669 
16670 	/*
16671 	 * Undecoded sense key.	Attempt retries and hope that will fix
16672 	 * the problem.  Otherwise, we're dead.
16673 	 */
16674 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
16675 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16676 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
16677 	}
16678 
16679 	si.ssi_severity = SCSI_ERR_FATAL;
16680 	si.ssi_pfa_flag = FALSE;
16681 
16682 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16683 	    &si, EIO, (clock_t)0, NULL);
16684 }
16685 
16686 
16687 
16688 /*
16689  *    Function: sd_print_retry_msg
16690  *
16691  * Description: Print a message indicating the retry action being taken.
16692  *
16693  *   Arguments: un - ptr to associated softstate
16694  *		bp - ptr to buf(9S) for the command
16695  *		arg - not used.
16696  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16697  *			or SD_NO_RETRY_ISSUED
16698  *
16699  *     Context: May be called from interrupt context
16700  */
16701 /* ARGSUSED */
16702 static void
16703 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
16704 {
16705 	struct sd_xbuf	*xp;
16706 	struct scsi_pkt *pktp;
16707 	char *reasonp;
16708 	char *msgp;
16709 
16710 	ASSERT(un != NULL);
16711 	ASSERT(mutex_owned(SD_MUTEX(un)));
16712 	ASSERT(bp != NULL);
16713 	pktp = SD_GET_PKTP(bp);
16714 	ASSERT(pktp != NULL);
16715 	xp = SD_GET_XBUF(bp);
16716 	ASSERT(xp != NULL);
16717 
16718 	ASSERT(!mutex_owned(&un->un_pm_mutex));
16719 	mutex_enter(&un->un_pm_mutex);
16720 	if ((un->un_state == SD_STATE_SUSPENDED) ||
16721 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
16722 	    (pktp->pkt_flags & FLAG_SILENT)) {
16723 		mutex_exit(&un->un_pm_mutex);
16724 		goto update_pkt_reason;
16725 	}
16726 	mutex_exit(&un->un_pm_mutex);
16727 
16728 	/*
16729 	 * Suppress messages if they are all the same pkt_reason; with
16730 	 * TQ, many (up to 256) are returned with the same pkt_reason.
16731 	 * If we are in panic, then suppress the retry messages.
16732 	 */
16733 	switch (flag) {
16734 	case SD_NO_RETRY_ISSUED:
16735 		msgp = "giving up";
16736 		break;
16737 	case SD_IMMEDIATE_RETRY_ISSUED:
16738 	case SD_DELAYED_RETRY_ISSUED:
16739 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
16740 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
16741 		    (sd_error_level != SCSI_ERR_ALL))) {
16742 			return;
16743 		}
16744 		msgp = "retrying command";
16745 		break;
16746 	default:
16747 		goto update_pkt_reason;
16748 	}
16749 
16750 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
16751 	    scsi_rname(pktp->pkt_reason));
16752 
16753 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16754 	    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
16755 
16756 update_pkt_reason:
16757 	/*
16758 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
16759 	 * This is to prevent multiple console messages for the same failure
16760 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
16761 	 * when the command is retried successfully because there still may be
16762 	 * more commands coming back with the same value of pktp->pkt_reason.
16763 	 */
16764 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
16765 		un->un_last_pkt_reason = pktp->pkt_reason;
16766 	}
16767 }
16768 
16769 
16770 /*
16771  *    Function: sd_print_cmd_incomplete_msg
16772  *
16773  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
16774  *
16775  *   Arguments: un - ptr to associated softstate
16776  *		bp - ptr to buf(9S) for the command
16777  *		arg - passed to sd_print_retry_msg()
16778  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16779  *			or SD_NO_RETRY_ISSUED
16780  *
16781  *     Context: May be called from interrupt context
16782  */
16783 
16784 static void
16785 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
16786 	int code)
16787 {
16788 	dev_info_t	*dip;
16789 
16790 	ASSERT(un != NULL);
16791 	ASSERT(mutex_owned(SD_MUTEX(un)));
16792 	ASSERT(bp != NULL);
16793 
16794 	switch (code) {
16795 	case SD_NO_RETRY_ISSUED:
16796 		/* Command was failed. Someone turned off this target? */
16797 		if (un->un_state != SD_STATE_OFFLINE) {
16798 			/*
16799 			 * Suppress message if we are detaching and
16800 			 * device has been disconnected
16801 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
16802 			 * private interface and not part of the DDI
16803 			 */
16804 			dip = un->un_sd->sd_dev;
16805 			if (!(DEVI_IS_DETACHING(dip) &&
16806 			    DEVI_IS_DEVICE_REMOVED(dip))) {
16807 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16808 				"disk not responding to selection\n");
16809 			}
16810 			New_state(un, SD_STATE_OFFLINE);
16811 		}
16812 		break;
16813 
16814 	case SD_DELAYED_RETRY_ISSUED:
16815 	case SD_IMMEDIATE_RETRY_ISSUED:
16816 	default:
16817 		/* Command was successfully queued for retry */
16818 		sd_print_retry_msg(un, bp, arg, code);
16819 		break;
16820 	}
16821 }
16822 
16823 
16824 /*
16825  *    Function: sd_pkt_reason_cmd_incomplete
16826  *
16827  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
16828  *
16829  *     Context: May be called from interrupt context
16830  */
16831 
16832 static void
16833 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
16834 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16835 {
16836 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
16837 
16838 	ASSERT(un != NULL);
16839 	ASSERT(mutex_owned(SD_MUTEX(un)));
16840 	ASSERT(bp != NULL);
16841 	ASSERT(xp != NULL);
16842 	ASSERT(pktp != NULL);
16843 
16844 	/* Do not do a reset if selection did not complete */
16845 	/* Note: Should this not just check the bit? */
16846 	if (pktp->pkt_state != STATE_GOT_BUS) {
16847 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
16848 		sd_reset_target(un, pktp);
16849 	}
16850 
16851 	/*
16852 	 * If the target was not successfully selected, then set
16853 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
16854 	 * with the target, and further retries and/or commands are
16855 	 * likely to take a long time.
16856 	 */
16857 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
16858 		flag |= SD_RETRIES_FAILFAST;
16859 	}
16860 
16861 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16862 
16863 	sd_retry_command(un, bp, flag,
16864 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16865 }
16866 
16867 
16868 
16869 /*
16870  *    Function: sd_pkt_reason_cmd_tran_err
16871  *
16872  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
16873  *
16874  *     Context: May be called from interrupt context
16875  */
16876 
16877 static void
16878 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
16879 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16880 {
16881 	ASSERT(un != NULL);
16882 	ASSERT(mutex_owned(SD_MUTEX(un)));
16883 	ASSERT(bp != NULL);
16884 	ASSERT(xp != NULL);
16885 	ASSERT(pktp != NULL);
16886 
16887 	/*
16888 	 * Do not reset if we got a parity error, or if
16889 	 * selection did not complete.
16890 	 */
16891 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16892 	/* Note: Should this not just check the bit for pkt_state? */
16893 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
16894 	    (pktp->pkt_state != STATE_GOT_BUS)) {
16895 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
16896 		sd_reset_target(un, pktp);
16897 	}
16898 
16899 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16900 
16901 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
16902 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16903 }
16904 
16905 
16906 
16907 /*
16908  *    Function: sd_pkt_reason_cmd_reset
16909  *
16910  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
16911  *
16912  *     Context: May be called from interrupt context
16913  */
16914 
16915 static void
16916 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
16917 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16918 {
16919 	ASSERT(un != NULL);
16920 	ASSERT(mutex_owned(SD_MUTEX(un)));
16921 	ASSERT(bp != NULL);
16922 	ASSERT(xp != NULL);
16923 	ASSERT(pktp != NULL);
16924 
16925 	/* The target may still be running the command, so try to reset. */
16926 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16927 	sd_reset_target(un, pktp);
16928 
16929 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16930 
16931 	/*
16932 	 * If pkt_reason is CMD_RESET chances are that this pkt got
16933 	 * reset because another target on this bus caused it. The target
16934 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
16935 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
16936 	 */
16937 
16938 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
16939 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16940 }
16941 
16942 
16943 
16944 
16945 /*
16946  *    Function: sd_pkt_reason_cmd_aborted
16947  *
16948  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
16949  *
16950  *     Context: May be called from interrupt context
16951  */
16952 
16953 static void
16954 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
16955 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16956 {
16957 	ASSERT(un != NULL);
16958 	ASSERT(mutex_owned(SD_MUTEX(un)));
16959 	ASSERT(bp != NULL);
16960 	ASSERT(xp != NULL);
16961 	ASSERT(pktp != NULL);
16962 
16963 	/* The target may still be running the command, so try to reset. */
16964 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16965 	sd_reset_target(un, pktp);
16966 
16967 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16968 
16969 	/*
16970 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
16971 	 * aborted because another target on this bus caused it. The target
16972 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
16973 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
16974 	 */
16975 
16976 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
16977 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16978 }
16979 
16980 
16981 
16982 /*
16983  *    Function: sd_pkt_reason_cmd_timeout
16984  *
16985  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
16986  *
16987  *     Context: May be called from interrupt context
16988  */
16989 
16990 static void
16991 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
16992 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16993 {
16994 	ASSERT(un != NULL);
16995 	ASSERT(mutex_owned(SD_MUTEX(un)));
16996 	ASSERT(bp != NULL);
16997 	ASSERT(xp != NULL);
16998 	ASSERT(pktp != NULL);
16999 
17000 
17001 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
17002 	sd_reset_target(un, pktp);
17003 
17004 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17005 
17006 	/*
17007 	 * A command timeout indicates that we could not establish
17008 	 * communication with the target, so set SD_RETRIES_FAILFAST
17009 	 * as further retries/commands are likely to take a long time.
17010 	 */
17011 	sd_retry_command(un, bp,
17012 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
17013 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17014 }
17015 
17016 
17017 
17018 /*
17019  *    Function: sd_pkt_reason_cmd_unx_bus_free
17020  *
17021  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
17022  *
17023  *     Context: May be called from interrupt context
17024  */
17025 
17026 static void
17027 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
17028 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17029 {
17030 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
17031 
17032 	ASSERT(un != NULL);
17033 	ASSERT(mutex_owned(SD_MUTEX(un)));
17034 	ASSERT(bp != NULL);
17035 	ASSERT(xp != NULL);
17036 	ASSERT(pktp != NULL);
17037 
17038 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17039 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17040 
17041 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
17042 	    sd_print_retry_msg : NULL;
17043 
17044 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
17045 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17046 }
17047 
17048 
17049 /*
17050  *    Function: sd_pkt_reason_cmd_tag_reject
17051  *
17052  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
17053  *
17054  *     Context: May be called from interrupt context
17055  */
17056 
17057 static void
17058 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
17059 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17060 {
17061 	ASSERT(un != NULL);
17062 	ASSERT(mutex_owned(SD_MUTEX(un)));
17063 	ASSERT(bp != NULL);
17064 	ASSERT(xp != NULL);
17065 	ASSERT(pktp != NULL);
17066 
17067 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17068 	pktp->pkt_flags = 0;
17069 	un->un_tagflags = 0;
17070 	if (un->un_f_opt_queueing == TRUE) {
17071 		un->un_throttle = min(un->un_throttle, 3);
17072 	} else {
17073 		un->un_throttle = 1;
17074 	}
17075 	mutex_exit(SD_MUTEX(un));
17076 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
17077 	mutex_enter(SD_MUTEX(un));
17078 
17079 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17080 
17081 	/* Legacy behavior not to check retry counts here. */
17082 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
17083 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17084 }
17085 
17086 
17087 /*
17088  *    Function: sd_pkt_reason_default
17089  *
17090  * Description: Default recovery actions for SCSA pkt_reason values that
17091  *		do not have more explicit recovery actions.
17092  *
17093  *     Context: May be called from interrupt context
17094  */
17095 
17096 static void
17097 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
17098 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17099 {
17100 	ASSERT(un != NULL);
17101 	ASSERT(mutex_owned(SD_MUTEX(un)));
17102 	ASSERT(bp != NULL);
17103 	ASSERT(xp != NULL);
17104 	ASSERT(pktp != NULL);
17105 
17106 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
17107 	sd_reset_target(un, pktp);
17108 
17109 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17110 
17111 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
17112 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17113 }
17114 
17115 
17116 
17117 /*
17118  *    Function: sd_pkt_status_check_condition
17119  *
17120  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
17121  *
17122  *     Context: May be called from interrupt context
17123  */
17124 
17125 static void
17126 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
17127 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17128 {
17129 	ASSERT(un != NULL);
17130 	ASSERT(mutex_owned(SD_MUTEX(un)));
17131 	ASSERT(bp != NULL);
17132 	ASSERT(xp != NULL);
17133 	ASSERT(pktp != NULL);
17134 
17135 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
17136 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
17137 
17138 	/*
17139 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
17140 	 * command will be retried after the request sense). Otherwise, retry
17141 	 * the command. Note: we are issuing the request sense even though the
17142 	 * retry limit may have been reached for the failed command.
17143 	 */
17144 	if (un->un_f_arq_enabled == FALSE) {
17145 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
17146 		    "no ARQ, sending request sense command\n");
17147 		sd_send_request_sense_command(un, bp, pktp);
17148 	} else {
17149 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
17150 		    "ARQ,retrying request sense command\n");
17151 #if defined(__i386) || defined(__amd64)
17152 		/*
17153 		 * The SD_RETRY_DELAY value need to be adjusted here
17154 		 * when SD_RETRY_DELAY change in sddef.h
17155 		 */
17156 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
17157 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
17158 		    NULL);
17159 #else
17160 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
17161 		    EIO, SD_RETRY_DELAY, NULL);
17162 #endif
17163 	}
17164 
17165 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
17166 }
17167 
17168 
17169 /*
17170  *    Function: sd_pkt_status_busy
17171  *
17172  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
17173  *
17174  *     Context: May be called from interrupt context
17175  */
17176 
17177 static void
17178 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17179 	struct scsi_pkt *pktp)
17180 {
17181 	ASSERT(un != NULL);
17182 	ASSERT(mutex_owned(SD_MUTEX(un)));
17183 	ASSERT(bp != NULL);
17184 	ASSERT(xp != NULL);
17185 	ASSERT(pktp != NULL);
17186 
17187 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17188 	    "sd_pkt_status_busy: entry\n");
17189 
17190 	/* If retries are exhausted, just fail the command. */
17191 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
17192 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17193 		    "device busy too long\n");
17194 		sd_return_failed_command(un, bp, EIO);
17195 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17196 		    "sd_pkt_status_busy: exit\n");
17197 		return;
17198 	}
17199 	xp->xb_retry_count++;
17200 
17201 	/*
17202 	 * Try to reset the target. However, we do not want to perform
17203 	 * more than one reset if the device continues to fail. The reset
17204 	 * will be performed when the retry count reaches the reset
17205 	 * threshold.  This threshold should be set such that at least
17206 	 * one retry is issued before the reset is performed.
17207 	 */
17208 	if (xp->xb_retry_count ==
17209 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
17210 		int rval = 0;
17211 		mutex_exit(SD_MUTEX(un));
17212 		if (un->un_f_allow_bus_device_reset == TRUE) {
17213 			/*
17214 			 * First try to reset the LUN; if we cannot then
17215 			 * try to reset the target.
17216 			 */
17217 			if (un->un_f_lun_reset_enabled == TRUE) {
17218 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17219 				    "sd_pkt_status_busy: RESET_LUN\n");
17220 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
17221 			}
17222 			if (rval == 0) {
17223 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17224 				    "sd_pkt_status_busy: RESET_TARGET\n");
17225 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
17226 			}
17227 		}
17228 		if (rval == 0) {
17229 			/*
17230 			 * If the RESET_LUN and/or RESET_TARGET failed,
17231 			 * try RESET_ALL
17232 			 */
17233 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17234 			    "sd_pkt_status_busy: RESET_ALL\n");
17235 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
17236 		}
17237 		mutex_enter(SD_MUTEX(un));
17238 		if (rval == 0) {
17239 			/*
17240 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
17241 			 * At this point we give up & fail the command.
17242 			 */
17243 			sd_return_failed_command(un, bp, EIO);
17244 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17245 			    "sd_pkt_status_busy: exit (failed cmd)\n");
17246 			return;
17247 		}
17248 	}
17249 
17250 	/*
17251 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
17252 	 * we have already checked the retry counts above.
17253 	 */
17254 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
17255 	    EIO, SD_BSY_TIMEOUT, NULL);
17256 
17257 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17258 	    "sd_pkt_status_busy: exit\n");
17259 }
17260 
17261 
17262 /*
17263  *    Function: sd_pkt_status_reservation_conflict
17264  *
17265  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
17266  *		command status.
17267  *
17268  *     Context: May be called from interrupt context
17269  */
17270 
17271 static void
17272 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
17273 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17274 {
17275 	ASSERT(un != NULL);
17276 	ASSERT(mutex_owned(SD_MUTEX(un)));
17277 	ASSERT(bp != NULL);
17278 	ASSERT(xp != NULL);
17279 	ASSERT(pktp != NULL);
17280 
17281 	/*
17282 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
17283 	 * conflict could be due to various reasons like incorrect keys, not
17284 	 * registered or not reserved etc. So, we return EACCES to the caller.
17285 	 */
17286 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
17287 		int cmd = SD_GET_PKT_OPCODE(pktp);
17288 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
17289 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
17290 			sd_return_failed_command(un, bp, EACCES);
17291 			return;
17292 		}
17293 	}
17294 
17295 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
17296 
17297 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
17298 		if (sd_failfast_enable != 0) {
17299 			/* By definition, we must panic here.... */
17300 			sd_panic_for_res_conflict(un);
17301 			/*NOTREACHED*/
17302 		}
17303 		SD_ERROR(SD_LOG_IO, un,
17304 		    "sd_handle_resv_conflict: Disk Reserved\n");
17305 		sd_return_failed_command(un, bp, EACCES);
17306 		return;
17307 	}
17308 
17309 	/*
17310 	 * 1147670: retry only if sd_retry_on_reservation_conflict
17311 	 * property is set (default is 1). Retries will not succeed
17312 	 * on a disk reserved by another initiator. HA systems
17313 	 * may reset this via sd.conf to avoid these retries.
17314 	 *
17315 	 * Note: The legacy return code for this failure is EIO, however EACCES
17316 	 * seems more appropriate for a reservation conflict.
17317 	 */
17318 	if (sd_retry_on_reservation_conflict == 0) {
17319 		SD_ERROR(SD_LOG_IO, un,
17320 		    "sd_handle_resv_conflict: Device Reserved\n");
17321 		sd_return_failed_command(un, bp, EIO);
17322 		return;
17323 	}
17324 
17325 	/*
17326 	 * Retry the command if we can.
17327 	 *
17328 	 * Note: The legacy return code for this failure is EIO, however EACCES
17329 	 * seems more appropriate for a reservation conflict.
17330 	 */
17331 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
17332 	    (clock_t)2, NULL);
17333 }
17334 
17335 
17336 
17337 /*
17338  *    Function: sd_pkt_status_qfull
17339  *
17340  * Description: Handle a QUEUE FULL condition from the target.  This can
17341  *		occur if the HBA does not handle the queue full condition.
17342  *		(Basically this means third-party HBAs as Sun HBAs will
17343  *		handle the queue full condition.)  Note that if there are
17344  *		some commands already in the transport, then the queue full
17345  *		has occurred because the queue for this nexus is actually
17346  *		full. If there are no commands in the transport, then the
17347  *		queue full is resulting from some other initiator or lun
17348  *		consuming all the resources at the target.
17349  *
17350  *     Context: May be called from interrupt context
17351  */
17352 
17353 static void
17354 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
17355 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17356 {
17357 	ASSERT(un != NULL);
17358 	ASSERT(mutex_owned(SD_MUTEX(un)));
17359 	ASSERT(bp != NULL);
17360 	ASSERT(xp != NULL);
17361 	ASSERT(pktp != NULL);
17362 
17363 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17364 	    "sd_pkt_status_qfull: entry\n");
17365 
17366 	/*
17367 	 * Just lower the QFULL throttle and retry the command.  Note that
17368 	 * we do not limit the number of retries here.
17369 	 */
17370 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
17371 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
17372 	    SD_RESTART_TIMEOUT, NULL);
17373 
17374 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17375 	    "sd_pkt_status_qfull: exit\n");
17376 }
17377 
17378 
17379 /*
17380  *    Function: sd_reset_target
17381  *
17382  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
17383  *		RESET_TARGET, or RESET_ALL.
17384  *
17385  *     Context: May be called under interrupt context.
17386  */
17387 
17388 static void
17389 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
17390 {
17391 	int rval = 0;
17392 
17393 	ASSERT(un != NULL);
17394 	ASSERT(mutex_owned(SD_MUTEX(un)));
17395 	ASSERT(pktp != NULL);
17396 
17397 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
17398 
17399 	/*
17400 	 * No need to reset if the transport layer has already done so.
17401 	 */
17402 	if ((pktp->pkt_statistics &
17403 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
17404 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17405 		    "sd_reset_target: no reset\n");
17406 		return;
17407 	}
17408 
17409 	mutex_exit(SD_MUTEX(un));
17410 
17411 	if (un->un_f_allow_bus_device_reset == TRUE) {
17412 		if (un->un_f_lun_reset_enabled == TRUE) {
17413 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17414 			    "sd_reset_target: RESET_LUN\n");
17415 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
17416 		}
17417 		if (rval == 0) {
17418 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17419 			    "sd_reset_target: RESET_TARGET\n");
17420 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
17421 		}
17422 	}
17423 
17424 	if (rval == 0) {
17425 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17426 		    "sd_reset_target: RESET_ALL\n");
17427 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
17428 	}
17429 
17430 	mutex_enter(SD_MUTEX(un));
17431 
17432 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
17433 }
17434 
17435 
17436 /*
17437  *    Function: sd_media_change_task
17438  *
17439  * Description: Recovery action for CDROM to become available.
17440  *
17441  *     Context: Executes in a taskq() thread context
17442  */
17443 
17444 static void
17445 sd_media_change_task(void *arg)
17446 {
17447 	struct	scsi_pkt	*pktp = arg;
17448 	struct	sd_lun		*un;
17449 	struct	buf		*bp;
17450 	struct	sd_xbuf		*xp;
17451 	int	err		= 0;
17452 	int	retry_count	= 0;
17453 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
17454 	struct	sd_sense_info	si;
17455 
17456 	ASSERT(pktp != NULL);
17457 	bp = (struct buf *)pktp->pkt_private;
17458 	ASSERT(bp != NULL);
17459 	xp = SD_GET_XBUF(bp);
17460 	ASSERT(xp != NULL);
17461 	un = SD_GET_UN(bp);
17462 	ASSERT(un != NULL);
17463 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17464 	ASSERT(un->un_f_monitor_media_state);
17465 
17466 	si.ssi_severity = SCSI_ERR_INFO;
17467 	si.ssi_pfa_flag = FALSE;
17468 
17469 	/*
17470 	 * When a reset is issued on a CDROM, it takes a long time to
17471 	 * recover. First few attempts to read capacity and other things
17472 	 * related to handling unit attention fail (with a ASC 0x4 and
17473 	 * ASCQ 0x1). In that case we want to do enough retries and we want
17474 	 * to limit the retries in other cases of genuine failures like
17475 	 * no media in drive.
17476 	 */
17477 	while (retry_count++ < retry_limit) {
17478 		if ((err = sd_handle_mchange(un)) == 0) {
17479 			break;
17480 		}
17481 		if (err == EAGAIN) {
17482 			retry_limit = SD_UNIT_ATTENTION_RETRY;
17483 		}
17484 		/* Sleep for 0.5 sec. & try again */
17485 		delay(drv_usectohz(500000));
17486 	}
17487 
17488 	/*
17489 	 * Dispatch (retry or fail) the original command here,
17490 	 * along with appropriate console messages....
17491 	 *
17492 	 * Must grab the mutex before calling sd_retry_command,
17493 	 * sd_print_sense_msg and sd_return_failed_command.
17494 	 */
17495 	mutex_enter(SD_MUTEX(un));
17496 	if (err != SD_CMD_SUCCESS) {
17497 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17498 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
17499 		si.ssi_severity = SCSI_ERR_FATAL;
17500 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17501 		sd_return_failed_command(un, bp, EIO);
17502 	} else {
17503 		sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
17504 		    &si, EIO, (clock_t)0, NULL);
17505 	}
17506 	mutex_exit(SD_MUTEX(un));
17507 }
17508 
17509 
17510 
17511 /*
17512  *    Function: sd_handle_mchange
17513  *
17514  * Description: Perform geometry validation & other recovery when CDROM
17515  *		has been removed from drive.
17516  *
17517  * Return Code: 0 for success
17518  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
17519  *		sd_send_scsi_READ_CAPACITY()
17520  *
17521  *     Context: Executes in a taskq() thread context
17522  */
17523 
17524 static int
17525 sd_handle_mchange(struct sd_lun *un)
17526 {
17527 	uint64_t	capacity;
17528 	uint32_t	lbasize;
17529 	int		rval;
17530 
17531 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17532 	ASSERT(un->un_f_monitor_media_state);
17533 
17534 	if ((rval = sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
17535 	    SD_PATH_DIRECT_PRIORITY)) != 0) {
17536 		return (rval);
17537 	}
17538 
17539 	mutex_enter(SD_MUTEX(un));
17540 	sd_update_block_info(un, lbasize, capacity);
17541 
17542 	if (un->un_errstats != NULL) {
17543 		struct	sd_errstats *stp =
17544 		    (struct sd_errstats *)un->un_errstats->ks_data;
17545 		stp->sd_capacity.value.ui64 = (uint64_t)
17546 		    ((uint64_t)un->un_blockcount *
17547 		    (uint64_t)un->un_tgt_blocksize);
17548 	}
17549 
17550 
17551 	/*
17552 	 * Check if the media in the device is writable or not
17553 	 */
17554 	if (ISCD(un))
17555 		sd_check_for_writable_cd(un, SD_PATH_DIRECT_PRIORITY);
17556 
17557 	/*
17558 	 * Note: Maybe let the strategy/partitioning chain worry about getting
17559 	 * valid geometry.
17560 	 */
17561 	mutex_exit(SD_MUTEX(un));
17562 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
17563 
17564 
17565 	if (cmlb_validate(un->un_cmlbhandle, 0,
17566 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
17567 		return (EIO);
17568 	} else {
17569 		if (un->un_f_pkstats_enabled) {
17570 			sd_set_pstats(un);
17571 			SD_TRACE(SD_LOG_IO_PARTITION, un,
17572 			    "sd_handle_mchange: un:0x%p pstats created and "
17573 			    "set\n", un);
17574 		}
17575 	}
17576 
17577 
17578 	/*
17579 	 * Try to lock the door
17580 	 */
17581 	return (sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
17582 	    SD_PATH_DIRECT_PRIORITY));
17583 }
17584 
17585 
17586 /*
17587  *    Function: sd_send_scsi_DOORLOCK
17588  *
17589  * Description: Issue the scsi DOOR LOCK command
17590  *
17591  *   Arguments: un    - pointer to driver soft state (unit) structure for
17592  *			this target.
17593  *		flag  - SD_REMOVAL_ALLOW
17594  *			SD_REMOVAL_PREVENT
17595  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17596  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17597  *			to use the USCSI "direct" chain and bypass the normal
17598  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17599  *			command is issued as part of an error recovery action.
17600  *
17601  * Return Code: 0   - Success
17602  *		errno return code from sd_send_scsi_cmd()
17603  *
17604  *     Context: Can sleep.
17605  */
17606 
17607 static int
17608 sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag)
17609 {
17610 	union scsi_cdb		cdb;
17611 	struct uscsi_cmd	ucmd_buf;
17612 	struct scsi_extended_sense	sense_buf;
17613 	int			status;
17614 
17615 	ASSERT(un != NULL);
17616 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17617 
17618 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
17619 
17620 	/* already determined doorlock is not supported, fake success */
17621 	if (un->un_f_doorlock_supported == FALSE) {
17622 		return (0);
17623 	}
17624 
17625 	/*
17626 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
17627 	 * ignore the command so we can complete the eject
17628 	 * operation.
17629 	 */
17630 	if (flag == SD_REMOVAL_PREVENT) {
17631 		mutex_enter(SD_MUTEX(un));
17632 		if (un->un_f_ejecting == TRUE) {
17633 			mutex_exit(SD_MUTEX(un));
17634 			return (EAGAIN);
17635 		}
17636 		mutex_exit(SD_MUTEX(un));
17637 	}
17638 
17639 	bzero(&cdb, sizeof (cdb));
17640 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17641 
17642 	cdb.scc_cmd = SCMD_DOORLOCK;
17643 	cdb.cdb_opaque[4] = (uchar_t)flag;
17644 
17645 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17646 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
17647 	ucmd_buf.uscsi_bufaddr	= NULL;
17648 	ucmd_buf.uscsi_buflen	= 0;
17649 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17650 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17651 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
17652 	ucmd_buf.uscsi_timeout	= 15;
17653 
17654 	SD_TRACE(SD_LOG_IO, un,
17655 	    "sd_send_scsi_DOORLOCK: returning sd_send_scsi_cmd()\n");
17656 
17657 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17658 	    UIO_SYSSPACE, path_flag);
17659 
17660 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
17661 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17662 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
17663 		/* fake success and skip subsequent doorlock commands */
17664 		un->un_f_doorlock_supported = FALSE;
17665 		return (0);
17666 	}
17667 
17668 	return (status);
17669 }
17670 
17671 /*
17672  *    Function: sd_send_scsi_READ_CAPACITY
17673  *
17674  * Description: This routine uses the scsi READ CAPACITY command to determine
17675  *		the device capacity in number of blocks and the device native
17676  *		block size. If this function returns a failure, then the
17677  *		values in *capp and *lbap are undefined.  If the capacity
17678  *		returned is 0xffffffff then the lun is too large for a
17679  *		normal READ CAPACITY command and the results of a
17680  *		READ CAPACITY 16 will be used instead.
17681  *
17682  *   Arguments: un   - ptr to soft state struct for the target
17683  *		capp - ptr to unsigned 64-bit variable to receive the
17684  *			capacity value from the command.
17685  *		lbap - ptr to unsigned 32-bit varaible to receive the
17686  *			block size value from the command
17687  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17688  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17689  *			to use the USCSI "direct" chain and bypass the normal
17690  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17691  *			command is issued as part of an error recovery action.
17692  *
17693  * Return Code: 0   - Success
17694  *		EIO - IO error
17695  *		EACCES - Reservation conflict detected
17696  *		EAGAIN - Device is becoming ready
17697  *		errno return code from sd_send_scsi_cmd()
17698  *
17699  *     Context: Can sleep.  Blocks until command completes.
17700  */
17701 
17702 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
17703 
17704 static int
17705 sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp, uint32_t *lbap,
17706 	int path_flag)
17707 {
17708 	struct	scsi_extended_sense	sense_buf;
17709 	struct	uscsi_cmd	ucmd_buf;
17710 	union	scsi_cdb	cdb;
17711 	uint32_t		*capacity_buf;
17712 	uint64_t		capacity;
17713 	uint32_t		lbasize;
17714 	int			status;
17715 
17716 	ASSERT(un != NULL);
17717 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17718 	ASSERT(capp != NULL);
17719 	ASSERT(lbap != NULL);
17720 
17721 	SD_TRACE(SD_LOG_IO, un,
17722 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
17723 
17724 	/*
17725 	 * First send a READ_CAPACITY command to the target.
17726 	 * (This command is mandatory under SCSI-2.)
17727 	 *
17728 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
17729 	 * Medium Indicator bit is cleared.  The address field must be
17730 	 * zero if the PMI bit is zero.
17731 	 */
17732 	bzero(&cdb, sizeof (cdb));
17733 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17734 
17735 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
17736 
17737 	cdb.scc_cmd = SCMD_READ_CAPACITY;
17738 
17739 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17740 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
17741 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
17742 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
17743 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17744 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17745 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
17746 	ucmd_buf.uscsi_timeout	= 60;
17747 
17748 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17749 	    UIO_SYSSPACE, path_flag);
17750 
17751 	switch (status) {
17752 	case 0:
17753 		/* Return failure if we did not get valid capacity data. */
17754 		if (ucmd_buf.uscsi_resid != 0) {
17755 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17756 			return (EIO);
17757 		}
17758 
17759 		/*
17760 		 * Read capacity and block size from the READ CAPACITY 10 data.
17761 		 * This data may be adjusted later due to device specific
17762 		 * issues.
17763 		 *
17764 		 * According to the SCSI spec, the READ CAPACITY 10
17765 		 * command returns the following:
17766 		 *
17767 		 *  bytes 0-3: Maximum logical block address available.
17768 		 *		(MSB in byte:0 & LSB in byte:3)
17769 		 *
17770 		 *  bytes 4-7: Block length in bytes
17771 		 *		(MSB in byte:4 & LSB in byte:7)
17772 		 *
17773 		 */
17774 		capacity = BE_32(capacity_buf[0]);
17775 		lbasize = BE_32(capacity_buf[1]);
17776 
17777 		/*
17778 		 * Done with capacity_buf
17779 		 */
17780 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17781 
17782 		/*
17783 		 * if the reported capacity is set to all 0xf's, then
17784 		 * this disk is too large and requires SBC-2 commands.
17785 		 * Reissue the request using READ CAPACITY 16.
17786 		 */
17787 		if (capacity == 0xffffffff) {
17788 			status = sd_send_scsi_READ_CAPACITY_16(un, &capacity,
17789 			    &lbasize, path_flag);
17790 			if (status != 0) {
17791 				return (status);
17792 			}
17793 		}
17794 		break;	/* Success! */
17795 	case EIO:
17796 		switch (ucmd_buf.uscsi_status) {
17797 		case STATUS_RESERVATION_CONFLICT:
17798 			status = EACCES;
17799 			break;
17800 		case STATUS_CHECK:
17801 			/*
17802 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
17803 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
17804 			 */
17805 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17806 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
17807 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
17808 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17809 				return (EAGAIN);
17810 			}
17811 			break;
17812 		default:
17813 			break;
17814 		}
17815 		/* FALLTHRU */
17816 	default:
17817 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17818 		return (status);
17819 	}
17820 
17821 	/*
17822 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
17823 	 * (2352 and 0 are common) so for these devices always force the value
17824 	 * to 2048 as required by the ATAPI specs.
17825 	 */
17826 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
17827 		lbasize = 2048;
17828 	}
17829 
17830 	/*
17831 	 * Get the maximum LBA value from the READ CAPACITY data.
17832 	 * Here we assume that the Partial Medium Indicator (PMI) bit
17833 	 * was cleared when issuing the command. This means that the LBA
17834 	 * returned from the device is the LBA of the last logical block
17835 	 * on the logical unit.  The actual logical block count will be
17836 	 * this value plus one.
17837 	 *
17838 	 * Currently the capacity is saved in terms of un->un_sys_blocksize,
17839 	 * so scale the capacity value to reflect this.
17840 	 */
17841 	capacity = (capacity + 1) * (lbasize / un->un_sys_blocksize);
17842 
17843 	/*
17844 	 * Copy the values from the READ CAPACITY command into the space
17845 	 * provided by the caller.
17846 	 */
17847 	*capp = capacity;
17848 	*lbap = lbasize;
17849 
17850 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
17851 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
17852 
17853 	/*
17854 	 * Both the lbasize and capacity from the device must be nonzero,
17855 	 * otherwise we assume that the values are not valid and return
17856 	 * failure to the caller. (4203735)
17857 	 */
17858 	if ((capacity == 0) || (lbasize == 0)) {
17859 		return (EIO);
17860 	}
17861 
17862 	return (0);
17863 }
17864 
17865 /*
17866  *    Function: sd_send_scsi_READ_CAPACITY_16
17867  *
17868  * Description: This routine uses the scsi READ CAPACITY 16 command to
17869  *		determine the device capacity in number of blocks and the
17870  *		device native block size.  If this function returns a failure,
17871  *		then the values in *capp and *lbap are undefined.
17872  *		This routine should always be called by
17873  *		sd_send_scsi_READ_CAPACITY which will appy any device
17874  *		specific adjustments to capacity and lbasize.
17875  *
17876  *   Arguments: un   - ptr to soft state struct for the target
17877  *		capp - ptr to unsigned 64-bit variable to receive the
17878  *			capacity value from the command.
17879  *		lbap - ptr to unsigned 32-bit varaible to receive the
17880  *			block size value from the command
17881  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17882  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17883  *			to use the USCSI "direct" chain and bypass the normal
17884  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
17885  *			this command is issued as part of an error recovery
17886  *			action.
17887  *
17888  * Return Code: 0   - Success
17889  *		EIO - IO error
17890  *		EACCES - Reservation conflict detected
17891  *		EAGAIN - Device is becoming ready
17892  *		errno return code from sd_send_scsi_cmd()
17893  *
17894  *     Context: Can sleep.  Blocks until command completes.
17895  */
17896 
17897 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
17898 
17899 static int
17900 sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
17901 	uint32_t *lbap, int path_flag)
17902 {
17903 	struct	scsi_extended_sense	sense_buf;
17904 	struct	uscsi_cmd	ucmd_buf;
17905 	union	scsi_cdb	cdb;
17906 	uint64_t		*capacity16_buf;
17907 	uint64_t		capacity;
17908 	uint32_t		lbasize;
17909 	int			status;
17910 
17911 	ASSERT(un != NULL);
17912 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17913 	ASSERT(capp != NULL);
17914 	ASSERT(lbap != NULL);
17915 
17916 	SD_TRACE(SD_LOG_IO, un,
17917 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
17918 
17919 	/*
17920 	 * First send a READ_CAPACITY_16 command to the target.
17921 	 *
17922 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
17923 	 * Medium Indicator bit is cleared.  The address field must be
17924 	 * zero if the PMI bit is zero.
17925 	 */
17926 	bzero(&cdb, sizeof (cdb));
17927 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17928 
17929 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
17930 
17931 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17932 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
17933 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
17934 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
17935 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17936 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17937 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
17938 	ucmd_buf.uscsi_timeout	= 60;
17939 
17940 	/*
17941 	 * Read Capacity (16) is a Service Action In command.  One
17942 	 * command byte (0x9E) is overloaded for multiple operations,
17943 	 * with the second CDB byte specifying the desired operation
17944 	 */
17945 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
17946 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
17947 
17948 	/*
17949 	 * Fill in allocation length field
17950 	 */
17951 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
17952 
17953 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17954 	    UIO_SYSSPACE, path_flag);
17955 
17956 	switch (status) {
17957 	case 0:
17958 		/* Return failure if we did not get valid capacity data. */
17959 		if (ucmd_buf.uscsi_resid > 20) {
17960 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17961 			return (EIO);
17962 		}
17963 
17964 		/*
17965 		 * Read capacity and block size from the READ CAPACITY 10 data.
17966 		 * This data may be adjusted later due to device specific
17967 		 * issues.
17968 		 *
17969 		 * According to the SCSI spec, the READ CAPACITY 10
17970 		 * command returns the following:
17971 		 *
17972 		 *  bytes 0-7: Maximum logical block address available.
17973 		 *		(MSB in byte:0 & LSB in byte:7)
17974 		 *
17975 		 *  bytes 8-11: Block length in bytes
17976 		 *		(MSB in byte:8 & LSB in byte:11)
17977 		 *
17978 		 */
17979 		capacity = BE_64(capacity16_buf[0]);
17980 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
17981 
17982 		/*
17983 		 * Done with capacity16_buf
17984 		 */
17985 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17986 
17987 		/*
17988 		 * if the reported capacity is set to all 0xf's, then
17989 		 * this disk is too large.  This could only happen with
17990 		 * a device that supports LBAs larger than 64 bits which
17991 		 * are not defined by any current T10 standards.
17992 		 */
17993 		if (capacity == 0xffffffffffffffff) {
17994 			return (EIO);
17995 		}
17996 		break;	/* Success! */
17997 	case EIO:
17998 		switch (ucmd_buf.uscsi_status) {
17999 		case STATUS_RESERVATION_CONFLICT:
18000 			status = EACCES;
18001 			break;
18002 		case STATUS_CHECK:
18003 			/*
18004 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
18005 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
18006 			 */
18007 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18008 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
18009 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
18010 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
18011 				return (EAGAIN);
18012 			}
18013 			break;
18014 		default:
18015 			break;
18016 		}
18017 		/* FALLTHRU */
18018 	default:
18019 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
18020 		return (status);
18021 	}
18022 
18023 	*capp = capacity;
18024 	*lbap = lbasize;
18025 
18026 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
18027 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
18028 
18029 	return (0);
18030 }
18031 
18032 
18033 /*
18034  *    Function: sd_send_scsi_START_STOP_UNIT
18035  *
18036  * Description: Issue a scsi START STOP UNIT command to the target.
18037  *
18038  *   Arguments: un    - pointer to driver soft state (unit) structure for
18039  *			this target.
18040  *		flag  - SD_TARGET_START
18041  *			SD_TARGET_STOP
18042  *			SD_TARGET_EJECT
18043  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
18044  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
18045  *			to use the USCSI "direct" chain and bypass the normal
18046  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
18047  *			command is issued as part of an error recovery action.
18048  *
18049  * Return Code: 0   - Success
18050  *		EIO - IO error
18051  *		EACCES - Reservation conflict detected
18052  *		ENXIO  - Not Ready, medium not present
18053  *		errno return code from sd_send_scsi_cmd()
18054  *
18055  *     Context: Can sleep.
18056  */
18057 
18058 static int
18059 sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag, int path_flag)
18060 {
18061 	struct	scsi_extended_sense	sense_buf;
18062 	union scsi_cdb		cdb;
18063 	struct uscsi_cmd	ucmd_buf;
18064 	int			status;
18065 
18066 	ASSERT(un != NULL);
18067 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18068 
18069 	SD_TRACE(SD_LOG_IO, un,
18070 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
18071 
18072 	if (un->un_f_check_start_stop &&
18073 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
18074 	    (un->un_f_start_stop_supported != TRUE)) {
18075 		return (0);
18076 	}
18077 
18078 	/*
18079 	 * If we are performing an eject operation and
18080 	 * we receive any command other than SD_TARGET_EJECT
18081 	 * we should immediately return.
18082 	 */
18083 	if (flag != SD_TARGET_EJECT) {
18084 		mutex_enter(SD_MUTEX(un));
18085 		if (un->un_f_ejecting == TRUE) {
18086 			mutex_exit(SD_MUTEX(un));
18087 			return (EAGAIN);
18088 		}
18089 		mutex_exit(SD_MUTEX(un));
18090 	}
18091 
18092 	bzero(&cdb, sizeof (cdb));
18093 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18094 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18095 
18096 	cdb.scc_cmd = SCMD_START_STOP;
18097 	cdb.cdb_opaque[4] = (uchar_t)flag;
18098 
18099 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18100 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18101 	ucmd_buf.uscsi_bufaddr	= NULL;
18102 	ucmd_buf.uscsi_buflen	= 0;
18103 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18104 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18105 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18106 	ucmd_buf.uscsi_timeout	= 200;
18107 
18108 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18109 	    UIO_SYSSPACE, path_flag);
18110 
18111 	switch (status) {
18112 	case 0:
18113 		break;	/* Success! */
18114 	case EIO:
18115 		switch (ucmd_buf.uscsi_status) {
18116 		case STATUS_RESERVATION_CONFLICT:
18117 			status = EACCES;
18118 			break;
18119 		case STATUS_CHECK:
18120 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
18121 				switch (scsi_sense_key(
18122 				    (uint8_t *)&sense_buf)) {
18123 				case KEY_ILLEGAL_REQUEST:
18124 					status = ENOTSUP;
18125 					break;
18126 				case KEY_NOT_READY:
18127 					if (scsi_sense_asc(
18128 					    (uint8_t *)&sense_buf)
18129 					    == 0x3A) {
18130 						status = ENXIO;
18131 					}
18132 					break;
18133 				default:
18134 					break;
18135 				}
18136 			}
18137 			break;
18138 		default:
18139 			break;
18140 		}
18141 		break;
18142 	default:
18143 		break;
18144 	}
18145 
18146 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
18147 
18148 	return (status);
18149 }
18150 
18151 
18152 /*
18153  *    Function: sd_start_stop_unit_callback
18154  *
18155  * Description: timeout(9F) callback to begin recovery process for a
18156  *		device that has spun down.
18157  *
18158  *   Arguments: arg - pointer to associated softstate struct.
18159  *
18160  *     Context: Executes in a timeout(9F) thread context
18161  */
18162 
18163 static void
18164 sd_start_stop_unit_callback(void *arg)
18165 {
18166 	struct sd_lun	*un = arg;
18167 	ASSERT(un != NULL);
18168 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18169 
18170 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
18171 
18172 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
18173 }
18174 
18175 
18176 /*
18177  *    Function: sd_start_stop_unit_task
18178  *
18179  * Description: Recovery procedure when a drive is spun down.
18180  *
18181  *   Arguments: arg - pointer to associated softstate struct.
18182  *
18183  *     Context: Executes in a taskq() thread context
18184  */
18185 
18186 static void
18187 sd_start_stop_unit_task(void *arg)
18188 {
18189 	struct sd_lun	*un = arg;
18190 
18191 	ASSERT(un != NULL);
18192 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18193 
18194 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
18195 
18196 	/*
18197 	 * Some unformatted drives report not ready error, no need to
18198 	 * restart if format has been initiated.
18199 	 */
18200 	mutex_enter(SD_MUTEX(un));
18201 	if (un->un_f_format_in_progress == TRUE) {
18202 		mutex_exit(SD_MUTEX(un));
18203 		return;
18204 	}
18205 	mutex_exit(SD_MUTEX(un));
18206 
18207 	/*
18208 	 * When a START STOP command is issued from here, it is part of a
18209 	 * failure recovery operation and must be issued before any other
18210 	 * commands, including any pending retries. Thus it must be sent
18211 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
18212 	 * succeeds or not, we will start I/O after the attempt.
18213 	 */
18214 	(void) sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
18215 	    SD_PATH_DIRECT_PRIORITY);
18216 
18217 	/*
18218 	 * The above call blocks until the START_STOP_UNIT command completes.
18219 	 * Now that it has completed, we must re-try the original IO that
18220 	 * received the NOT READY condition in the first place. There are
18221 	 * three possible conditions here:
18222 	 *
18223 	 *  (1) The original IO is on un_retry_bp.
18224 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
18225 	 *	is NULL.
18226 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
18227 	 *	points to some other, unrelated bp.
18228 	 *
18229 	 * For each case, we must call sd_start_cmds() with un_retry_bp
18230 	 * as the argument. If un_retry_bp is NULL, this will initiate
18231 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
18232 	 * then this will process the bp on un_retry_bp. That may or may not
18233 	 * be the original IO, but that does not matter: the important thing
18234 	 * is to keep the IO processing going at this point.
18235 	 *
18236 	 * Note: This is a very specific error recovery sequence associated
18237 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
18238 	 * serialize the I/O with completion of the spin-up.
18239 	 */
18240 	mutex_enter(SD_MUTEX(un));
18241 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18242 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
18243 	    un, un->un_retry_bp);
18244 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
18245 	sd_start_cmds(un, un->un_retry_bp);
18246 	mutex_exit(SD_MUTEX(un));
18247 
18248 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
18249 }
18250 
18251 
18252 /*
18253  *    Function: sd_send_scsi_INQUIRY
18254  *
18255  * Description: Issue the scsi INQUIRY command.
18256  *
18257  *   Arguments: un
18258  *		bufaddr
18259  *		buflen
18260  *		evpd
18261  *		page_code
18262  *		page_length
18263  *
18264  * Return Code: 0   - Success
18265  *		errno return code from sd_send_scsi_cmd()
18266  *
18267  *     Context: Can sleep. Does not return until command is completed.
18268  */
18269 
18270 static int
18271 sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr, size_t buflen,
18272 	uchar_t evpd, uchar_t page_code, size_t *residp)
18273 {
18274 	union scsi_cdb		cdb;
18275 	struct uscsi_cmd	ucmd_buf;
18276 	int			status;
18277 
18278 	ASSERT(un != NULL);
18279 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18280 	ASSERT(bufaddr != NULL);
18281 
18282 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
18283 
18284 	bzero(&cdb, sizeof (cdb));
18285 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18286 	bzero(bufaddr, buflen);
18287 
18288 	cdb.scc_cmd = SCMD_INQUIRY;
18289 	cdb.cdb_opaque[1] = evpd;
18290 	cdb.cdb_opaque[2] = page_code;
18291 	FORMG0COUNT(&cdb, buflen);
18292 
18293 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18294 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18295 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
18296 	ucmd_buf.uscsi_buflen	= buflen;
18297 	ucmd_buf.uscsi_rqbuf	= NULL;
18298 	ucmd_buf.uscsi_rqlen	= 0;
18299 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
18300 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
18301 
18302 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18303 	    UIO_SYSSPACE, SD_PATH_DIRECT);
18304 
18305 	if ((status == 0) && (residp != NULL)) {
18306 		*residp = ucmd_buf.uscsi_resid;
18307 	}
18308 
18309 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
18310 
18311 	return (status);
18312 }
18313 
18314 
18315 /*
18316  *    Function: sd_send_scsi_TEST_UNIT_READY
18317  *
18318  * Description: Issue the scsi TEST UNIT READY command.
18319  *		This routine can be told to set the flag USCSI_DIAGNOSE to
18320  *		prevent retrying failed commands. Use this when the intent
18321  *		is either to check for device readiness, to clear a Unit
18322  *		Attention, or to clear any outstanding sense data.
18323  *		However under specific conditions the expected behavior
18324  *		is for retries to bring a device ready, so use the flag
18325  *		with caution.
18326  *
18327  *   Arguments: un
18328  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
18329  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
18330  *			0: dont check for media present, do retries on cmd.
18331  *
18332  * Return Code: 0   - Success
18333  *		EIO - IO error
18334  *		EACCES - Reservation conflict detected
18335  *		ENXIO  - Not Ready, medium not present
18336  *		errno return code from sd_send_scsi_cmd()
18337  *
18338  *     Context: Can sleep. Does not return until command is completed.
18339  */
18340 
18341 static int
18342 sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag)
18343 {
18344 	struct	scsi_extended_sense	sense_buf;
18345 	union scsi_cdb		cdb;
18346 	struct uscsi_cmd	ucmd_buf;
18347 	int			status;
18348 
18349 	ASSERT(un != NULL);
18350 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18351 
18352 	SD_TRACE(SD_LOG_IO, un,
18353 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
18354 
18355 	/*
18356 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
18357 	 * timeouts when they receive a TUR and the queue is not empty. Check
18358 	 * the configuration flag set during attach (indicating the drive has
18359 	 * this firmware bug) and un_ncmds_in_transport before issuing the
18360 	 * TUR. If there are
18361 	 * pending commands return success, this is a bit arbitrary but is ok
18362 	 * for non-removables (i.e. the eliteI disks) and non-clustering
18363 	 * configurations.
18364 	 */
18365 	if (un->un_f_cfg_tur_check == TRUE) {
18366 		mutex_enter(SD_MUTEX(un));
18367 		if (un->un_ncmds_in_transport != 0) {
18368 			mutex_exit(SD_MUTEX(un));
18369 			return (0);
18370 		}
18371 		mutex_exit(SD_MUTEX(un));
18372 	}
18373 
18374 	bzero(&cdb, sizeof (cdb));
18375 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18376 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18377 
18378 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
18379 
18380 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18381 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18382 	ucmd_buf.uscsi_bufaddr	= NULL;
18383 	ucmd_buf.uscsi_buflen	= 0;
18384 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18385 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18386 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18387 
18388 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
18389 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
18390 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
18391 	}
18392 	ucmd_buf.uscsi_timeout	= 60;
18393 
18394 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18395 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
18396 	    SD_PATH_STANDARD));
18397 
18398 	switch (status) {
18399 	case 0:
18400 		break;	/* Success! */
18401 	case EIO:
18402 		switch (ucmd_buf.uscsi_status) {
18403 		case STATUS_RESERVATION_CONFLICT:
18404 			status = EACCES;
18405 			break;
18406 		case STATUS_CHECK:
18407 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
18408 				break;
18409 			}
18410 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18411 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18412 			    KEY_NOT_READY) &&
18413 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
18414 				status = ENXIO;
18415 			}
18416 			break;
18417 		default:
18418 			break;
18419 		}
18420 		break;
18421 	default:
18422 		break;
18423 	}
18424 
18425 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
18426 
18427 	return (status);
18428 }
18429 
18430 
18431 /*
18432  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
18433  *
18434  * Description: Issue the scsi PERSISTENT RESERVE IN command.
18435  *
18436  *   Arguments: un
18437  *
18438  * Return Code: 0   - Success
18439  *		EACCES
18440  *		ENOTSUP
18441  *		errno return code from sd_send_scsi_cmd()
18442  *
18443  *     Context: Can sleep. Does not return until command is completed.
18444  */
18445 
18446 static int
18447 sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un, uchar_t  usr_cmd,
18448 	uint16_t data_len, uchar_t *data_bufp)
18449 {
18450 	struct scsi_extended_sense	sense_buf;
18451 	union scsi_cdb		cdb;
18452 	struct uscsi_cmd	ucmd_buf;
18453 	int			status;
18454 	int			no_caller_buf = FALSE;
18455 
18456 	ASSERT(un != NULL);
18457 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18458 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
18459 
18460 	SD_TRACE(SD_LOG_IO, un,
18461 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
18462 
18463 	bzero(&cdb, sizeof (cdb));
18464 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18465 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18466 	if (data_bufp == NULL) {
18467 		/* Allocate a default buf if the caller did not give one */
18468 		ASSERT(data_len == 0);
18469 		data_len  = MHIOC_RESV_KEY_SIZE;
18470 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
18471 		no_caller_buf = TRUE;
18472 	}
18473 
18474 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
18475 	cdb.cdb_opaque[1] = usr_cmd;
18476 	FORMG1COUNT(&cdb, data_len);
18477 
18478 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18479 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18480 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
18481 	ucmd_buf.uscsi_buflen	= data_len;
18482 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18483 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18484 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
18485 	ucmd_buf.uscsi_timeout	= 60;
18486 
18487 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18488 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18489 
18490 	switch (status) {
18491 	case 0:
18492 		break;	/* Success! */
18493 	case EIO:
18494 		switch (ucmd_buf.uscsi_status) {
18495 		case STATUS_RESERVATION_CONFLICT:
18496 			status = EACCES;
18497 			break;
18498 		case STATUS_CHECK:
18499 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18500 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18501 			    KEY_ILLEGAL_REQUEST)) {
18502 				status = ENOTSUP;
18503 			}
18504 			break;
18505 		default:
18506 			break;
18507 		}
18508 		break;
18509 	default:
18510 		break;
18511 	}
18512 
18513 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
18514 
18515 	if (no_caller_buf == TRUE) {
18516 		kmem_free(data_bufp, data_len);
18517 	}
18518 
18519 	return (status);
18520 }
18521 
18522 
18523 /*
18524  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
18525  *
18526  * Description: This routine is the driver entry point for handling CD-ROM
18527  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
18528  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
18529  *		device.
18530  *
18531  *   Arguments: un  -   Pointer to soft state struct for the target.
18532  *		usr_cmd SCSI-3 reservation facility command (one of
18533  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
18534  *			SD_SCSI3_PREEMPTANDABORT)
18535  *		usr_bufp - user provided pointer register, reserve descriptor or
18536  *			preempt and abort structure (mhioc_register_t,
18537  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
18538  *
18539  * Return Code: 0   - Success
18540  *		EACCES
18541  *		ENOTSUP
18542  *		errno return code from sd_send_scsi_cmd()
18543  *
18544  *     Context: Can sleep. Does not return until command is completed.
18545  */
18546 
18547 static int
18548 sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un, uchar_t usr_cmd,
18549 	uchar_t	*usr_bufp)
18550 {
18551 	struct scsi_extended_sense	sense_buf;
18552 	union scsi_cdb		cdb;
18553 	struct uscsi_cmd	ucmd_buf;
18554 	int			status;
18555 	uchar_t			data_len = sizeof (sd_prout_t);
18556 	sd_prout_t		*prp;
18557 
18558 	ASSERT(un != NULL);
18559 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18560 	ASSERT(data_len == 24);	/* required by scsi spec */
18561 
18562 	SD_TRACE(SD_LOG_IO, un,
18563 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
18564 
18565 	if (usr_bufp == NULL) {
18566 		return (EINVAL);
18567 	}
18568 
18569 	bzero(&cdb, sizeof (cdb));
18570 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18571 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18572 	prp = kmem_zalloc(data_len, KM_SLEEP);
18573 
18574 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
18575 	cdb.cdb_opaque[1] = usr_cmd;
18576 	FORMG1COUNT(&cdb, data_len);
18577 
18578 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18579 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18580 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
18581 	ucmd_buf.uscsi_buflen	= data_len;
18582 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18583 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18584 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
18585 	ucmd_buf.uscsi_timeout	= 60;
18586 
18587 	switch (usr_cmd) {
18588 	case SD_SCSI3_REGISTER: {
18589 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
18590 
18591 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18592 		bcopy(ptr->newkey.key, prp->service_key,
18593 		    MHIOC_RESV_KEY_SIZE);
18594 		prp->aptpl = ptr->aptpl;
18595 		break;
18596 	}
18597 	case SD_SCSI3_RESERVE:
18598 	case SD_SCSI3_RELEASE: {
18599 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
18600 
18601 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18602 		prp->scope_address = BE_32(ptr->scope_specific_addr);
18603 		cdb.cdb_opaque[2] = ptr->type;
18604 		break;
18605 	}
18606 	case SD_SCSI3_PREEMPTANDABORT: {
18607 		mhioc_preemptandabort_t *ptr =
18608 		    (mhioc_preemptandabort_t *)usr_bufp;
18609 
18610 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18611 		bcopy(ptr->victim_key.key, prp->service_key,
18612 		    MHIOC_RESV_KEY_SIZE);
18613 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
18614 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
18615 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
18616 		break;
18617 	}
18618 	case SD_SCSI3_REGISTERANDIGNOREKEY:
18619 	{
18620 		mhioc_registerandignorekey_t *ptr;
18621 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
18622 		bcopy(ptr->newkey.key,
18623 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
18624 		prp->aptpl = ptr->aptpl;
18625 		break;
18626 	}
18627 	default:
18628 		ASSERT(FALSE);
18629 		break;
18630 	}
18631 
18632 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18633 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18634 
18635 	switch (status) {
18636 	case 0:
18637 		break;	/* Success! */
18638 	case EIO:
18639 		switch (ucmd_buf.uscsi_status) {
18640 		case STATUS_RESERVATION_CONFLICT:
18641 			status = EACCES;
18642 			break;
18643 		case STATUS_CHECK:
18644 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18645 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18646 			    KEY_ILLEGAL_REQUEST)) {
18647 				status = ENOTSUP;
18648 			}
18649 			break;
18650 		default:
18651 			break;
18652 		}
18653 		break;
18654 	default:
18655 		break;
18656 	}
18657 
18658 	kmem_free(prp, data_len);
18659 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
18660 	return (status);
18661 }
18662 
18663 
18664 /*
18665  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
18666  *
18667  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
18668  *
18669  *   Arguments: un - pointer to the target's soft state struct
18670  *              dkc - pointer to the callback structure
18671  *
18672  * Return Code: 0 - success
18673  *		errno-type error code
18674  *
18675  *     Context: kernel thread context only.
18676  *
18677  *  _______________________________________________________________
18678  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
18679  * |FLUSH_VOLATILE|              | operation                       |
18680  * |______________|______________|_________________________________|
18681  * | 0            | NULL         | Synchronous flush on both       |
18682  * |              |              | volatile and non-volatile cache |
18683  * |______________|______________|_________________________________|
18684  * | 1            | NULL         | Synchronous flush on volatile   |
18685  * |              |              | cache; disk drivers may suppress|
18686  * |              |              | flush if disk table indicates   |
18687  * |              |              | non-volatile cache              |
18688  * |______________|______________|_________________________________|
18689  * | 0            | !NULL        | Asynchronous flush on both      |
18690  * |              |              | volatile and non-volatile cache;|
18691  * |______________|______________|_________________________________|
18692  * | 1            | !NULL        | Asynchronous flush on volatile  |
18693  * |              |              | cache; disk drivers may suppress|
18694  * |              |              | flush if disk table indicates   |
18695  * |              |              | non-volatile cache              |
18696  * |______________|______________|_________________________________|
18697  *
18698  */
18699 
18700 static int
18701 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
18702 {
18703 	struct sd_uscsi_info	*uip;
18704 	struct uscsi_cmd	*uscmd;
18705 	union scsi_cdb		*cdb;
18706 	struct buf		*bp;
18707 	int			rval = 0;
18708 	int			is_async;
18709 
18710 	SD_TRACE(SD_LOG_IO, un,
18711 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
18712 
18713 	ASSERT(un != NULL);
18714 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18715 
18716 	if (dkc == NULL || dkc->dkc_callback == NULL) {
18717 		is_async = FALSE;
18718 	} else {
18719 		is_async = TRUE;
18720 	}
18721 
18722 	mutex_enter(SD_MUTEX(un));
18723 	/* check whether cache flush should be suppressed */
18724 	if (un->un_f_suppress_cache_flush == TRUE) {
18725 		mutex_exit(SD_MUTEX(un));
18726 		/*
18727 		 * suppress the cache flush if the device is told to do
18728 		 * so by sd.conf or disk table
18729 		 */
18730 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
18731 		    skip the cache flush since suppress_cache_flush is %d!\n",
18732 		    un->un_f_suppress_cache_flush);
18733 
18734 		if (is_async == TRUE) {
18735 			/* invoke callback for asynchronous flush */
18736 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
18737 		}
18738 		return (rval);
18739 	}
18740 	mutex_exit(SD_MUTEX(un));
18741 
18742 	/*
18743 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
18744 	 * set properly
18745 	 */
18746 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
18747 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
18748 
18749 	mutex_enter(SD_MUTEX(un));
18750 	if (dkc != NULL && un->un_f_sync_nv_supported &&
18751 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
18752 		/*
18753 		 * if the device supports SYNC_NV bit, turn on
18754 		 * the SYNC_NV bit to only flush volatile cache
18755 		 */
18756 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
18757 	}
18758 	mutex_exit(SD_MUTEX(un));
18759 
18760 	/*
18761 	 * First get some memory for the uscsi_cmd struct and cdb
18762 	 * and initialize for SYNCHRONIZE_CACHE cmd.
18763 	 */
18764 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
18765 	uscmd->uscsi_cdblen = CDB_GROUP1;
18766 	uscmd->uscsi_cdb = (caddr_t)cdb;
18767 	uscmd->uscsi_bufaddr = NULL;
18768 	uscmd->uscsi_buflen = 0;
18769 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
18770 	uscmd->uscsi_rqlen = SENSE_LENGTH;
18771 	uscmd->uscsi_rqresid = SENSE_LENGTH;
18772 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
18773 	uscmd->uscsi_timeout = sd_io_time;
18774 
18775 	/*
18776 	 * Allocate an sd_uscsi_info struct and fill it with the info
18777 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
18778 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
18779 	 * since we allocate the buf here in this function, we do not
18780 	 * need to preserve the prior contents of b_private.
18781 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
18782 	 */
18783 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
18784 	uip->ui_flags = SD_PATH_DIRECT;
18785 	uip->ui_cmdp  = uscmd;
18786 
18787 	bp = getrbuf(KM_SLEEP);
18788 	bp->b_private = uip;
18789 
18790 	/*
18791 	 * Setup buffer to carry uscsi request.
18792 	 */
18793 	bp->b_flags  = B_BUSY;
18794 	bp->b_bcount = 0;
18795 	bp->b_blkno  = 0;
18796 
18797 	if (is_async == TRUE) {
18798 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
18799 		uip->ui_dkc = *dkc;
18800 	}
18801 
18802 	bp->b_edev = SD_GET_DEV(un);
18803 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
18804 
18805 	(void) sd_uscsi_strategy(bp);
18806 
18807 	/*
18808 	 * If synchronous request, wait for completion
18809 	 * If async just return and let b_iodone callback
18810 	 * cleanup.
18811 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
18812 	 * but it was also incremented in sd_uscsi_strategy(), so
18813 	 * we should be ok.
18814 	 */
18815 	if (is_async == FALSE) {
18816 		(void) biowait(bp);
18817 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
18818 	}
18819 
18820 	return (rval);
18821 }
18822 
18823 
18824 static int
18825 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
18826 {
18827 	struct sd_uscsi_info *uip;
18828 	struct uscsi_cmd *uscmd;
18829 	uint8_t *sense_buf;
18830 	struct sd_lun *un;
18831 	int status;
18832 	union scsi_cdb *cdb;
18833 
18834 	uip = (struct sd_uscsi_info *)(bp->b_private);
18835 	ASSERT(uip != NULL);
18836 
18837 	uscmd = uip->ui_cmdp;
18838 	ASSERT(uscmd != NULL);
18839 
18840 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
18841 	ASSERT(sense_buf != NULL);
18842 
18843 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
18844 	ASSERT(un != NULL);
18845 
18846 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
18847 
18848 	status = geterror(bp);
18849 	switch (status) {
18850 	case 0:
18851 		break;	/* Success! */
18852 	case EIO:
18853 		switch (uscmd->uscsi_status) {
18854 		case STATUS_RESERVATION_CONFLICT:
18855 			/* Ignore reservation conflict */
18856 			status = 0;
18857 			goto done;
18858 
18859 		case STATUS_CHECK:
18860 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
18861 			    (scsi_sense_key(sense_buf) ==
18862 			    KEY_ILLEGAL_REQUEST)) {
18863 				/* Ignore Illegal Request error */
18864 				if (cdb->cdb_un.tag|SD_SYNC_NV_BIT) {
18865 					mutex_enter(SD_MUTEX(un));
18866 					un->un_f_sync_nv_supported = FALSE;
18867 					mutex_exit(SD_MUTEX(un));
18868 					status = 0;
18869 					SD_TRACE(SD_LOG_IO, un,
18870 					    "un_f_sync_nv_supported \
18871 					    is set to false.\n");
18872 					goto done;
18873 				}
18874 
18875 				mutex_enter(SD_MUTEX(un));
18876 				un->un_f_sync_cache_supported = FALSE;
18877 				mutex_exit(SD_MUTEX(un));
18878 				SD_TRACE(SD_LOG_IO, un,
18879 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
18880 				    un_f_sync_cache_supported set to false \
18881 				    with asc = %x, ascq = %x\n",
18882 				    scsi_sense_asc(sense_buf),
18883 				    scsi_sense_ascq(sense_buf));
18884 				status = ENOTSUP;
18885 				goto done;
18886 			}
18887 			break;
18888 		default:
18889 			break;
18890 		}
18891 		/* FALLTHRU */
18892 	default:
18893 		/*
18894 		 * Don't log an error message if this device
18895 		 * has removable media.
18896 		 */
18897 		if (!un->un_f_has_removable_media) {
18898 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18899 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
18900 		}
18901 		break;
18902 	}
18903 
18904 done:
18905 	if (uip->ui_dkc.dkc_callback != NULL) {
18906 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
18907 	}
18908 
18909 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
18910 	freerbuf(bp);
18911 	kmem_free(uip, sizeof (struct sd_uscsi_info));
18912 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
18913 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
18914 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
18915 
18916 	return (status);
18917 }
18918 
18919 
18920 /*
18921  *    Function: sd_send_scsi_GET_CONFIGURATION
18922  *
18923  * Description: Issues the get configuration command to the device.
18924  *		Called from sd_check_for_writable_cd & sd_get_media_info
18925  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
18926  *   Arguments: un
18927  *		ucmdbuf
18928  *		rqbuf
18929  *		rqbuflen
18930  *		bufaddr
18931  *		buflen
18932  *		path_flag
18933  *
18934  * Return Code: 0   - Success
18935  *		errno return code from sd_send_scsi_cmd()
18936  *
18937  *     Context: Can sleep. Does not return until command is completed.
18938  *
18939  */
18940 
18941 static int
18942 sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un, struct uscsi_cmd *ucmdbuf,
18943 	uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
18944 	int path_flag)
18945 {
18946 	char	cdb[CDB_GROUP1];
18947 	int	status;
18948 
18949 	ASSERT(un != NULL);
18950 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18951 	ASSERT(bufaddr != NULL);
18952 	ASSERT(ucmdbuf != NULL);
18953 	ASSERT(rqbuf != NULL);
18954 
18955 	SD_TRACE(SD_LOG_IO, un,
18956 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
18957 
18958 	bzero(cdb, sizeof (cdb));
18959 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
18960 	bzero(rqbuf, rqbuflen);
18961 	bzero(bufaddr, buflen);
18962 
18963 	/*
18964 	 * Set up cdb field for the get configuration command.
18965 	 */
18966 	cdb[0] = SCMD_GET_CONFIGURATION;
18967 	cdb[1] = 0x02;  /* Requested Type */
18968 	cdb[8] = SD_PROFILE_HEADER_LEN;
18969 	ucmdbuf->uscsi_cdb = cdb;
18970 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
18971 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
18972 	ucmdbuf->uscsi_buflen = buflen;
18973 	ucmdbuf->uscsi_timeout = sd_io_time;
18974 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
18975 	ucmdbuf->uscsi_rqlen = rqbuflen;
18976 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
18977 
18978 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, FKIOCTL,
18979 	    UIO_SYSSPACE, path_flag);
18980 
18981 	switch (status) {
18982 	case 0:
18983 		break;  /* Success! */
18984 	case EIO:
18985 		switch (ucmdbuf->uscsi_status) {
18986 		case STATUS_RESERVATION_CONFLICT:
18987 			status = EACCES;
18988 			break;
18989 		default:
18990 			break;
18991 		}
18992 		break;
18993 	default:
18994 		break;
18995 	}
18996 
18997 	if (status == 0) {
18998 		SD_DUMP_MEMORY(un, SD_LOG_IO,
18999 		    "sd_send_scsi_GET_CONFIGURATION: data",
19000 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
19001 	}
19002 
19003 	SD_TRACE(SD_LOG_IO, un,
19004 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
19005 
19006 	return (status);
19007 }
19008 
19009 /*
19010  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
19011  *
19012  * Description: Issues the get configuration command to the device to
19013  *              retrieve a specific feature. Called from
19014  *		sd_check_for_writable_cd & sd_set_mmc_caps.
19015  *   Arguments: un
19016  *              ucmdbuf
19017  *              rqbuf
19018  *              rqbuflen
19019  *              bufaddr
19020  *              buflen
19021  *		feature
19022  *
19023  * Return Code: 0   - Success
19024  *              errno return code from sd_send_scsi_cmd()
19025  *
19026  *     Context: Can sleep. Does not return until command is completed.
19027  *
19028  */
19029 static int
19030 sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
19031 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
19032 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag)
19033 {
19034 	char    cdb[CDB_GROUP1];
19035 	int	status;
19036 
19037 	ASSERT(un != NULL);
19038 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19039 	ASSERT(bufaddr != NULL);
19040 	ASSERT(ucmdbuf != NULL);
19041 	ASSERT(rqbuf != NULL);
19042 
19043 	SD_TRACE(SD_LOG_IO, un,
19044 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
19045 
19046 	bzero(cdb, sizeof (cdb));
19047 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
19048 	bzero(rqbuf, rqbuflen);
19049 	bzero(bufaddr, buflen);
19050 
19051 	/*
19052 	 * Set up cdb field for the get configuration command.
19053 	 */
19054 	cdb[0] = SCMD_GET_CONFIGURATION;
19055 	cdb[1] = 0x02;  /* Requested Type */
19056 	cdb[3] = feature;
19057 	cdb[8] = buflen;
19058 	ucmdbuf->uscsi_cdb = cdb;
19059 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
19060 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
19061 	ucmdbuf->uscsi_buflen = buflen;
19062 	ucmdbuf->uscsi_timeout = sd_io_time;
19063 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
19064 	ucmdbuf->uscsi_rqlen = rqbuflen;
19065 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
19066 
19067 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, FKIOCTL,
19068 	    UIO_SYSSPACE, path_flag);
19069 
19070 	switch (status) {
19071 	case 0:
19072 		break;  /* Success! */
19073 	case EIO:
19074 		switch (ucmdbuf->uscsi_status) {
19075 		case STATUS_RESERVATION_CONFLICT:
19076 			status = EACCES;
19077 			break;
19078 		default:
19079 			break;
19080 		}
19081 		break;
19082 	default:
19083 		break;
19084 	}
19085 
19086 	if (status == 0) {
19087 		SD_DUMP_MEMORY(un, SD_LOG_IO,
19088 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
19089 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
19090 	}
19091 
19092 	SD_TRACE(SD_LOG_IO, un,
19093 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
19094 
19095 	return (status);
19096 }
19097 
19098 
19099 /*
19100  *    Function: sd_send_scsi_MODE_SENSE
19101  *
19102  * Description: Utility function for issuing a scsi MODE SENSE command.
19103  *		Note: This routine uses a consistent implementation for Group0,
19104  *		Group1, and Group2 commands across all platforms. ATAPI devices
19105  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
19106  *
19107  *   Arguments: un - pointer to the softstate struct for the target.
19108  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
19109  *			  CDB_GROUP[1|2] (10 byte).
19110  *		bufaddr - buffer for page data retrieved from the target.
19111  *		buflen - size of page to be retrieved.
19112  *		page_code - page code of data to be retrieved from the target.
19113  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19114  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19115  *			to use the USCSI "direct" chain and bypass the normal
19116  *			command waitq.
19117  *
19118  * Return Code: 0   - Success
19119  *		errno return code from sd_send_scsi_cmd()
19120  *
19121  *     Context: Can sleep. Does not return until command is completed.
19122  */
19123 
19124 static int
19125 sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
19126 	size_t buflen,  uchar_t page_code, int path_flag)
19127 {
19128 	struct	scsi_extended_sense	sense_buf;
19129 	union scsi_cdb		cdb;
19130 	struct uscsi_cmd	ucmd_buf;
19131 	int			status;
19132 	int			headlen;
19133 
19134 	ASSERT(un != NULL);
19135 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19136 	ASSERT(bufaddr != NULL);
19137 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
19138 	    (cdbsize == CDB_GROUP2));
19139 
19140 	SD_TRACE(SD_LOG_IO, un,
19141 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
19142 
19143 	bzero(&cdb, sizeof (cdb));
19144 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19145 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19146 	bzero(bufaddr, buflen);
19147 
19148 	if (cdbsize == CDB_GROUP0) {
19149 		cdb.scc_cmd = SCMD_MODE_SENSE;
19150 		cdb.cdb_opaque[2] = page_code;
19151 		FORMG0COUNT(&cdb, buflen);
19152 		headlen = MODE_HEADER_LENGTH;
19153 	} else {
19154 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
19155 		cdb.cdb_opaque[2] = page_code;
19156 		FORMG1COUNT(&cdb, buflen);
19157 		headlen = MODE_HEADER_LENGTH_GRP2;
19158 	}
19159 
19160 	ASSERT(headlen <= buflen);
19161 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19162 
19163 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19164 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19165 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19166 	ucmd_buf.uscsi_buflen	= buflen;
19167 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19168 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19169 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19170 	ucmd_buf.uscsi_timeout	= 60;
19171 
19172 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19173 	    UIO_SYSSPACE, path_flag);
19174 
19175 	switch (status) {
19176 	case 0:
19177 		/*
19178 		 * sr_check_wp() uses 0x3f page code and check the header of
19179 		 * mode page to determine if target device is write-protected.
19180 		 * But some USB devices return 0 bytes for 0x3f page code. For
19181 		 * this case, make sure that mode page header is returned at
19182 		 * least.
19183 		 */
19184 		if (buflen - ucmd_buf.uscsi_resid <  headlen)
19185 			status = EIO;
19186 		break;	/* Success! */
19187 	case EIO:
19188 		switch (ucmd_buf.uscsi_status) {
19189 		case STATUS_RESERVATION_CONFLICT:
19190 			status = EACCES;
19191 			break;
19192 		default:
19193 			break;
19194 		}
19195 		break;
19196 	default:
19197 		break;
19198 	}
19199 
19200 	if (status == 0) {
19201 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
19202 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19203 	}
19204 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
19205 
19206 	return (status);
19207 }
19208 
19209 
19210 /*
19211  *    Function: sd_send_scsi_MODE_SELECT
19212  *
19213  * Description: Utility function for issuing a scsi MODE SELECT command.
19214  *		Note: This routine uses a consistent implementation for Group0,
19215  *		Group1, and Group2 commands across all platforms. ATAPI devices
19216  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
19217  *
19218  *   Arguments: un - pointer to the softstate struct for the target.
19219  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
19220  *			  CDB_GROUP[1|2] (10 byte).
19221  *		bufaddr - buffer for page data retrieved from the target.
19222  *		buflen - size of page to be retrieved.
19223  *		save_page - boolean to determin if SP bit should be set.
19224  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19225  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19226  *			to use the USCSI "direct" chain and bypass the normal
19227  *			command waitq.
19228  *
19229  * Return Code: 0   - Success
19230  *		errno return code from sd_send_scsi_cmd()
19231  *
19232  *     Context: Can sleep. Does not return until command is completed.
19233  */
19234 
19235 static int
19236 sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
19237 	size_t buflen,  uchar_t save_page, int path_flag)
19238 {
19239 	struct	scsi_extended_sense	sense_buf;
19240 	union scsi_cdb		cdb;
19241 	struct uscsi_cmd	ucmd_buf;
19242 	int			status;
19243 
19244 	ASSERT(un != NULL);
19245 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19246 	ASSERT(bufaddr != NULL);
19247 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
19248 	    (cdbsize == CDB_GROUP2));
19249 
19250 	SD_TRACE(SD_LOG_IO, un,
19251 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
19252 
19253 	bzero(&cdb, sizeof (cdb));
19254 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19255 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19256 
19257 	/* Set the PF bit for many third party drives */
19258 	cdb.cdb_opaque[1] = 0x10;
19259 
19260 	/* Set the savepage(SP) bit if given */
19261 	if (save_page == SD_SAVE_PAGE) {
19262 		cdb.cdb_opaque[1] |= 0x01;
19263 	}
19264 
19265 	if (cdbsize == CDB_GROUP0) {
19266 		cdb.scc_cmd = SCMD_MODE_SELECT;
19267 		FORMG0COUNT(&cdb, buflen);
19268 	} else {
19269 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
19270 		FORMG1COUNT(&cdb, buflen);
19271 	}
19272 
19273 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19274 
19275 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19276 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19277 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19278 	ucmd_buf.uscsi_buflen	= buflen;
19279 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19280 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19281 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
19282 	ucmd_buf.uscsi_timeout	= 60;
19283 
19284 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19285 	    UIO_SYSSPACE, path_flag);
19286 
19287 	switch (status) {
19288 	case 0:
19289 		break;	/* Success! */
19290 	case EIO:
19291 		switch (ucmd_buf.uscsi_status) {
19292 		case STATUS_RESERVATION_CONFLICT:
19293 			status = EACCES;
19294 			break;
19295 		default:
19296 			break;
19297 		}
19298 		break;
19299 	default:
19300 		break;
19301 	}
19302 
19303 	if (status == 0) {
19304 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
19305 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19306 	}
19307 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
19308 
19309 	return (status);
19310 }
19311 
19312 
19313 /*
19314  *    Function: sd_send_scsi_RDWR
19315  *
19316  * Description: Issue a scsi READ or WRITE command with the given parameters.
19317  *
19318  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19319  *		cmd:	 SCMD_READ or SCMD_WRITE
19320  *		bufaddr: Address of caller's buffer to receive the RDWR data
19321  *		buflen:  Length of caller's buffer receive the RDWR data.
19322  *		start_block: Block number for the start of the RDWR operation.
19323  *			 (Assumes target-native block size.)
19324  *		residp:  Pointer to variable to receive the redisual of the
19325  *			 RDWR operation (may be NULL of no residual requested).
19326  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19327  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19328  *			to use the USCSI "direct" chain and bypass the normal
19329  *			command waitq.
19330  *
19331  * Return Code: 0   - Success
19332  *		errno return code from sd_send_scsi_cmd()
19333  *
19334  *     Context: Can sleep. Does not return until command is completed.
19335  */
19336 
19337 static int
19338 sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
19339 	size_t buflen, daddr_t start_block, int path_flag)
19340 {
19341 	struct	scsi_extended_sense	sense_buf;
19342 	union scsi_cdb		cdb;
19343 	struct uscsi_cmd	ucmd_buf;
19344 	uint32_t		block_count;
19345 	int			status;
19346 	int			cdbsize;
19347 	uchar_t			flag;
19348 
19349 	ASSERT(un != NULL);
19350 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19351 	ASSERT(bufaddr != NULL);
19352 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
19353 
19354 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
19355 
19356 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
19357 		return (EINVAL);
19358 	}
19359 
19360 	mutex_enter(SD_MUTEX(un));
19361 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
19362 	mutex_exit(SD_MUTEX(un));
19363 
19364 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
19365 
19366 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
19367 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
19368 	    bufaddr, buflen, start_block, block_count);
19369 
19370 	bzero(&cdb, sizeof (cdb));
19371 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19372 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19373 
19374 	/* Compute CDB size to use */
19375 	if (start_block > 0xffffffff)
19376 		cdbsize = CDB_GROUP4;
19377 	else if ((start_block & 0xFFE00000) ||
19378 	    (un->un_f_cfg_is_atapi == TRUE))
19379 		cdbsize = CDB_GROUP1;
19380 	else
19381 		cdbsize = CDB_GROUP0;
19382 
19383 	switch (cdbsize) {
19384 	case CDB_GROUP0:	/* 6-byte CDBs */
19385 		cdb.scc_cmd = cmd;
19386 		FORMG0ADDR(&cdb, start_block);
19387 		FORMG0COUNT(&cdb, block_count);
19388 		break;
19389 	case CDB_GROUP1:	/* 10-byte CDBs */
19390 		cdb.scc_cmd = cmd | SCMD_GROUP1;
19391 		FORMG1ADDR(&cdb, start_block);
19392 		FORMG1COUNT(&cdb, block_count);
19393 		break;
19394 	case CDB_GROUP4:	/* 16-byte CDBs */
19395 		cdb.scc_cmd = cmd | SCMD_GROUP4;
19396 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
19397 		FORMG4COUNT(&cdb, block_count);
19398 		break;
19399 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
19400 	default:
19401 		/* All others reserved */
19402 		return (EINVAL);
19403 	}
19404 
19405 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
19406 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19407 
19408 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19409 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19410 	ucmd_buf.uscsi_bufaddr	= bufaddr;
19411 	ucmd_buf.uscsi_buflen	= buflen;
19412 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19413 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19414 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
19415 	ucmd_buf.uscsi_timeout	= 60;
19416 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19417 	    UIO_SYSSPACE, path_flag);
19418 	switch (status) {
19419 	case 0:
19420 		break;	/* Success! */
19421 	case EIO:
19422 		switch (ucmd_buf.uscsi_status) {
19423 		case STATUS_RESERVATION_CONFLICT:
19424 			status = EACCES;
19425 			break;
19426 		default:
19427 			break;
19428 		}
19429 		break;
19430 	default:
19431 		break;
19432 	}
19433 
19434 	if (status == 0) {
19435 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
19436 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19437 	}
19438 
19439 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
19440 
19441 	return (status);
19442 }
19443 
19444 
19445 /*
19446  *    Function: sd_send_scsi_LOG_SENSE
19447  *
19448  * Description: Issue a scsi LOG_SENSE command with the given parameters.
19449  *
19450  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19451  *
19452  * Return Code: 0   - Success
19453  *		errno return code from sd_send_scsi_cmd()
19454  *
19455  *     Context: Can sleep. Does not return until command is completed.
19456  */
19457 
19458 static int
19459 sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr, uint16_t buflen,
19460 	uchar_t page_code, uchar_t page_control, uint16_t param_ptr,
19461 	int path_flag)
19462 
19463 {
19464 	struct	scsi_extended_sense	sense_buf;
19465 	union scsi_cdb		cdb;
19466 	struct uscsi_cmd	ucmd_buf;
19467 	int			status;
19468 
19469 	ASSERT(un != NULL);
19470 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19471 
19472 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
19473 
19474 	bzero(&cdb, sizeof (cdb));
19475 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19476 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19477 
19478 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
19479 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
19480 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
19481 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
19482 	FORMG1COUNT(&cdb, buflen);
19483 
19484 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19485 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19486 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19487 	ucmd_buf.uscsi_buflen	= buflen;
19488 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19489 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19490 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19491 	ucmd_buf.uscsi_timeout	= 60;
19492 
19493 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19494 	    UIO_SYSSPACE, path_flag);
19495 
19496 	switch (status) {
19497 	case 0:
19498 		break;
19499 	case EIO:
19500 		switch (ucmd_buf.uscsi_status) {
19501 		case STATUS_RESERVATION_CONFLICT:
19502 			status = EACCES;
19503 			break;
19504 		case STATUS_CHECK:
19505 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19506 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
19507 				KEY_ILLEGAL_REQUEST) &&
19508 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
19509 				/*
19510 				 * ASC 0x24: INVALID FIELD IN CDB
19511 				 */
19512 				switch (page_code) {
19513 				case START_STOP_CYCLE_PAGE:
19514 					/*
19515 					 * The start stop cycle counter is
19516 					 * implemented as page 0x31 in earlier
19517 					 * generation disks. In new generation
19518 					 * disks the start stop cycle counter is
19519 					 * implemented as page 0xE. To properly
19520 					 * handle this case if an attempt for
19521 					 * log page 0xE is made and fails we
19522 					 * will try again using page 0x31.
19523 					 *
19524 					 * Network storage BU committed to
19525 					 * maintain the page 0x31 for this
19526 					 * purpose and will not have any other
19527 					 * page implemented with page code 0x31
19528 					 * until all disks transition to the
19529 					 * standard page.
19530 					 */
19531 					mutex_enter(SD_MUTEX(un));
19532 					un->un_start_stop_cycle_page =
19533 					    START_STOP_CYCLE_VU_PAGE;
19534 					cdb.cdb_opaque[2] =
19535 					    (char)(page_control << 6) |
19536 					    un->un_start_stop_cycle_page;
19537 					mutex_exit(SD_MUTEX(un));
19538 					status = sd_send_scsi_cmd(
19539 					    SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19540 					    UIO_SYSSPACE, path_flag);
19541 
19542 					break;
19543 				case TEMPERATURE_PAGE:
19544 					status = ENOTTY;
19545 					break;
19546 				default:
19547 					break;
19548 				}
19549 			}
19550 			break;
19551 		default:
19552 			break;
19553 		}
19554 		break;
19555 	default:
19556 		break;
19557 	}
19558 
19559 	if (status == 0) {
19560 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
19561 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19562 	}
19563 
19564 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
19565 
19566 	return (status);
19567 }
19568 
19569 
19570 /*
19571  *    Function: sdioctl
19572  *
19573  * Description: Driver's ioctl(9e) entry point function.
19574  *
19575  *   Arguments: dev     - device number
19576  *		cmd     - ioctl operation to be performed
19577  *		arg     - user argument, contains data to be set or reference
19578  *			  parameter for get
19579  *		flag    - bit flag, indicating open settings, 32/64 bit type
19580  *		cred_p  - user credential pointer
19581  *		rval_p  - calling process return value (OPT)
19582  *
19583  * Return Code: EINVAL
19584  *		ENOTTY
19585  *		ENXIO
19586  *		EIO
19587  *		EFAULT
19588  *		ENOTSUP
19589  *		EPERM
19590  *
19591  *     Context: Called from the device switch at normal priority.
19592  */
19593 
19594 static int
19595 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
19596 {
19597 	struct sd_lun	*un = NULL;
19598 	int		err = 0;
19599 	int		i = 0;
19600 	cred_t		*cr;
19601 	int		tmprval = EINVAL;
19602 	int 		is_valid;
19603 
19604 	/*
19605 	 * All device accesses go thru sdstrategy where we check on suspend
19606 	 * status
19607 	 */
19608 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
19609 		return (ENXIO);
19610 	}
19611 
19612 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19613 
19614 
19615 	is_valid = SD_IS_VALID_LABEL(un);
19616 
19617 	/*
19618 	 * Moved this wait from sd_uscsi_strategy to here for
19619 	 * reasons of deadlock prevention. Internal driver commands,
19620 	 * specifically those to change a devices power level, result
19621 	 * in a call to sd_uscsi_strategy.
19622 	 */
19623 	mutex_enter(SD_MUTEX(un));
19624 	while ((un->un_state == SD_STATE_SUSPENDED) ||
19625 	    (un->un_state == SD_STATE_PM_CHANGING)) {
19626 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
19627 	}
19628 	/*
19629 	 * Twiddling the counter here protects commands from now
19630 	 * through to the top of sd_uscsi_strategy. Without the
19631 	 * counter inc. a power down, for example, could get in
19632 	 * after the above check for state is made and before
19633 	 * execution gets to the top of sd_uscsi_strategy.
19634 	 * That would cause problems.
19635 	 */
19636 	un->un_ncmds_in_driver++;
19637 
19638 	if (!is_valid &&
19639 	    (flag & (FNDELAY | FNONBLOCK))) {
19640 		switch (cmd) {
19641 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
19642 		case DKIOCGVTOC:
19643 		case DKIOCGAPART:
19644 		case DKIOCPARTINFO:
19645 		case DKIOCSGEOM:
19646 		case DKIOCSAPART:
19647 		case DKIOCGETEFI:
19648 		case DKIOCPARTITION:
19649 		case DKIOCSVTOC:
19650 		case DKIOCSETEFI:
19651 		case DKIOCGMBOOT:
19652 		case DKIOCSMBOOT:
19653 		case DKIOCG_PHYGEOM:
19654 		case DKIOCG_VIRTGEOM:
19655 			/* let cmlb handle it */
19656 			goto skip_ready_valid;
19657 
19658 		case CDROMPAUSE:
19659 		case CDROMRESUME:
19660 		case CDROMPLAYMSF:
19661 		case CDROMPLAYTRKIND:
19662 		case CDROMREADTOCHDR:
19663 		case CDROMREADTOCENTRY:
19664 		case CDROMSTOP:
19665 		case CDROMSTART:
19666 		case CDROMVOLCTRL:
19667 		case CDROMSUBCHNL:
19668 		case CDROMREADMODE2:
19669 		case CDROMREADMODE1:
19670 		case CDROMREADOFFSET:
19671 		case CDROMSBLKMODE:
19672 		case CDROMGBLKMODE:
19673 		case CDROMGDRVSPEED:
19674 		case CDROMSDRVSPEED:
19675 		case CDROMCDDA:
19676 		case CDROMCDXA:
19677 		case CDROMSUBCODE:
19678 			if (!ISCD(un)) {
19679 				un->un_ncmds_in_driver--;
19680 				ASSERT(un->un_ncmds_in_driver >= 0);
19681 				mutex_exit(SD_MUTEX(un));
19682 				return (ENOTTY);
19683 			}
19684 			break;
19685 		case FDEJECT:
19686 		case DKIOCEJECT:
19687 		case CDROMEJECT:
19688 			if (!un->un_f_eject_media_supported) {
19689 				un->un_ncmds_in_driver--;
19690 				ASSERT(un->un_ncmds_in_driver >= 0);
19691 				mutex_exit(SD_MUTEX(un));
19692 				return (ENOTTY);
19693 			}
19694 			break;
19695 		case DKIOCFLUSHWRITECACHE:
19696 			mutex_exit(SD_MUTEX(un));
19697 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
19698 			if (err != 0) {
19699 				mutex_enter(SD_MUTEX(un));
19700 				un->un_ncmds_in_driver--;
19701 				ASSERT(un->un_ncmds_in_driver >= 0);
19702 				mutex_exit(SD_MUTEX(un));
19703 				return (EIO);
19704 			}
19705 			mutex_enter(SD_MUTEX(un));
19706 			/* FALLTHROUGH */
19707 		case DKIOCREMOVABLE:
19708 		case DKIOCHOTPLUGGABLE:
19709 		case DKIOCINFO:
19710 		case DKIOCGMEDIAINFO:
19711 		case MHIOCENFAILFAST:
19712 		case MHIOCSTATUS:
19713 		case MHIOCTKOWN:
19714 		case MHIOCRELEASE:
19715 		case MHIOCGRP_INKEYS:
19716 		case MHIOCGRP_INRESV:
19717 		case MHIOCGRP_REGISTER:
19718 		case MHIOCGRP_RESERVE:
19719 		case MHIOCGRP_PREEMPTANDABORT:
19720 		case MHIOCGRP_REGISTERANDIGNOREKEY:
19721 		case CDROMCLOSETRAY:
19722 		case USCSICMD:
19723 			goto skip_ready_valid;
19724 		default:
19725 			break;
19726 		}
19727 
19728 		mutex_exit(SD_MUTEX(un));
19729 		err = sd_ready_and_valid(un);
19730 		mutex_enter(SD_MUTEX(un));
19731 
19732 		if (err != SD_READY_VALID) {
19733 			switch (cmd) {
19734 			case DKIOCSTATE:
19735 			case CDROMGDRVSPEED:
19736 			case CDROMSDRVSPEED:
19737 			case FDEJECT:	/* for eject command */
19738 			case DKIOCEJECT:
19739 			case CDROMEJECT:
19740 			case DKIOCREMOVABLE:
19741 			case DKIOCHOTPLUGGABLE:
19742 				break;
19743 			default:
19744 				if (un->un_f_has_removable_media) {
19745 					err = ENXIO;
19746 				} else {
19747 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
19748 					if (err == SD_RESERVED_BY_OTHERS) {
19749 						err = EACCES;
19750 					} else {
19751 						err = EIO;
19752 					}
19753 				}
19754 				un->un_ncmds_in_driver--;
19755 				ASSERT(un->un_ncmds_in_driver >= 0);
19756 				mutex_exit(SD_MUTEX(un));
19757 				return (err);
19758 			}
19759 		}
19760 	}
19761 
19762 skip_ready_valid:
19763 	mutex_exit(SD_MUTEX(un));
19764 
19765 	switch (cmd) {
19766 	case DKIOCINFO:
19767 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
19768 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
19769 		break;
19770 
19771 	case DKIOCGMEDIAINFO:
19772 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
19773 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
19774 		break;
19775 
19776 	case DKIOCGGEOM:
19777 	case DKIOCGVTOC:
19778 	case DKIOCGAPART:
19779 	case DKIOCPARTINFO:
19780 	case DKIOCSGEOM:
19781 	case DKIOCSAPART:
19782 	case DKIOCGETEFI:
19783 	case DKIOCPARTITION:
19784 	case DKIOCSVTOC:
19785 	case DKIOCSETEFI:
19786 	case DKIOCGMBOOT:
19787 	case DKIOCSMBOOT:
19788 	case DKIOCG_PHYGEOM:
19789 	case DKIOCG_VIRTGEOM:
19790 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
19791 
19792 		/* TUR should spin up */
19793 
19794 		if (un->un_f_has_removable_media)
19795 			err = sd_send_scsi_TEST_UNIT_READY(un,
19796 			    SD_CHECK_FOR_MEDIA);
19797 		else
19798 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
19799 
19800 		if (err != 0)
19801 			break;
19802 
19803 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
19804 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
19805 
19806 		if ((err == 0) &&
19807 		    ((cmd == DKIOCSETEFI) ||
19808 		    (un->un_f_pkstats_enabled) &&
19809 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC))) {
19810 
19811 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
19812 			    (void *)SD_PATH_DIRECT);
19813 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
19814 				sd_set_pstats(un);
19815 				SD_TRACE(SD_LOG_IO_PARTITION, un,
19816 				    "sd_ioctl: un:0x%p pstats created and "
19817 				    "set\n", un);
19818 			}
19819 		}
19820 
19821 		if ((cmd == DKIOCSVTOC) ||
19822 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
19823 
19824 			mutex_enter(SD_MUTEX(un));
19825 			if (un->un_f_devid_supported &&
19826 			    (un->un_f_opt_fab_devid == TRUE)) {
19827 				if (un->un_devid == NULL) {
19828 					sd_register_devid(un, SD_DEVINFO(un),
19829 					    SD_TARGET_IS_UNRESERVED);
19830 				} else {
19831 					/*
19832 					 * The device id for this disk
19833 					 * has been fabricated. The
19834 					 * device id must be preserved
19835 					 * by writing it back out to
19836 					 * disk.
19837 					 */
19838 					if (sd_write_deviceid(un) != 0) {
19839 						ddi_devid_free(un->un_devid);
19840 						un->un_devid = NULL;
19841 					}
19842 				}
19843 			}
19844 			mutex_exit(SD_MUTEX(un));
19845 		}
19846 
19847 		break;
19848 
19849 	case DKIOCLOCK:
19850 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
19851 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
19852 		    SD_PATH_STANDARD);
19853 		break;
19854 
19855 	case DKIOCUNLOCK:
19856 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
19857 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
19858 		    SD_PATH_STANDARD);
19859 		break;
19860 
19861 	case DKIOCSTATE: {
19862 		enum dkio_state		state;
19863 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
19864 
19865 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
19866 			err = EFAULT;
19867 		} else {
19868 			err = sd_check_media(dev, state);
19869 			if (err == 0) {
19870 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
19871 				    sizeof (int), flag) != 0)
19872 					err = EFAULT;
19873 			}
19874 		}
19875 		break;
19876 	}
19877 
19878 	case DKIOCREMOVABLE:
19879 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
19880 		i = un->un_f_has_removable_media ? 1 : 0;
19881 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
19882 			err = EFAULT;
19883 		} else {
19884 			err = 0;
19885 		}
19886 		break;
19887 
19888 	case DKIOCHOTPLUGGABLE:
19889 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
19890 		i = un->un_f_is_hotpluggable ? 1 : 0;
19891 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
19892 			err = EFAULT;
19893 		} else {
19894 			err = 0;
19895 		}
19896 		break;
19897 
19898 	case DKIOCGTEMPERATURE:
19899 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
19900 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
19901 		break;
19902 
19903 	case MHIOCENFAILFAST:
19904 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
19905 		if ((err = drv_priv(cred_p)) == 0) {
19906 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
19907 		}
19908 		break;
19909 
19910 	case MHIOCTKOWN:
19911 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
19912 		if ((err = drv_priv(cred_p)) == 0) {
19913 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
19914 		}
19915 		break;
19916 
19917 	case MHIOCRELEASE:
19918 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
19919 		if ((err = drv_priv(cred_p)) == 0) {
19920 			err = sd_mhdioc_release(dev);
19921 		}
19922 		break;
19923 
19924 	case MHIOCSTATUS:
19925 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
19926 		if ((err = drv_priv(cred_p)) == 0) {
19927 			switch (sd_send_scsi_TEST_UNIT_READY(un, 0)) {
19928 			case 0:
19929 				err = 0;
19930 				break;
19931 			case EACCES:
19932 				*rval_p = 1;
19933 				err = 0;
19934 				break;
19935 			default:
19936 				err = EIO;
19937 				break;
19938 			}
19939 		}
19940 		break;
19941 
19942 	case MHIOCQRESERVE:
19943 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
19944 		if ((err = drv_priv(cred_p)) == 0) {
19945 			err = sd_reserve_release(dev, SD_RESERVE);
19946 		}
19947 		break;
19948 
19949 	case MHIOCREREGISTERDEVID:
19950 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
19951 		if (drv_priv(cred_p) == EPERM) {
19952 			err = EPERM;
19953 		} else if (!un->un_f_devid_supported) {
19954 			err = ENOTTY;
19955 		} else {
19956 			err = sd_mhdioc_register_devid(dev);
19957 		}
19958 		break;
19959 
19960 	case MHIOCGRP_INKEYS:
19961 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
19962 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
19963 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19964 				err = ENOTSUP;
19965 			} else {
19966 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
19967 				    flag);
19968 			}
19969 		}
19970 		break;
19971 
19972 	case MHIOCGRP_INRESV:
19973 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
19974 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
19975 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19976 				err = ENOTSUP;
19977 			} else {
19978 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
19979 			}
19980 		}
19981 		break;
19982 
19983 	case MHIOCGRP_REGISTER:
19984 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
19985 		if ((err = drv_priv(cred_p)) != EPERM) {
19986 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19987 				err = ENOTSUP;
19988 			} else if (arg != NULL) {
19989 				mhioc_register_t reg;
19990 				if (ddi_copyin((void *)arg, &reg,
19991 				    sizeof (mhioc_register_t), flag) != 0) {
19992 					err = EFAULT;
19993 				} else {
19994 					err =
19995 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
19996 					    un, SD_SCSI3_REGISTER,
19997 					    (uchar_t *)&reg);
19998 				}
19999 			}
20000 		}
20001 		break;
20002 
20003 	case MHIOCGRP_RESERVE:
20004 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
20005 		if ((err = drv_priv(cred_p)) != EPERM) {
20006 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20007 				err = ENOTSUP;
20008 			} else if (arg != NULL) {
20009 				mhioc_resv_desc_t resv_desc;
20010 				if (ddi_copyin((void *)arg, &resv_desc,
20011 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
20012 					err = EFAULT;
20013 				} else {
20014 					err =
20015 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20016 					    un, SD_SCSI3_RESERVE,
20017 					    (uchar_t *)&resv_desc);
20018 				}
20019 			}
20020 		}
20021 		break;
20022 
20023 	case MHIOCGRP_PREEMPTANDABORT:
20024 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
20025 		if ((err = drv_priv(cred_p)) != EPERM) {
20026 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20027 				err = ENOTSUP;
20028 			} else if (arg != NULL) {
20029 				mhioc_preemptandabort_t preempt_abort;
20030 				if (ddi_copyin((void *)arg, &preempt_abort,
20031 				    sizeof (mhioc_preemptandabort_t),
20032 				    flag) != 0) {
20033 					err = EFAULT;
20034 				} else {
20035 					err =
20036 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20037 					    un, SD_SCSI3_PREEMPTANDABORT,
20038 					    (uchar_t *)&preempt_abort);
20039 				}
20040 			}
20041 		}
20042 		break;
20043 
20044 	case MHIOCGRP_REGISTERANDIGNOREKEY:
20045 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
20046 		if ((err = drv_priv(cred_p)) != EPERM) {
20047 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20048 				err = ENOTSUP;
20049 			} else if (arg != NULL) {
20050 				mhioc_registerandignorekey_t r_and_i;
20051 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
20052 				    sizeof (mhioc_registerandignorekey_t),
20053 				    flag) != 0) {
20054 					err = EFAULT;
20055 				} else {
20056 					err =
20057 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20058 					    un, SD_SCSI3_REGISTERANDIGNOREKEY,
20059 					    (uchar_t *)&r_and_i);
20060 				}
20061 			}
20062 		}
20063 		break;
20064 
20065 	case USCSICMD:
20066 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
20067 		cr = ddi_get_cred();
20068 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
20069 			err = EPERM;
20070 		} else {
20071 			enum uio_seg	uioseg;
20072 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
20073 			    UIO_USERSPACE;
20074 			if (un->un_f_format_in_progress == TRUE) {
20075 				err = EAGAIN;
20076 				break;
20077 			}
20078 			err = sd_send_scsi_cmd(dev, (struct uscsi_cmd *)arg,
20079 			    flag, uioseg, SD_PATH_STANDARD);
20080 		}
20081 		break;
20082 
20083 	case CDROMPAUSE:
20084 	case CDROMRESUME:
20085 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
20086 		if (!ISCD(un)) {
20087 			err = ENOTTY;
20088 		} else {
20089 			err = sr_pause_resume(dev, cmd);
20090 		}
20091 		break;
20092 
20093 	case CDROMPLAYMSF:
20094 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
20095 		if (!ISCD(un)) {
20096 			err = ENOTTY;
20097 		} else {
20098 			err = sr_play_msf(dev, (caddr_t)arg, flag);
20099 		}
20100 		break;
20101 
20102 	case CDROMPLAYTRKIND:
20103 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
20104 #if defined(__i386) || defined(__amd64)
20105 		/*
20106 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
20107 		 */
20108 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
20109 #else
20110 		if (!ISCD(un)) {
20111 #endif
20112 			err = ENOTTY;
20113 		} else {
20114 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
20115 		}
20116 		break;
20117 
20118 	case CDROMREADTOCHDR:
20119 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
20120 		if (!ISCD(un)) {
20121 			err = ENOTTY;
20122 		} else {
20123 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
20124 		}
20125 		break;
20126 
20127 	case CDROMREADTOCENTRY:
20128 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
20129 		if (!ISCD(un)) {
20130 			err = ENOTTY;
20131 		} else {
20132 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
20133 		}
20134 		break;
20135 
20136 	case CDROMSTOP:
20137 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
20138 		if (!ISCD(un)) {
20139 			err = ENOTTY;
20140 		} else {
20141 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_STOP,
20142 			    SD_PATH_STANDARD);
20143 		}
20144 		break;
20145 
20146 	case CDROMSTART:
20147 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
20148 		if (!ISCD(un)) {
20149 			err = ENOTTY;
20150 		} else {
20151 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
20152 			    SD_PATH_STANDARD);
20153 		}
20154 		break;
20155 
20156 	case CDROMCLOSETRAY:
20157 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
20158 		if (!ISCD(un)) {
20159 			err = ENOTTY;
20160 		} else {
20161 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_CLOSE,
20162 			    SD_PATH_STANDARD);
20163 		}
20164 		break;
20165 
20166 	case FDEJECT:	/* for eject command */
20167 	case DKIOCEJECT:
20168 	case CDROMEJECT:
20169 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
20170 		if (!un->un_f_eject_media_supported) {
20171 			err = ENOTTY;
20172 		} else {
20173 			err = sr_eject(dev);
20174 		}
20175 		break;
20176 
20177 	case CDROMVOLCTRL:
20178 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
20179 		if (!ISCD(un)) {
20180 			err = ENOTTY;
20181 		} else {
20182 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
20183 		}
20184 		break;
20185 
20186 	case CDROMSUBCHNL:
20187 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
20188 		if (!ISCD(un)) {
20189 			err = ENOTTY;
20190 		} else {
20191 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
20192 		}
20193 		break;
20194 
20195 	case CDROMREADMODE2:
20196 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
20197 		if (!ISCD(un)) {
20198 			err = ENOTTY;
20199 		} else if (un->un_f_cfg_is_atapi == TRUE) {
20200 			/*
20201 			 * If the drive supports READ CD, use that instead of
20202 			 * switching the LBA size via a MODE SELECT
20203 			 * Block Descriptor
20204 			 */
20205 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
20206 		} else {
20207 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
20208 		}
20209 		break;
20210 
20211 	case CDROMREADMODE1:
20212 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
20213 		if (!ISCD(un)) {
20214 			err = ENOTTY;
20215 		} else {
20216 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
20217 		}
20218 		break;
20219 
20220 	case CDROMREADOFFSET:
20221 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
20222 		if (!ISCD(un)) {
20223 			err = ENOTTY;
20224 		} else {
20225 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
20226 			    flag);
20227 		}
20228 		break;
20229 
20230 	case CDROMSBLKMODE:
20231 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
20232 		/*
20233 		 * There is no means of changing block size in case of atapi
20234 		 * drives, thus return ENOTTY if drive type is atapi
20235 		 */
20236 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
20237 			err = ENOTTY;
20238 		} else if (un->un_f_mmc_cap == TRUE) {
20239 
20240 			/*
20241 			 * MMC Devices do not support changing the
20242 			 * logical block size
20243 			 *
20244 			 * Note: EINVAL is being returned instead of ENOTTY to
20245 			 * maintain consistancy with the original mmc
20246 			 * driver update.
20247 			 */
20248 			err = EINVAL;
20249 		} else {
20250 			mutex_enter(SD_MUTEX(un));
20251 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
20252 			    (un->un_ncmds_in_transport > 0)) {
20253 				mutex_exit(SD_MUTEX(un));
20254 				err = EINVAL;
20255 			} else {
20256 				mutex_exit(SD_MUTEX(un));
20257 				err = sr_change_blkmode(dev, cmd, arg, flag);
20258 			}
20259 		}
20260 		break;
20261 
20262 	case CDROMGBLKMODE:
20263 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
20264 		if (!ISCD(un)) {
20265 			err = ENOTTY;
20266 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
20267 		    (un->un_f_blockcount_is_valid != FALSE)) {
20268 			/*
20269 			 * Drive is an ATAPI drive so return target block
20270 			 * size for ATAPI drives since we cannot change the
20271 			 * blocksize on ATAPI drives. Used primarily to detect
20272 			 * if an ATAPI cdrom is present.
20273 			 */
20274 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
20275 			    sizeof (int), flag) != 0) {
20276 				err = EFAULT;
20277 			} else {
20278 				err = 0;
20279 			}
20280 
20281 		} else {
20282 			/*
20283 			 * Drive supports changing block sizes via a Mode
20284 			 * Select.
20285 			 */
20286 			err = sr_change_blkmode(dev, cmd, arg, flag);
20287 		}
20288 		break;
20289 
20290 	case CDROMGDRVSPEED:
20291 	case CDROMSDRVSPEED:
20292 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
20293 		if (!ISCD(un)) {
20294 			err = ENOTTY;
20295 		} else if (un->un_f_mmc_cap == TRUE) {
20296 			/*
20297 			 * Note: In the future the driver implementation
20298 			 * for getting and
20299 			 * setting cd speed should entail:
20300 			 * 1) If non-mmc try the Toshiba mode page
20301 			 *    (sr_change_speed)
20302 			 * 2) If mmc but no support for Real Time Streaming try
20303 			 *    the SET CD SPEED (0xBB) command
20304 			 *   (sr_atapi_change_speed)
20305 			 * 3) If mmc and support for Real Time Streaming
20306 			 *    try the GET PERFORMANCE and SET STREAMING
20307 			 *    commands (not yet implemented, 4380808)
20308 			 */
20309 			/*
20310 			 * As per recent MMC spec, CD-ROM speed is variable
20311 			 * and changes with LBA. Since there is no such
20312 			 * things as drive speed now, fail this ioctl.
20313 			 *
20314 			 * Note: EINVAL is returned for consistancy of original
20315 			 * implementation which included support for getting
20316 			 * the drive speed of mmc devices but not setting
20317 			 * the drive speed. Thus EINVAL would be returned
20318 			 * if a set request was made for an mmc device.
20319 			 * We no longer support get or set speed for
20320 			 * mmc but need to remain consistent with regard
20321 			 * to the error code returned.
20322 			 */
20323 			err = EINVAL;
20324 		} else if (un->un_f_cfg_is_atapi == TRUE) {
20325 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
20326 		} else {
20327 			err = sr_change_speed(dev, cmd, arg, flag);
20328 		}
20329 		break;
20330 
20331 	case CDROMCDDA:
20332 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
20333 		if (!ISCD(un)) {
20334 			err = ENOTTY;
20335 		} else {
20336 			err = sr_read_cdda(dev, (void *)arg, flag);
20337 		}
20338 		break;
20339 
20340 	case CDROMCDXA:
20341 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
20342 		if (!ISCD(un)) {
20343 			err = ENOTTY;
20344 		} else {
20345 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
20346 		}
20347 		break;
20348 
20349 	case CDROMSUBCODE:
20350 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
20351 		if (!ISCD(un)) {
20352 			err = ENOTTY;
20353 		} else {
20354 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
20355 		}
20356 		break;
20357 
20358 
20359 #ifdef SDDEBUG
20360 /* RESET/ABORTS testing ioctls */
20361 	case DKIOCRESET: {
20362 		int	reset_level;
20363 
20364 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
20365 			err = EFAULT;
20366 		} else {
20367 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
20368 			    "reset_level = 0x%lx\n", reset_level);
20369 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
20370 				err = 0;
20371 			} else {
20372 				err = EIO;
20373 			}
20374 		}
20375 		break;
20376 	}
20377 
20378 	case DKIOCABORT:
20379 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
20380 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
20381 			err = 0;
20382 		} else {
20383 			err = EIO;
20384 		}
20385 		break;
20386 #endif
20387 
20388 #ifdef SD_FAULT_INJECTION
20389 /* SDIOC FaultInjection testing ioctls */
20390 	case SDIOCSTART:
20391 	case SDIOCSTOP:
20392 	case SDIOCINSERTPKT:
20393 	case SDIOCINSERTXB:
20394 	case SDIOCINSERTUN:
20395 	case SDIOCINSERTARQ:
20396 	case SDIOCPUSH:
20397 	case SDIOCRETRIEVE:
20398 	case SDIOCRUN:
20399 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
20400 		    "SDIOC detected cmd:0x%X:\n", cmd);
20401 		/* call error generator */
20402 		sd_faultinjection_ioctl(cmd, arg, un);
20403 		err = 0;
20404 		break;
20405 
20406 #endif /* SD_FAULT_INJECTION */
20407 
20408 	case DKIOCFLUSHWRITECACHE:
20409 		{
20410 			struct dk_callback *dkc = (struct dk_callback *)arg;
20411 
20412 			mutex_enter(SD_MUTEX(un));
20413 			if (!un->un_f_sync_cache_supported ||
20414 			    !un->un_f_write_cache_enabled) {
20415 				err = un->un_f_sync_cache_supported ?
20416 				    0 : ENOTSUP;
20417 				mutex_exit(SD_MUTEX(un));
20418 				if ((flag & FKIOCTL) && dkc != NULL &&
20419 				    dkc->dkc_callback != NULL) {
20420 					(*dkc->dkc_callback)(dkc->dkc_cookie,
20421 					    err);
20422 					/*
20423 					 * Did callback and reported error.
20424 					 * Since we did a callback, ioctl
20425 					 * should return 0.
20426 					 */
20427 					err = 0;
20428 				}
20429 				break;
20430 			}
20431 			mutex_exit(SD_MUTEX(un));
20432 
20433 			if ((flag & FKIOCTL) && dkc != NULL &&
20434 			    dkc->dkc_callback != NULL) {
20435 				/* async SYNC CACHE request */
20436 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
20437 			} else {
20438 				/* synchronous SYNC CACHE request */
20439 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
20440 			}
20441 		}
20442 		break;
20443 
20444 	case DKIOCGETWCE: {
20445 
20446 		int wce;
20447 
20448 		if ((err = sd_get_write_cache_enabled(un, &wce)) != 0) {
20449 			break;
20450 		}
20451 
20452 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
20453 			err = EFAULT;
20454 		}
20455 		break;
20456 	}
20457 
20458 	case DKIOCSETWCE: {
20459 
20460 		int wce, sync_supported;
20461 
20462 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
20463 			err = EFAULT;
20464 			break;
20465 		}
20466 
20467 		/*
20468 		 * Synchronize multiple threads trying to enable
20469 		 * or disable the cache via the un_f_wcc_cv
20470 		 * condition variable.
20471 		 */
20472 		mutex_enter(SD_MUTEX(un));
20473 
20474 		/*
20475 		 * Don't allow the cache to be enabled if the
20476 		 * config file has it disabled.
20477 		 */
20478 		if (un->un_f_opt_disable_cache && wce) {
20479 			mutex_exit(SD_MUTEX(un));
20480 			err = EINVAL;
20481 			break;
20482 		}
20483 
20484 		/*
20485 		 * Wait for write cache change in progress
20486 		 * bit to be clear before proceeding.
20487 		 */
20488 		while (un->un_f_wcc_inprog)
20489 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
20490 
20491 		un->un_f_wcc_inprog = 1;
20492 
20493 		if (un->un_f_write_cache_enabled && wce == 0) {
20494 			/*
20495 			 * Disable the write cache.  Don't clear
20496 			 * un_f_write_cache_enabled until after
20497 			 * the mode select and flush are complete.
20498 			 */
20499 			sync_supported = un->un_f_sync_cache_supported;
20500 
20501 			/*
20502 			 * If cache flush is suppressed, we assume that the
20503 			 * controller firmware will take care of managing the
20504 			 * write cache for us: no need to explicitly
20505 			 * disable it.
20506 			 */
20507 			if (!un->un_f_suppress_cache_flush) {
20508 				mutex_exit(SD_MUTEX(un));
20509 				if ((err = sd_cache_control(un,
20510 				    SD_CACHE_NOCHANGE,
20511 				    SD_CACHE_DISABLE)) == 0 &&
20512 				    sync_supported) {
20513 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
20514 					    NULL);
20515 				}
20516 			} else {
20517 				mutex_exit(SD_MUTEX(un));
20518 			}
20519 
20520 			mutex_enter(SD_MUTEX(un));
20521 			if (err == 0) {
20522 				un->un_f_write_cache_enabled = 0;
20523 			}
20524 
20525 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
20526 			/*
20527 			 * Set un_f_write_cache_enabled first, so there is
20528 			 * no window where the cache is enabled, but the
20529 			 * bit says it isn't.
20530 			 */
20531 			un->un_f_write_cache_enabled = 1;
20532 
20533 			/*
20534 			 * If cache flush is suppressed, we assume that the
20535 			 * controller firmware will take care of managing the
20536 			 * write cache for us: no need to explicitly
20537 			 * enable it.
20538 			 */
20539 			if (!un->un_f_suppress_cache_flush) {
20540 				mutex_exit(SD_MUTEX(un));
20541 				err = sd_cache_control(un, SD_CACHE_NOCHANGE,
20542 				    SD_CACHE_ENABLE);
20543 			} else {
20544 				mutex_exit(SD_MUTEX(un));
20545 			}
20546 
20547 			mutex_enter(SD_MUTEX(un));
20548 
20549 			if (err) {
20550 				un->un_f_write_cache_enabled = 0;
20551 			}
20552 		}
20553 
20554 		un->un_f_wcc_inprog = 0;
20555 		cv_broadcast(&un->un_wcc_cv);
20556 		mutex_exit(SD_MUTEX(un));
20557 		break;
20558 	}
20559 
20560 	default:
20561 		err = ENOTTY;
20562 		break;
20563 	}
20564 	mutex_enter(SD_MUTEX(un));
20565 	un->un_ncmds_in_driver--;
20566 	ASSERT(un->un_ncmds_in_driver >= 0);
20567 	mutex_exit(SD_MUTEX(un));
20568 
20569 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
20570 	return (err);
20571 }
20572 
20573 
20574 /*
20575  *    Function: sd_dkio_ctrl_info
20576  *
20577  * Description: This routine is the driver entry point for handling controller
20578  *		information ioctl requests (DKIOCINFO).
20579  *
20580  *   Arguments: dev  - the device number
20581  *		arg  - pointer to user provided dk_cinfo structure
20582  *		       specifying the controller type and attributes.
20583  *		flag - this argument is a pass through to ddi_copyxxx()
20584  *		       directly from the mode argument of ioctl().
20585  *
20586  * Return Code: 0
20587  *		EFAULT
20588  *		ENXIO
20589  */
20590 
20591 static int
20592 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
20593 {
20594 	struct sd_lun	*un = NULL;
20595 	struct dk_cinfo	*info;
20596 	dev_info_t	*pdip;
20597 	int		lun, tgt;
20598 
20599 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20600 		return (ENXIO);
20601 	}
20602 
20603 	info = (struct dk_cinfo *)
20604 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
20605 
20606 	switch (un->un_ctype) {
20607 	case CTYPE_CDROM:
20608 		info->dki_ctype = DKC_CDROM;
20609 		break;
20610 	default:
20611 		info->dki_ctype = DKC_SCSI_CCS;
20612 		break;
20613 	}
20614 	pdip = ddi_get_parent(SD_DEVINFO(un));
20615 	info->dki_cnum = ddi_get_instance(pdip);
20616 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
20617 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
20618 	} else {
20619 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
20620 		    DK_DEVLEN - 1);
20621 	}
20622 
20623 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20624 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
20625 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20626 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
20627 
20628 	/* Unit Information */
20629 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
20630 	info->dki_slave = ((tgt << 3) | lun);
20631 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
20632 	    DK_DEVLEN - 1);
20633 	info->dki_flags = DKI_FMTVOL;
20634 	info->dki_partition = SDPART(dev);
20635 
20636 	/* Max Transfer size of this device in blocks */
20637 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
20638 	info->dki_addr = 0;
20639 	info->dki_space = 0;
20640 	info->dki_prio = 0;
20641 	info->dki_vec = 0;
20642 
20643 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
20644 		kmem_free(info, sizeof (struct dk_cinfo));
20645 		return (EFAULT);
20646 	} else {
20647 		kmem_free(info, sizeof (struct dk_cinfo));
20648 		return (0);
20649 	}
20650 }
20651 
20652 
20653 /*
20654  *    Function: sd_get_media_info
20655  *
20656  * Description: This routine is the driver entry point for handling ioctl
20657  *		requests for the media type or command set profile used by the
20658  *		drive to operate on the media (DKIOCGMEDIAINFO).
20659  *
20660  *   Arguments: dev	- the device number
20661  *		arg	- pointer to user provided dk_minfo structure
20662  *			  specifying the media type, logical block size and
20663  *			  drive capacity.
20664  *		flag	- this argument is a pass through to ddi_copyxxx()
20665  *			  directly from the mode argument of ioctl().
20666  *
20667  * Return Code: 0
20668  *		EACCESS
20669  *		EFAULT
20670  *		ENXIO
20671  *		EIO
20672  */
20673 
20674 static int
20675 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
20676 {
20677 	struct sd_lun		*un = NULL;
20678 	struct uscsi_cmd	com;
20679 	struct scsi_inquiry	*sinq;
20680 	struct dk_minfo		media_info;
20681 	u_longlong_t		media_capacity;
20682 	uint64_t		capacity;
20683 	uint_t			lbasize;
20684 	uchar_t			*out_data;
20685 	uchar_t			*rqbuf;
20686 	int			rval = 0;
20687 	int			rtn;
20688 
20689 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
20690 	    (un->un_state == SD_STATE_OFFLINE)) {
20691 		return (ENXIO);
20692 	}
20693 
20694 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info: entry\n");
20695 
20696 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
20697 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
20698 
20699 	/* Issue a TUR to determine if the drive is ready with media present */
20700 	rval = sd_send_scsi_TEST_UNIT_READY(un, SD_CHECK_FOR_MEDIA);
20701 	if (rval == ENXIO) {
20702 		goto done;
20703 	}
20704 
20705 	/* Now get configuration data */
20706 	if (ISCD(un)) {
20707 		media_info.dki_media_type = DK_CDROM;
20708 
20709 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
20710 		if (un->un_f_mmc_cap == TRUE) {
20711 			rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf,
20712 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
20713 			    SD_PATH_STANDARD);
20714 
20715 			if (rtn) {
20716 				/*
20717 				 * Failed for other than an illegal request
20718 				 * or command not supported
20719 				 */
20720 				if ((com.uscsi_status == STATUS_CHECK) &&
20721 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
20722 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
20723 					    (rqbuf[12] != 0x20)) {
20724 						rval = EIO;
20725 						goto done;
20726 					}
20727 				}
20728 			} else {
20729 				/*
20730 				 * The GET CONFIGURATION command succeeded
20731 				 * so set the media type according to the
20732 				 * returned data
20733 				 */
20734 				media_info.dki_media_type = out_data[6];
20735 				media_info.dki_media_type <<= 8;
20736 				media_info.dki_media_type |= out_data[7];
20737 			}
20738 		}
20739 	} else {
20740 		/*
20741 		 * The profile list is not available, so we attempt to identify
20742 		 * the media type based on the inquiry data
20743 		 */
20744 		sinq = un->un_sd->sd_inq;
20745 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
20746 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
20747 			/* This is a direct access device  or optical disk */
20748 			media_info.dki_media_type = DK_FIXED_DISK;
20749 
20750 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
20751 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
20752 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
20753 					media_info.dki_media_type = DK_ZIP;
20754 				} else if (
20755 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
20756 					media_info.dki_media_type = DK_JAZ;
20757 				}
20758 			}
20759 		} else {
20760 			/*
20761 			 * Not a CD, direct access or optical disk so return
20762 			 * unknown media
20763 			 */
20764 			media_info.dki_media_type = DK_UNKNOWN;
20765 		}
20766 	}
20767 
20768 	/* Now read the capacity so we can provide the lbasize and capacity */
20769 	switch (sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
20770 	    SD_PATH_DIRECT)) {
20771 	case 0:
20772 		break;
20773 	case EACCES:
20774 		rval = EACCES;
20775 		goto done;
20776 	default:
20777 		rval = EIO;
20778 		goto done;
20779 	}
20780 
20781 	media_info.dki_lbsize = lbasize;
20782 	media_capacity = capacity;
20783 
20784 	/*
20785 	 * sd_send_scsi_READ_CAPACITY() reports capacity in
20786 	 * un->un_sys_blocksize chunks. So we need to convert it into
20787 	 * cap.lbasize chunks.
20788 	 */
20789 	media_capacity *= un->un_sys_blocksize;
20790 	media_capacity /= lbasize;
20791 	media_info.dki_capacity = media_capacity;
20792 
20793 	if (ddi_copyout(&media_info, arg, sizeof (struct dk_minfo), flag)) {
20794 		rval = EFAULT;
20795 		/* Put goto. Anybody might add some code below in future */
20796 		goto done;
20797 	}
20798 done:
20799 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
20800 	kmem_free(rqbuf, SENSE_LENGTH);
20801 	return (rval);
20802 }
20803 
20804 
20805 /*
20806  *    Function: sd_check_media
20807  *
20808  * Description: This utility routine implements the functionality for the
20809  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
20810  *		driver state changes from that specified by the user
20811  *		(inserted or ejected). For example, if the user specifies
20812  *		DKIO_EJECTED and the current media state is inserted this
20813  *		routine will immediately return DKIO_INSERTED. However, if the
20814  *		current media state is not inserted the user thread will be
20815  *		blocked until the drive state changes. If DKIO_NONE is specified
20816  *		the user thread will block until a drive state change occurs.
20817  *
20818  *   Arguments: dev  - the device number
20819  *		state  - user pointer to a dkio_state, updated with the current
20820  *			drive state at return.
20821  *
20822  * Return Code: ENXIO
20823  *		EIO
20824  *		EAGAIN
20825  *		EINTR
20826  */
20827 
20828 static int
20829 sd_check_media(dev_t dev, enum dkio_state state)
20830 {
20831 	struct sd_lun		*un = NULL;
20832 	enum dkio_state		prev_state;
20833 	opaque_t		token = NULL;
20834 	int			rval = 0;
20835 
20836 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20837 		return (ENXIO);
20838 	}
20839 
20840 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
20841 
20842 	mutex_enter(SD_MUTEX(un));
20843 
20844 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
20845 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
20846 
20847 	prev_state = un->un_mediastate;
20848 
20849 	/* is there anything to do? */
20850 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
20851 		/*
20852 		 * submit the request to the scsi_watch service;
20853 		 * scsi_media_watch_cb() does the real work
20854 		 */
20855 		mutex_exit(SD_MUTEX(un));
20856 
20857 		/*
20858 		 * This change handles the case where a scsi watch request is
20859 		 * added to a device that is powered down. To accomplish this
20860 		 * we power up the device before adding the scsi watch request,
20861 		 * since the scsi watch sends a TUR directly to the device
20862 		 * which the device cannot handle if it is powered down.
20863 		 */
20864 		if (sd_pm_entry(un) != DDI_SUCCESS) {
20865 			mutex_enter(SD_MUTEX(un));
20866 			goto done;
20867 		}
20868 
20869 		token = scsi_watch_request_submit(SD_SCSI_DEVP(un),
20870 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
20871 		    (caddr_t)dev);
20872 
20873 		sd_pm_exit(un);
20874 
20875 		mutex_enter(SD_MUTEX(un));
20876 		if (token == NULL) {
20877 			rval = EAGAIN;
20878 			goto done;
20879 		}
20880 
20881 		/*
20882 		 * This is a special case IOCTL that doesn't return
20883 		 * until the media state changes. Routine sdpower
20884 		 * knows about and handles this so don't count it
20885 		 * as an active cmd in the driver, which would
20886 		 * keep the device busy to the pm framework.
20887 		 * If the count isn't decremented the device can't
20888 		 * be powered down.
20889 		 */
20890 		un->un_ncmds_in_driver--;
20891 		ASSERT(un->un_ncmds_in_driver >= 0);
20892 
20893 		/*
20894 		 * if a prior request had been made, this will be the same
20895 		 * token, as scsi_watch was designed that way.
20896 		 */
20897 		un->un_swr_token = token;
20898 		un->un_specified_mediastate = state;
20899 
20900 		/*
20901 		 * now wait for media change
20902 		 * we will not be signalled unless mediastate == state but it is
20903 		 * still better to test for this condition, since there is a
20904 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
20905 		 */
20906 		SD_TRACE(SD_LOG_COMMON, un,
20907 		    "sd_check_media: waiting for media state change\n");
20908 		while (un->un_mediastate == state) {
20909 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
20910 				SD_TRACE(SD_LOG_COMMON, un,
20911 				    "sd_check_media: waiting for media state "
20912 				    "was interrupted\n");
20913 				un->un_ncmds_in_driver++;
20914 				rval = EINTR;
20915 				goto done;
20916 			}
20917 			SD_TRACE(SD_LOG_COMMON, un,
20918 			    "sd_check_media: received signal, state=%x\n",
20919 			    un->un_mediastate);
20920 		}
20921 		/*
20922 		 * Inc the counter to indicate the device once again
20923 		 * has an active outstanding cmd.
20924 		 */
20925 		un->un_ncmds_in_driver++;
20926 	}
20927 
20928 	/* invalidate geometry */
20929 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
20930 		sr_ejected(un);
20931 	}
20932 
20933 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
20934 		uint64_t	capacity;
20935 		uint_t		lbasize;
20936 
20937 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
20938 		mutex_exit(SD_MUTEX(un));
20939 		/*
20940 		 * Since the following routines use SD_PATH_DIRECT, we must
20941 		 * call PM directly before the upcoming disk accesses. This
20942 		 * may cause the disk to be power/spin up.
20943 		 */
20944 
20945 		if (sd_pm_entry(un) == DDI_SUCCESS) {
20946 			rval = sd_send_scsi_READ_CAPACITY(un,
20947 			    &capacity,
20948 			    &lbasize, SD_PATH_DIRECT);
20949 			if (rval != 0) {
20950 				sd_pm_exit(un);
20951 				mutex_enter(SD_MUTEX(un));
20952 				goto done;
20953 			}
20954 		} else {
20955 			rval = EIO;
20956 			mutex_enter(SD_MUTEX(un));
20957 			goto done;
20958 		}
20959 		mutex_enter(SD_MUTEX(un));
20960 
20961 		sd_update_block_info(un, lbasize, capacity);
20962 
20963 		/*
20964 		 *  Check if the media in the device is writable or not
20965 		 */
20966 		if (ISCD(un))
20967 			sd_check_for_writable_cd(un, SD_PATH_DIRECT);
20968 
20969 		mutex_exit(SD_MUTEX(un));
20970 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
20971 		if ((cmlb_validate(un->un_cmlbhandle, 0,
20972 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
20973 			sd_set_pstats(un);
20974 			SD_TRACE(SD_LOG_IO_PARTITION, un,
20975 			    "sd_check_media: un:0x%p pstats created and "
20976 			    "set\n", un);
20977 		}
20978 
20979 		rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
20980 		    SD_PATH_DIRECT);
20981 		sd_pm_exit(un);
20982 
20983 		mutex_enter(SD_MUTEX(un));
20984 	}
20985 done:
20986 	un->un_f_watcht_stopped = FALSE;
20987 	if (un->un_swr_token) {
20988 		/*
20989 		 * Use of this local token and the mutex ensures that we avoid
20990 		 * some race conditions associated with terminating the
20991 		 * scsi watch.
20992 		 */
20993 		token = un->un_swr_token;
20994 		un->un_swr_token = (opaque_t)NULL;
20995 		mutex_exit(SD_MUTEX(un));
20996 		(void) scsi_watch_request_terminate(token,
20997 		    SCSI_WATCH_TERMINATE_WAIT);
20998 		mutex_enter(SD_MUTEX(un));
20999 	}
21000 
21001 	/*
21002 	 * Update the capacity kstat value, if no media previously
21003 	 * (capacity kstat is 0) and a media has been inserted
21004 	 * (un_f_blockcount_is_valid == TRUE)
21005 	 */
21006 	if (un->un_errstats) {
21007 		struct sd_errstats	*stp = NULL;
21008 
21009 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
21010 		if ((stp->sd_capacity.value.ui64 == 0) &&
21011 		    (un->un_f_blockcount_is_valid == TRUE)) {
21012 			stp->sd_capacity.value.ui64 =
21013 			    (uint64_t)((uint64_t)un->un_blockcount *
21014 			    un->un_sys_blocksize);
21015 		}
21016 	}
21017 	mutex_exit(SD_MUTEX(un));
21018 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
21019 	return (rval);
21020 }
21021 
21022 
21023 /*
21024  *    Function: sd_delayed_cv_broadcast
21025  *
21026  * Description: Delayed cv_broadcast to allow for target to recover from media
21027  *		insertion.
21028  *
21029  *   Arguments: arg - driver soft state (unit) structure
21030  */
21031 
21032 static void
21033 sd_delayed_cv_broadcast(void *arg)
21034 {
21035 	struct sd_lun *un = arg;
21036 
21037 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
21038 
21039 	mutex_enter(SD_MUTEX(un));
21040 	un->un_dcvb_timeid = NULL;
21041 	cv_broadcast(&un->un_state_cv);
21042 	mutex_exit(SD_MUTEX(un));
21043 }
21044 
21045 
21046 /*
21047  *    Function: sd_media_watch_cb
21048  *
21049  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
21050  *		routine processes the TUR sense data and updates the driver
21051  *		state if a transition has occurred. The user thread
21052  *		(sd_check_media) is then signalled.
21053  *
21054  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
21055  *			among multiple watches that share this callback function
21056  *		resultp - scsi watch facility result packet containing scsi
21057  *			  packet, status byte and sense data
21058  *
21059  * Return Code: 0 for success, -1 for failure
21060  */
21061 
21062 static int
21063 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
21064 {
21065 	struct sd_lun			*un;
21066 	struct scsi_status		*statusp = resultp->statusp;
21067 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
21068 	enum dkio_state			state = DKIO_NONE;
21069 	dev_t				dev = (dev_t)arg;
21070 	uchar_t				actual_sense_length;
21071 	uint8_t				skey, asc, ascq;
21072 
21073 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21074 		return (-1);
21075 	}
21076 	actual_sense_length = resultp->actual_sense_length;
21077 
21078 	mutex_enter(SD_MUTEX(un));
21079 	SD_TRACE(SD_LOG_COMMON, un,
21080 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
21081 	    *((char *)statusp), (void *)sensep, actual_sense_length);
21082 
21083 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
21084 		un->un_mediastate = DKIO_DEV_GONE;
21085 		cv_broadcast(&un->un_state_cv);
21086 		mutex_exit(SD_MUTEX(un));
21087 
21088 		return (0);
21089 	}
21090 
21091 	/*
21092 	 * If there was a check condition then sensep points to valid sense data
21093 	 * If status was not a check condition but a reservation or busy status
21094 	 * then the new state is DKIO_NONE
21095 	 */
21096 	if (sensep != NULL) {
21097 		skey = scsi_sense_key(sensep);
21098 		asc = scsi_sense_asc(sensep);
21099 		ascq = scsi_sense_ascq(sensep);
21100 
21101 		SD_INFO(SD_LOG_COMMON, un,
21102 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
21103 		    skey, asc, ascq);
21104 		/* This routine only uses up to 13 bytes of sense data. */
21105 		if (actual_sense_length >= 13) {
21106 			if (skey == KEY_UNIT_ATTENTION) {
21107 				if (asc == 0x28) {
21108 					state = DKIO_INSERTED;
21109 				}
21110 			} else if (skey == KEY_NOT_READY) {
21111 				/*
21112 				 * if 02/04/02  means that the host
21113 				 * should send start command. Explicitly
21114 				 * leave the media state as is
21115 				 * (inserted) as the media is inserted
21116 				 * and host has stopped device for PM
21117 				 * reasons. Upon next true read/write
21118 				 * to this media will bring the
21119 				 * device to the right state good for
21120 				 * media access.
21121 				 */
21122 				if (asc == 0x3a) {
21123 					state = DKIO_EJECTED;
21124 				} else {
21125 					/*
21126 					 * If the drive is busy with an
21127 					 * operation or long write, keep the
21128 					 * media in an inserted state.
21129 					 */
21130 
21131 					if ((asc == 0x04) &&
21132 					    ((ascq == 0x02) ||
21133 					    (ascq == 0x07) ||
21134 					    (ascq == 0x08))) {
21135 						state = DKIO_INSERTED;
21136 					}
21137 				}
21138 			} else if (skey == KEY_NO_SENSE) {
21139 				if ((asc == 0x00) && (ascq == 0x00)) {
21140 					/*
21141 					 * Sense Data 00/00/00 does not provide
21142 					 * any information about the state of
21143 					 * the media. Ignore it.
21144 					 */
21145 					mutex_exit(SD_MUTEX(un));
21146 					return (0);
21147 				}
21148 			}
21149 		}
21150 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
21151 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
21152 		state = DKIO_INSERTED;
21153 	}
21154 
21155 	SD_TRACE(SD_LOG_COMMON, un,
21156 	    "sd_media_watch_cb: state=%x, specified=%x\n",
21157 	    state, un->un_specified_mediastate);
21158 
21159 	/*
21160 	 * now signal the waiting thread if this is *not* the specified state;
21161 	 * delay the signal if the state is DKIO_INSERTED to allow the target
21162 	 * to recover
21163 	 */
21164 	if (state != un->un_specified_mediastate) {
21165 		un->un_mediastate = state;
21166 		if (state == DKIO_INSERTED) {
21167 			/*
21168 			 * delay the signal to give the drive a chance
21169 			 * to do what it apparently needs to do
21170 			 */
21171 			SD_TRACE(SD_LOG_COMMON, un,
21172 			    "sd_media_watch_cb: delayed cv_broadcast\n");
21173 			if (un->un_dcvb_timeid == NULL) {
21174 				un->un_dcvb_timeid =
21175 				    timeout(sd_delayed_cv_broadcast, un,
21176 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
21177 			}
21178 		} else {
21179 			SD_TRACE(SD_LOG_COMMON, un,
21180 			    "sd_media_watch_cb: immediate cv_broadcast\n");
21181 			cv_broadcast(&un->un_state_cv);
21182 		}
21183 	}
21184 	mutex_exit(SD_MUTEX(un));
21185 	return (0);
21186 }
21187 
21188 
21189 /*
21190  *    Function: sd_dkio_get_temp
21191  *
21192  * Description: This routine is the driver entry point for handling ioctl
21193  *		requests to get the disk temperature.
21194  *
21195  *   Arguments: dev  - the device number
21196  *		arg  - pointer to user provided dk_temperature structure.
21197  *		flag - this argument is a pass through to ddi_copyxxx()
21198  *		       directly from the mode argument of ioctl().
21199  *
21200  * Return Code: 0
21201  *		EFAULT
21202  *		ENXIO
21203  *		EAGAIN
21204  */
21205 
21206 static int
21207 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
21208 {
21209 	struct sd_lun		*un = NULL;
21210 	struct dk_temperature	*dktemp = NULL;
21211 	uchar_t			*temperature_page;
21212 	int			rval = 0;
21213 	int			path_flag = SD_PATH_STANDARD;
21214 
21215 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21216 		return (ENXIO);
21217 	}
21218 
21219 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
21220 
21221 	/* copyin the disk temp argument to get the user flags */
21222 	if (ddi_copyin((void *)arg, dktemp,
21223 	    sizeof (struct dk_temperature), flag) != 0) {
21224 		rval = EFAULT;
21225 		goto done;
21226 	}
21227 
21228 	/* Initialize the temperature to invalid. */
21229 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
21230 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
21231 
21232 	/*
21233 	 * Note: Investigate removing the "bypass pm" semantic.
21234 	 * Can we just bypass PM always?
21235 	 */
21236 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
21237 		path_flag = SD_PATH_DIRECT;
21238 		ASSERT(!mutex_owned(&un->un_pm_mutex));
21239 		mutex_enter(&un->un_pm_mutex);
21240 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
21241 			/*
21242 			 * If DKT_BYPASS_PM is set, and the drive happens to be
21243 			 * in low power mode, we can not wake it up, Need to
21244 			 * return EAGAIN.
21245 			 */
21246 			mutex_exit(&un->un_pm_mutex);
21247 			rval = EAGAIN;
21248 			goto done;
21249 		} else {
21250 			/*
21251 			 * Indicate to PM the device is busy. This is required
21252 			 * to avoid a race - i.e. the ioctl is issuing a
21253 			 * command and the pm framework brings down the device
21254 			 * to low power mode (possible power cut-off on some
21255 			 * platforms).
21256 			 */
21257 			mutex_exit(&un->un_pm_mutex);
21258 			if (sd_pm_entry(un) != DDI_SUCCESS) {
21259 				rval = EAGAIN;
21260 				goto done;
21261 			}
21262 		}
21263 	}
21264 
21265 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
21266 
21267 	if ((rval = sd_send_scsi_LOG_SENSE(un, temperature_page,
21268 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag)) != 0) {
21269 		goto done2;
21270 	}
21271 
21272 	/*
21273 	 * For the current temperature verify that the parameter length is 0x02
21274 	 * and the parameter code is 0x00
21275 	 */
21276 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
21277 	    (temperature_page[5] == 0x00)) {
21278 		if (temperature_page[9] == 0xFF) {
21279 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
21280 		} else {
21281 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
21282 		}
21283 	}
21284 
21285 	/*
21286 	 * For the reference temperature verify that the parameter
21287 	 * length is 0x02 and the parameter code is 0x01
21288 	 */
21289 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
21290 	    (temperature_page[11] == 0x01)) {
21291 		if (temperature_page[15] == 0xFF) {
21292 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
21293 		} else {
21294 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
21295 		}
21296 	}
21297 
21298 	/* Do the copyout regardless of the temperature commands status. */
21299 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
21300 	    flag) != 0) {
21301 		rval = EFAULT;
21302 	}
21303 
21304 done2:
21305 	if (path_flag == SD_PATH_DIRECT) {
21306 		sd_pm_exit(un);
21307 	}
21308 
21309 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
21310 done:
21311 	if (dktemp != NULL) {
21312 		kmem_free(dktemp, sizeof (struct dk_temperature));
21313 	}
21314 
21315 	return (rval);
21316 }
21317 
21318 
21319 /*
21320  *    Function: sd_log_page_supported
21321  *
21322  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
21323  *		supported log pages.
21324  *
21325  *   Arguments: un -
21326  *		log_page -
21327  *
21328  * Return Code: -1 - on error (log sense is optional and may not be supported).
21329  *		0  - log page not found.
21330  *  		1  - log page found.
21331  */
21332 
21333 static int
21334 sd_log_page_supported(struct sd_lun *un, int log_page)
21335 {
21336 	uchar_t *log_page_data;
21337 	int	i;
21338 	int	match = 0;
21339 	int	log_size;
21340 
21341 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
21342 
21343 	if (sd_send_scsi_LOG_SENSE(un, log_page_data, 0xFF, 0, 0x01, 0,
21344 	    SD_PATH_DIRECT) != 0) {
21345 		SD_ERROR(SD_LOG_COMMON, un,
21346 		    "sd_log_page_supported: failed log page retrieval\n");
21347 		kmem_free(log_page_data, 0xFF);
21348 		return (-1);
21349 	}
21350 	log_size = log_page_data[3];
21351 
21352 	/*
21353 	 * The list of supported log pages start from the fourth byte. Check
21354 	 * until we run out of log pages or a match is found.
21355 	 */
21356 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
21357 		if (log_page_data[i] == log_page) {
21358 			match++;
21359 		}
21360 	}
21361 	kmem_free(log_page_data, 0xFF);
21362 	return (match);
21363 }
21364 
21365 
21366 /*
21367  *    Function: sd_mhdioc_failfast
21368  *
21369  * Description: This routine is the driver entry point for handling ioctl
21370  *		requests to enable/disable the multihost failfast option.
21371  *		(MHIOCENFAILFAST)
21372  *
21373  *   Arguments: dev	- the device number
21374  *		arg	- user specified probing interval.
21375  *		flag	- this argument is a pass through to ddi_copyxxx()
21376  *			  directly from the mode argument of ioctl().
21377  *
21378  * Return Code: 0
21379  *		EFAULT
21380  *		ENXIO
21381  */
21382 
21383 static int
21384 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
21385 {
21386 	struct sd_lun	*un = NULL;
21387 	int		mh_time;
21388 	int		rval = 0;
21389 
21390 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21391 		return (ENXIO);
21392 	}
21393 
21394 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
21395 		return (EFAULT);
21396 
21397 	if (mh_time) {
21398 		mutex_enter(SD_MUTEX(un));
21399 		un->un_resvd_status |= SD_FAILFAST;
21400 		mutex_exit(SD_MUTEX(un));
21401 		/*
21402 		 * If mh_time is INT_MAX, then this ioctl is being used for
21403 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
21404 		 */
21405 		if (mh_time != INT_MAX) {
21406 			rval = sd_check_mhd(dev, mh_time);
21407 		}
21408 	} else {
21409 		(void) sd_check_mhd(dev, 0);
21410 		mutex_enter(SD_MUTEX(un));
21411 		un->un_resvd_status &= ~SD_FAILFAST;
21412 		mutex_exit(SD_MUTEX(un));
21413 	}
21414 	return (rval);
21415 }
21416 
21417 
21418 /*
21419  *    Function: sd_mhdioc_takeown
21420  *
21421  * Description: This routine is the driver entry point for handling ioctl
21422  *		requests to forcefully acquire exclusive access rights to the
21423  *		multihost disk (MHIOCTKOWN).
21424  *
21425  *   Arguments: dev	- the device number
21426  *		arg	- user provided structure specifying the delay
21427  *			  parameters in milliseconds
21428  *		flag	- this argument is a pass through to ddi_copyxxx()
21429  *			  directly from the mode argument of ioctl().
21430  *
21431  * Return Code: 0
21432  *		EFAULT
21433  *		ENXIO
21434  */
21435 
21436 static int
21437 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
21438 {
21439 	struct sd_lun		*un = NULL;
21440 	struct mhioctkown	*tkown = NULL;
21441 	int			rval = 0;
21442 
21443 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21444 		return (ENXIO);
21445 	}
21446 
21447 	if (arg != NULL) {
21448 		tkown = (struct mhioctkown *)
21449 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
21450 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
21451 		if (rval != 0) {
21452 			rval = EFAULT;
21453 			goto error;
21454 		}
21455 	}
21456 
21457 	rval = sd_take_ownership(dev, tkown);
21458 	mutex_enter(SD_MUTEX(un));
21459 	if (rval == 0) {
21460 		un->un_resvd_status |= SD_RESERVE;
21461 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
21462 			sd_reinstate_resv_delay =
21463 			    tkown->reinstate_resv_delay * 1000;
21464 		} else {
21465 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
21466 		}
21467 		/*
21468 		 * Give the scsi_watch routine interval set by
21469 		 * the MHIOCENFAILFAST ioctl precedence here.
21470 		 */
21471 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
21472 			mutex_exit(SD_MUTEX(un));
21473 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
21474 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
21475 			    "sd_mhdioc_takeown : %d\n",
21476 			    sd_reinstate_resv_delay);
21477 		} else {
21478 			mutex_exit(SD_MUTEX(un));
21479 		}
21480 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
21481 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21482 	} else {
21483 		un->un_resvd_status &= ~SD_RESERVE;
21484 		mutex_exit(SD_MUTEX(un));
21485 	}
21486 
21487 error:
21488 	if (tkown != NULL) {
21489 		kmem_free(tkown, sizeof (struct mhioctkown));
21490 	}
21491 	return (rval);
21492 }
21493 
21494 
21495 /*
21496  *    Function: sd_mhdioc_release
21497  *
21498  * Description: This routine is the driver entry point for handling ioctl
21499  *		requests to release exclusive access rights to the multihost
21500  *		disk (MHIOCRELEASE).
21501  *
21502  *   Arguments: dev	- the device number
21503  *
21504  * Return Code: 0
21505  *		ENXIO
21506  */
21507 
21508 static int
21509 sd_mhdioc_release(dev_t dev)
21510 {
21511 	struct sd_lun		*un = NULL;
21512 	timeout_id_t		resvd_timeid_save;
21513 	int			resvd_status_save;
21514 	int			rval = 0;
21515 
21516 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21517 		return (ENXIO);
21518 	}
21519 
21520 	mutex_enter(SD_MUTEX(un));
21521 	resvd_status_save = un->un_resvd_status;
21522 	un->un_resvd_status &=
21523 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
21524 	if (un->un_resvd_timeid) {
21525 		resvd_timeid_save = un->un_resvd_timeid;
21526 		un->un_resvd_timeid = NULL;
21527 		mutex_exit(SD_MUTEX(un));
21528 		(void) untimeout(resvd_timeid_save);
21529 	} else {
21530 		mutex_exit(SD_MUTEX(un));
21531 	}
21532 
21533 	/*
21534 	 * destroy any pending timeout thread that may be attempting to
21535 	 * reinstate reservation on this device.
21536 	 */
21537 	sd_rmv_resv_reclaim_req(dev);
21538 
21539 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
21540 		mutex_enter(SD_MUTEX(un));
21541 		if ((un->un_mhd_token) &&
21542 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
21543 			mutex_exit(SD_MUTEX(un));
21544 			(void) sd_check_mhd(dev, 0);
21545 		} else {
21546 			mutex_exit(SD_MUTEX(un));
21547 		}
21548 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
21549 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21550 	} else {
21551 		/*
21552 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
21553 		 */
21554 		mutex_enter(SD_MUTEX(un));
21555 		un->un_resvd_status = resvd_status_save;
21556 		mutex_exit(SD_MUTEX(un));
21557 	}
21558 	return (rval);
21559 }
21560 
21561 
21562 /*
21563  *    Function: sd_mhdioc_register_devid
21564  *
21565  * Description: This routine is the driver entry point for handling ioctl
21566  *		requests to register the device id (MHIOCREREGISTERDEVID).
21567  *
21568  *		Note: The implementation for this ioctl has been updated to
21569  *		be consistent with the original PSARC case (1999/357)
21570  *		(4375899, 4241671, 4220005)
21571  *
21572  *   Arguments: dev	- the device number
21573  *
21574  * Return Code: 0
21575  *		ENXIO
21576  */
21577 
21578 static int
21579 sd_mhdioc_register_devid(dev_t dev)
21580 {
21581 	struct sd_lun	*un = NULL;
21582 	int		rval = 0;
21583 
21584 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21585 		return (ENXIO);
21586 	}
21587 
21588 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21589 
21590 	mutex_enter(SD_MUTEX(un));
21591 
21592 	/* If a devid already exists, de-register it */
21593 	if (un->un_devid != NULL) {
21594 		ddi_devid_unregister(SD_DEVINFO(un));
21595 		/*
21596 		 * After unregister devid, needs to free devid memory
21597 		 */
21598 		ddi_devid_free(un->un_devid);
21599 		un->un_devid = NULL;
21600 	}
21601 
21602 	/* Check for reservation conflict */
21603 	mutex_exit(SD_MUTEX(un));
21604 	rval = sd_send_scsi_TEST_UNIT_READY(un, 0);
21605 	mutex_enter(SD_MUTEX(un));
21606 
21607 	switch (rval) {
21608 	case 0:
21609 		sd_register_devid(un, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
21610 		break;
21611 	case EACCES:
21612 		break;
21613 	default:
21614 		rval = EIO;
21615 	}
21616 
21617 	mutex_exit(SD_MUTEX(un));
21618 	return (rval);
21619 }
21620 
21621 
21622 /*
21623  *    Function: sd_mhdioc_inkeys
21624  *
21625  * Description: This routine is the driver entry point for handling ioctl
21626  *		requests to issue the SCSI-3 Persistent In Read Keys command
21627  *		to the device (MHIOCGRP_INKEYS).
21628  *
21629  *   Arguments: dev	- the device number
21630  *		arg	- user provided in_keys structure
21631  *		flag	- this argument is a pass through to ddi_copyxxx()
21632  *			  directly from the mode argument of ioctl().
21633  *
21634  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
21635  *		ENXIO
21636  *		EFAULT
21637  */
21638 
21639 static int
21640 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
21641 {
21642 	struct sd_lun		*un;
21643 	mhioc_inkeys_t		inkeys;
21644 	int			rval = 0;
21645 
21646 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21647 		return (ENXIO);
21648 	}
21649 
21650 #ifdef _MULTI_DATAMODEL
21651 	switch (ddi_model_convert_from(flag & FMODELS)) {
21652 	case DDI_MODEL_ILP32: {
21653 		struct mhioc_inkeys32	inkeys32;
21654 
21655 		if (ddi_copyin(arg, &inkeys32,
21656 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
21657 			return (EFAULT);
21658 		}
21659 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
21660 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21661 		    &inkeys, flag)) != 0) {
21662 			return (rval);
21663 		}
21664 		inkeys32.generation = inkeys.generation;
21665 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
21666 		    flag) != 0) {
21667 			return (EFAULT);
21668 		}
21669 		break;
21670 	}
21671 	case DDI_MODEL_NONE:
21672 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
21673 		    flag) != 0) {
21674 			return (EFAULT);
21675 		}
21676 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21677 		    &inkeys, flag)) != 0) {
21678 			return (rval);
21679 		}
21680 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
21681 		    flag) != 0) {
21682 			return (EFAULT);
21683 		}
21684 		break;
21685 	}
21686 
21687 #else /* ! _MULTI_DATAMODEL */
21688 
21689 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
21690 		return (EFAULT);
21691 	}
21692 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
21693 	if (rval != 0) {
21694 		return (rval);
21695 	}
21696 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
21697 		return (EFAULT);
21698 	}
21699 
21700 #endif /* _MULTI_DATAMODEL */
21701 
21702 	return (rval);
21703 }
21704 
21705 
21706 /*
21707  *    Function: sd_mhdioc_inresv
21708  *
21709  * Description: This routine is the driver entry point for handling ioctl
21710  *		requests to issue the SCSI-3 Persistent In Read Reservations
21711  *		command to the device (MHIOCGRP_INKEYS).
21712  *
21713  *   Arguments: dev	- the device number
21714  *		arg	- user provided in_resv structure
21715  *		flag	- this argument is a pass through to ddi_copyxxx()
21716  *			  directly from the mode argument of ioctl().
21717  *
21718  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
21719  *		ENXIO
21720  *		EFAULT
21721  */
21722 
21723 static int
21724 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
21725 {
21726 	struct sd_lun		*un;
21727 	mhioc_inresvs_t		inresvs;
21728 	int			rval = 0;
21729 
21730 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21731 		return (ENXIO);
21732 	}
21733 
21734 #ifdef _MULTI_DATAMODEL
21735 
21736 	switch (ddi_model_convert_from(flag & FMODELS)) {
21737 	case DDI_MODEL_ILP32: {
21738 		struct mhioc_inresvs32	inresvs32;
21739 
21740 		if (ddi_copyin(arg, &inresvs32,
21741 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21742 			return (EFAULT);
21743 		}
21744 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
21745 		if ((rval = sd_persistent_reservation_in_read_resv(un,
21746 		    &inresvs, flag)) != 0) {
21747 			return (rval);
21748 		}
21749 		inresvs32.generation = inresvs.generation;
21750 		if (ddi_copyout(&inresvs32, arg,
21751 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21752 			return (EFAULT);
21753 		}
21754 		break;
21755 	}
21756 	case DDI_MODEL_NONE:
21757 		if (ddi_copyin(arg, &inresvs,
21758 		    sizeof (mhioc_inresvs_t), flag) != 0) {
21759 			return (EFAULT);
21760 		}
21761 		if ((rval = sd_persistent_reservation_in_read_resv(un,
21762 		    &inresvs, flag)) != 0) {
21763 			return (rval);
21764 		}
21765 		if (ddi_copyout(&inresvs, arg,
21766 		    sizeof (mhioc_inresvs_t), flag) != 0) {
21767 			return (EFAULT);
21768 		}
21769 		break;
21770 	}
21771 
21772 #else /* ! _MULTI_DATAMODEL */
21773 
21774 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
21775 		return (EFAULT);
21776 	}
21777 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
21778 	if (rval != 0) {
21779 		return (rval);
21780 	}
21781 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
21782 		return (EFAULT);
21783 	}
21784 
21785 #endif /* ! _MULTI_DATAMODEL */
21786 
21787 	return (rval);
21788 }
21789 
21790 
21791 /*
21792  * The following routines support the clustering functionality described below
21793  * and implement lost reservation reclaim functionality.
21794  *
21795  * Clustering
21796  * ----------
21797  * The clustering code uses two different, independent forms of SCSI
21798  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
21799  * Persistent Group Reservations. For any particular disk, it will use either
21800  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
21801  *
21802  * SCSI-2
21803  * The cluster software takes ownership of a multi-hosted disk by issuing the
21804  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
21805  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
21806  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
21807  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
21808  * driver. The meaning of failfast is that if the driver (on this host) ever
21809  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
21810  * it should immediately panic the host. The motivation for this ioctl is that
21811  * if this host does encounter reservation conflict, the underlying cause is
21812  * that some other host of the cluster has decided that this host is no longer
21813  * in the cluster and has seized control of the disks for itself. Since this
21814  * host is no longer in the cluster, it ought to panic itself. The
21815  * MHIOCENFAILFAST ioctl does two things:
21816  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
21817  *      error to panic the host
21818  *      (b) it sets up a periodic timer to test whether this host still has
21819  *      "access" (in that no other host has reserved the device):  if the
21820  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
21821  *      purpose of that periodic timer is to handle scenarios where the host is
21822  *      otherwise temporarily quiescent, temporarily doing no real i/o.
21823  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
21824  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
21825  * the device itself.
21826  *
21827  * SCSI-3 PGR
21828  * A direct semantic implementation of the SCSI-3 Persistent Reservation
21829  * facility is supported through the shared multihost disk ioctls
21830  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
21831  * MHIOCGRP_PREEMPTANDABORT)
21832  *
21833  * Reservation Reclaim:
21834  * --------------------
21835  * To support the lost reservation reclaim operations this driver creates a
21836  * single thread to handle reinstating reservations on all devices that have
21837  * lost reservations sd_resv_reclaim_requests are logged for all devices that
21838  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
21839  * and the reservation reclaim thread loops through the requests to regain the
21840  * lost reservations.
21841  */
21842 
21843 /*
21844  *    Function: sd_check_mhd()
21845  *
21846  * Description: This function sets up and submits a scsi watch request or
21847  *		terminates an existing watch request. This routine is used in
21848  *		support of reservation reclaim.
21849  *
21850  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
21851  *			 among multiple watches that share the callback function
21852  *		interval - the number of microseconds specifying the watch
21853  *			   interval for issuing TEST UNIT READY commands. If
21854  *			   set to 0 the watch should be terminated. If the
21855  *			   interval is set to 0 and if the device is required
21856  *			   to hold reservation while disabling failfast, the
21857  *			   watch is restarted with an interval of
21858  *			   reinstate_resv_delay.
21859  *
21860  * Return Code: 0	   - Successful submit/terminate of scsi watch request
21861  *		ENXIO      - Indicates an invalid device was specified
21862  *		EAGAIN     - Unable to submit the scsi watch request
21863  */
21864 
21865 static int
21866 sd_check_mhd(dev_t dev, int interval)
21867 {
21868 	struct sd_lun	*un;
21869 	opaque_t	token;
21870 
21871 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21872 		return (ENXIO);
21873 	}
21874 
21875 	/* is this a watch termination request? */
21876 	if (interval == 0) {
21877 		mutex_enter(SD_MUTEX(un));
21878 		/* if there is an existing watch task then terminate it */
21879 		if (un->un_mhd_token) {
21880 			token = un->un_mhd_token;
21881 			un->un_mhd_token = NULL;
21882 			mutex_exit(SD_MUTEX(un));
21883 			(void) scsi_watch_request_terminate(token,
21884 			    SCSI_WATCH_TERMINATE_WAIT);
21885 			mutex_enter(SD_MUTEX(un));
21886 		} else {
21887 			mutex_exit(SD_MUTEX(un));
21888 			/*
21889 			 * Note: If we return here we don't check for the
21890 			 * failfast case. This is the original legacy
21891 			 * implementation but perhaps we should be checking
21892 			 * the failfast case.
21893 			 */
21894 			return (0);
21895 		}
21896 		/*
21897 		 * If the device is required to hold reservation while
21898 		 * disabling failfast, we need to restart the scsi_watch
21899 		 * routine with an interval of reinstate_resv_delay.
21900 		 */
21901 		if (un->un_resvd_status & SD_RESERVE) {
21902 			interval = sd_reinstate_resv_delay/1000;
21903 		} else {
21904 			/* no failfast so bail */
21905 			mutex_exit(SD_MUTEX(un));
21906 			return (0);
21907 		}
21908 		mutex_exit(SD_MUTEX(un));
21909 	}
21910 
21911 	/*
21912 	 * adjust minimum time interval to 1 second,
21913 	 * and convert from msecs to usecs
21914 	 */
21915 	if (interval > 0 && interval < 1000) {
21916 		interval = 1000;
21917 	}
21918 	interval *= 1000;
21919 
21920 	/*
21921 	 * submit the request to the scsi_watch service
21922 	 */
21923 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
21924 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
21925 	if (token == NULL) {
21926 		return (EAGAIN);
21927 	}
21928 
21929 	/*
21930 	 * save token for termination later on
21931 	 */
21932 	mutex_enter(SD_MUTEX(un));
21933 	un->un_mhd_token = token;
21934 	mutex_exit(SD_MUTEX(un));
21935 	return (0);
21936 }
21937 
21938 
21939 /*
21940  *    Function: sd_mhd_watch_cb()
21941  *
21942  * Description: This function is the call back function used by the scsi watch
21943  *		facility. The scsi watch facility sends the "Test Unit Ready"
21944  *		and processes the status. If applicable (i.e. a "Unit Attention"
21945  *		status and automatic "Request Sense" not used) the scsi watch
21946  *		facility will send a "Request Sense" and retrieve the sense data
21947  *		to be passed to this callback function. In either case the
21948  *		automatic "Request Sense" or the facility submitting one, this
21949  *		callback is passed the status and sense data.
21950  *
21951  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
21952  *			among multiple watches that share this callback function
21953  *		resultp - scsi watch facility result packet containing scsi
21954  *			  packet, status byte and sense data
21955  *
21956  * Return Code: 0 - continue the watch task
21957  *		non-zero - terminate the watch task
21958  */
21959 
21960 static int
21961 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
21962 {
21963 	struct sd_lun			*un;
21964 	struct scsi_status		*statusp;
21965 	uint8_t				*sensep;
21966 	struct scsi_pkt			*pkt;
21967 	uchar_t				actual_sense_length;
21968 	dev_t  				dev = (dev_t)arg;
21969 
21970 	ASSERT(resultp != NULL);
21971 	statusp			= resultp->statusp;
21972 	sensep			= (uint8_t *)resultp->sensep;
21973 	pkt			= resultp->pkt;
21974 	actual_sense_length	= resultp->actual_sense_length;
21975 
21976 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21977 		return (ENXIO);
21978 	}
21979 
21980 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
21981 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
21982 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
21983 
21984 	/* Begin processing of the status and/or sense data */
21985 	if (pkt->pkt_reason != CMD_CMPLT) {
21986 		/* Handle the incomplete packet */
21987 		sd_mhd_watch_incomplete(un, pkt);
21988 		return (0);
21989 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
21990 		if (*((unsigned char *)statusp)
21991 		    == STATUS_RESERVATION_CONFLICT) {
21992 			/*
21993 			 * Handle a reservation conflict by panicking if
21994 			 * configured for failfast or by logging the conflict
21995 			 * and updating the reservation status
21996 			 */
21997 			mutex_enter(SD_MUTEX(un));
21998 			if ((un->un_resvd_status & SD_FAILFAST) &&
21999 			    (sd_failfast_enable)) {
22000 				sd_panic_for_res_conflict(un);
22001 				/*NOTREACHED*/
22002 			}
22003 			SD_INFO(SD_LOG_IOCTL_MHD, un,
22004 			    "sd_mhd_watch_cb: Reservation Conflict\n");
22005 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
22006 			mutex_exit(SD_MUTEX(un));
22007 		}
22008 	}
22009 
22010 	if (sensep != NULL) {
22011 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
22012 			mutex_enter(SD_MUTEX(un));
22013 			if ((scsi_sense_asc(sensep) ==
22014 			    SD_SCSI_RESET_SENSE_CODE) &&
22015 			    (un->un_resvd_status & SD_RESERVE)) {
22016 				/*
22017 				 * The additional sense code indicates a power
22018 				 * on or bus device reset has occurred; update
22019 				 * the reservation status.
22020 				 */
22021 				un->un_resvd_status |=
22022 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
22023 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22024 				    "sd_mhd_watch_cb: Lost Reservation\n");
22025 			}
22026 		} else {
22027 			return (0);
22028 		}
22029 	} else {
22030 		mutex_enter(SD_MUTEX(un));
22031 	}
22032 
22033 	if ((un->un_resvd_status & SD_RESERVE) &&
22034 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
22035 		if (un->un_resvd_status & SD_WANT_RESERVE) {
22036 			/*
22037 			 * A reset occurred in between the last probe and this
22038 			 * one so if a timeout is pending cancel it.
22039 			 */
22040 			if (un->un_resvd_timeid) {
22041 				timeout_id_t temp_id = un->un_resvd_timeid;
22042 				un->un_resvd_timeid = NULL;
22043 				mutex_exit(SD_MUTEX(un));
22044 				(void) untimeout(temp_id);
22045 				mutex_enter(SD_MUTEX(un));
22046 			}
22047 			un->un_resvd_status &= ~SD_WANT_RESERVE;
22048 		}
22049 		if (un->un_resvd_timeid == 0) {
22050 			/* Schedule a timeout to handle the lost reservation */
22051 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
22052 			    (void *)dev,
22053 			    drv_usectohz(sd_reinstate_resv_delay));
22054 		}
22055 	}
22056 	mutex_exit(SD_MUTEX(un));
22057 	return (0);
22058 }
22059 
22060 
22061 /*
22062  *    Function: sd_mhd_watch_incomplete()
22063  *
22064  * Description: This function is used to find out why a scsi pkt sent by the
22065  *		scsi watch facility was not completed. Under some scenarios this
22066  *		routine will return. Otherwise it will send a bus reset to see
22067  *		if the drive is still online.
22068  *
22069  *   Arguments: un  - driver soft state (unit) structure
22070  *		pkt - incomplete scsi pkt
22071  */
22072 
22073 static void
22074 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
22075 {
22076 	int	be_chatty;
22077 	int	perr;
22078 
22079 	ASSERT(pkt != NULL);
22080 	ASSERT(un != NULL);
22081 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
22082 	perr		= (pkt->pkt_statistics & STAT_PERR);
22083 
22084 	mutex_enter(SD_MUTEX(un));
22085 	if (un->un_state == SD_STATE_DUMPING) {
22086 		mutex_exit(SD_MUTEX(un));
22087 		return;
22088 	}
22089 
22090 	switch (pkt->pkt_reason) {
22091 	case CMD_UNX_BUS_FREE:
22092 		/*
22093 		 * If we had a parity error that caused the target to drop BSY*,
22094 		 * don't be chatty about it.
22095 		 */
22096 		if (perr && be_chatty) {
22097 			be_chatty = 0;
22098 		}
22099 		break;
22100 	case CMD_TAG_REJECT:
22101 		/*
22102 		 * The SCSI-2 spec states that a tag reject will be sent by the
22103 		 * target if tagged queuing is not supported. A tag reject may
22104 		 * also be sent during certain initialization periods or to
22105 		 * control internal resources. For the latter case the target
22106 		 * may also return Queue Full.
22107 		 *
22108 		 * If this driver receives a tag reject from a target that is
22109 		 * going through an init period or controlling internal
22110 		 * resources tagged queuing will be disabled. This is a less
22111 		 * than optimal behavior but the driver is unable to determine
22112 		 * the target state and assumes tagged queueing is not supported
22113 		 */
22114 		pkt->pkt_flags = 0;
22115 		un->un_tagflags = 0;
22116 
22117 		if (un->un_f_opt_queueing == TRUE) {
22118 			un->un_throttle = min(un->un_throttle, 3);
22119 		} else {
22120 			un->un_throttle = 1;
22121 		}
22122 		mutex_exit(SD_MUTEX(un));
22123 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
22124 		mutex_enter(SD_MUTEX(un));
22125 		break;
22126 	case CMD_INCOMPLETE:
22127 		/*
22128 		 * The transport stopped with an abnormal state, fallthrough and
22129 		 * reset the target and/or bus unless selection did not complete
22130 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
22131 		 * go through a target/bus reset
22132 		 */
22133 		if (pkt->pkt_state == STATE_GOT_BUS) {
22134 			break;
22135 		}
22136 		/*FALLTHROUGH*/
22137 
22138 	case CMD_TIMEOUT:
22139 	default:
22140 		/*
22141 		 * The lun may still be running the command, so a lun reset
22142 		 * should be attempted. If the lun reset fails or cannot be
22143 		 * issued, than try a target reset. Lastly try a bus reset.
22144 		 */
22145 		if ((pkt->pkt_statistics &
22146 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
22147 			int reset_retval = 0;
22148 			mutex_exit(SD_MUTEX(un));
22149 			if (un->un_f_allow_bus_device_reset == TRUE) {
22150 				if (un->un_f_lun_reset_enabled == TRUE) {
22151 					reset_retval =
22152 					    scsi_reset(SD_ADDRESS(un),
22153 					    RESET_LUN);
22154 				}
22155 				if (reset_retval == 0) {
22156 					reset_retval =
22157 					    scsi_reset(SD_ADDRESS(un),
22158 					    RESET_TARGET);
22159 				}
22160 			}
22161 			if (reset_retval == 0) {
22162 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
22163 			}
22164 			mutex_enter(SD_MUTEX(un));
22165 		}
22166 		break;
22167 	}
22168 
22169 	/* A device/bus reset has occurred; update the reservation status. */
22170 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
22171 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
22172 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22173 			un->un_resvd_status |=
22174 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
22175 			SD_INFO(SD_LOG_IOCTL_MHD, un,
22176 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
22177 		}
22178 	}
22179 
22180 	/*
22181 	 * The disk has been turned off; Update the device state.
22182 	 *
22183 	 * Note: Should we be offlining the disk here?
22184 	 */
22185 	if (pkt->pkt_state == STATE_GOT_BUS) {
22186 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
22187 		    "Disk not responding to selection\n");
22188 		if (un->un_state != SD_STATE_OFFLINE) {
22189 			New_state(un, SD_STATE_OFFLINE);
22190 		}
22191 	} else if (be_chatty) {
22192 		/*
22193 		 * suppress messages if they are all the same pkt reason;
22194 		 * with TQ, many (up to 256) are returned with the same
22195 		 * pkt_reason
22196 		 */
22197 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
22198 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
22199 			    "sd_mhd_watch_incomplete: "
22200 			    "SCSI transport failed: reason '%s'\n",
22201 			    scsi_rname(pkt->pkt_reason));
22202 		}
22203 	}
22204 	un->un_last_pkt_reason = pkt->pkt_reason;
22205 	mutex_exit(SD_MUTEX(un));
22206 }
22207 
22208 
22209 /*
22210  *    Function: sd_sname()
22211  *
22212  * Description: This is a simple little routine to return a string containing
22213  *		a printable description of command status byte for use in
22214  *		logging.
22215  *
22216  *   Arguments: status - pointer to a status byte
22217  *
22218  * Return Code: char * - string containing status description.
22219  */
22220 
22221 static char *
22222 sd_sname(uchar_t status)
22223 {
22224 	switch (status & STATUS_MASK) {
22225 	case STATUS_GOOD:
22226 		return ("good status");
22227 	case STATUS_CHECK:
22228 		return ("check condition");
22229 	case STATUS_MET:
22230 		return ("condition met");
22231 	case STATUS_BUSY:
22232 		return ("busy");
22233 	case STATUS_INTERMEDIATE:
22234 		return ("intermediate");
22235 	case STATUS_INTERMEDIATE_MET:
22236 		return ("intermediate - condition met");
22237 	case STATUS_RESERVATION_CONFLICT:
22238 		return ("reservation_conflict");
22239 	case STATUS_TERMINATED:
22240 		return ("command terminated");
22241 	case STATUS_QFULL:
22242 		return ("queue full");
22243 	default:
22244 		return ("<unknown status>");
22245 	}
22246 }
22247 
22248 
22249 /*
22250  *    Function: sd_mhd_resvd_recover()
22251  *
22252  * Description: This function adds a reservation entry to the
22253  *		sd_resv_reclaim_request list and signals the reservation
22254  *		reclaim thread that there is work pending. If the reservation
22255  *		reclaim thread has not been previously created this function
22256  *		will kick it off.
22257  *
22258  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
22259  *			among multiple watches that share this callback function
22260  *
22261  *     Context: This routine is called by timeout() and is run in interrupt
22262  *		context. It must not sleep or call other functions which may
22263  *		sleep.
22264  */
22265 
22266 static void
22267 sd_mhd_resvd_recover(void *arg)
22268 {
22269 	dev_t			dev = (dev_t)arg;
22270 	struct sd_lun		*un;
22271 	struct sd_thr_request	*sd_treq = NULL;
22272 	struct sd_thr_request	*sd_cur = NULL;
22273 	struct sd_thr_request	*sd_prev = NULL;
22274 	int			already_there = 0;
22275 
22276 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22277 		return;
22278 	}
22279 
22280 	mutex_enter(SD_MUTEX(un));
22281 	un->un_resvd_timeid = NULL;
22282 	if (un->un_resvd_status & SD_WANT_RESERVE) {
22283 		/*
22284 		 * There was a reset so don't issue the reserve, allow the
22285 		 * sd_mhd_watch_cb callback function to notice this and
22286 		 * reschedule the timeout for reservation.
22287 		 */
22288 		mutex_exit(SD_MUTEX(un));
22289 		return;
22290 	}
22291 	mutex_exit(SD_MUTEX(un));
22292 
22293 	/*
22294 	 * Add this device to the sd_resv_reclaim_request list and the
22295 	 * sd_resv_reclaim_thread should take care of the rest.
22296 	 *
22297 	 * Note: We can't sleep in this context so if the memory allocation
22298 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
22299 	 * reschedule the timeout for reservation.  (4378460)
22300 	 */
22301 	sd_treq = (struct sd_thr_request *)
22302 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
22303 	if (sd_treq == NULL) {
22304 		return;
22305 	}
22306 
22307 	sd_treq->sd_thr_req_next = NULL;
22308 	sd_treq->dev = dev;
22309 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22310 	if (sd_tr.srq_thr_req_head == NULL) {
22311 		sd_tr.srq_thr_req_head = sd_treq;
22312 	} else {
22313 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
22314 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
22315 			if (sd_cur->dev == dev) {
22316 				/*
22317 				 * already in Queue so don't log
22318 				 * another request for the device
22319 				 */
22320 				already_there = 1;
22321 				break;
22322 			}
22323 			sd_prev = sd_cur;
22324 		}
22325 		if (!already_there) {
22326 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
22327 			    "logging request for %lx\n", dev);
22328 			sd_prev->sd_thr_req_next = sd_treq;
22329 		} else {
22330 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
22331 		}
22332 	}
22333 
22334 	/*
22335 	 * Create a kernel thread to do the reservation reclaim and free up this
22336 	 * thread. We cannot block this thread while we go away to do the
22337 	 * reservation reclaim
22338 	 */
22339 	if (sd_tr.srq_resv_reclaim_thread == NULL)
22340 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
22341 		    sd_resv_reclaim_thread, NULL,
22342 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
22343 
22344 	/* Tell the reservation reclaim thread that it has work to do */
22345 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
22346 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22347 }
22348 
22349 /*
22350  *    Function: sd_resv_reclaim_thread()
22351  *
22352  * Description: This function implements the reservation reclaim operations
22353  *
22354  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
22355  *		      among multiple watches that share this callback function
22356  */
22357 
22358 static void
22359 sd_resv_reclaim_thread()
22360 {
22361 	struct sd_lun		*un;
22362 	struct sd_thr_request	*sd_mhreq;
22363 
22364 	/* Wait for work */
22365 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22366 	if (sd_tr.srq_thr_req_head == NULL) {
22367 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
22368 		    &sd_tr.srq_resv_reclaim_mutex);
22369 	}
22370 
22371 	/* Loop while we have work */
22372 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
22373 		un = ddi_get_soft_state(sd_state,
22374 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
22375 		if (un == NULL) {
22376 			/*
22377 			 * softstate structure is NULL so just
22378 			 * dequeue the request and continue
22379 			 */
22380 			sd_tr.srq_thr_req_head =
22381 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22382 			kmem_free(sd_tr.srq_thr_cur_req,
22383 			    sizeof (struct sd_thr_request));
22384 			continue;
22385 		}
22386 
22387 		/* dequeue the request */
22388 		sd_mhreq = sd_tr.srq_thr_cur_req;
22389 		sd_tr.srq_thr_req_head =
22390 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22391 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22392 
22393 		/*
22394 		 * Reclaim reservation only if SD_RESERVE is still set. There
22395 		 * may have been a call to MHIOCRELEASE before we got here.
22396 		 */
22397 		mutex_enter(SD_MUTEX(un));
22398 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22399 			/*
22400 			 * Note: The SD_LOST_RESERVE flag is cleared before
22401 			 * reclaiming the reservation. If this is done after the
22402 			 * call to sd_reserve_release a reservation loss in the
22403 			 * window between pkt completion of reserve cmd and
22404 			 * mutex_enter below may not be recognized
22405 			 */
22406 			un->un_resvd_status &= ~SD_LOST_RESERVE;
22407 			mutex_exit(SD_MUTEX(un));
22408 
22409 			if (sd_reserve_release(sd_mhreq->dev,
22410 			    SD_RESERVE) == 0) {
22411 				mutex_enter(SD_MUTEX(un));
22412 				un->un_resvd_status |= SD_RESERVE;
22413 				mutex_exit(SD_MUTEX(un));
22414 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22415 				    "sd_resv_reclaim_thread: "
22416 				    "Reservation Recovered\n");
22417 			} else {
22418 				mutex_enter(SD_MUTEX(un));
22419 				un->un_resvd_status |= SD_LOST_RESERVE;
22420 				mutex_exit(SD_MUTEX(un));
22421 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22422 				    "sd_resv_reclaim_thread: Failed "
22423 				    "Reservation Recovery\n");
22424 			}
22425 		} else {
22426 			mutex_exit(SD_MUTEX(un));
22427 		}
22428 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22429 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
22430 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22431 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
22432 		/*
22433 		 * wakeup the destroy thread if anyone is waiting on
22434 		 * us to complete.
22435 		 */
22436 		cv_signal(&sd_tr.srq_inprocess_cv);
22437 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
22438 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
22439 	}
22440 
22441 	/*
22442 	 * cleanup the sd_tr structure now that this thread will not exist
22443 	 */
22444 	ASSERT(sd_tr.srq_thr_req_head == NULL);
22445 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
22446 	sd_tr.srq_resv_reclaim_thread = NULL;
22447 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22448 	thread_exit();
22449 }
22450 
22451 
22452 /*
22453  *    Function: sd_rmv_resv_reclaim_req()
22454  *
22455  * Description: This function removes any pending reservation reclaim requests
22456  *		for the specified device.
22457  *
22458  *   Arguments: dev - the device 'dev_t'
22459  */
22460 
22461 static void
22462 sd_rmv_resv_reclaim_req(dev_t dev)
22463 {
22464 	struct sd_thr_request *sd_mhreq;
22465 	struct sd_thr_request *sd_prev;
22466 
22467 	/* Remove a reservation reclaim request from the list */
22468 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22469 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
22470 		/*
22471 		 * We are attempting to reinstate reservation for
22472 		 * this device. We wait for sd_reserve_release()
22473 		 * to return before we return.
22474 		 */
22475 		cv_wait(&sd_tr.srq_inprocess_cv,
22476 		    &sd_tr.srq_resv_reclaim_mutex);
22477 	} else {
22478 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
22479 		if (sd_mhreq && sd_mhreq->dev == dev) {
22480 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
22481 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22482 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22483 			return;
22484 		}
22485 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
22486 			if (sd_mhreq && sd_mhreq->dev == dev) {
22487 				break;
22488 			}
22489 			sd_prev = sd_mhreq;
22490 		}
22491 		if (sd_mhreq != NULL) {
22492 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
22493 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22494 		}
22495 	}
22496 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22497 }
22498 
22499 
22500 /*
22501  *    Function: sd_mhd_reset_notify_cb()
22502  *
22503  * Description: This is a call back function for scsi_reset_notify. This
22504  *		function updates the softstate reserved status and logs the
22505  *		reset. The driver scsi watch facility callback function
22506  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
22507  *		will reclaim the reservation.
22508  *
22509  *   Arguments: arg  - driver soft state (unit) structure
22510  */
22511 
22512 static void
22513 sd_mhd_reset_notify_cb(caddr_t arg)
22514 {
22515 	struct sd_lun *un = (struct sd_lun *)arg;
22516 
22517 	mutex_enter(SD_MUTEX(un));
22518 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22519 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
22520 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22521 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
22522 	}
22523 	mutex_exit(SD_MUTEX(un));
22524 }
22525 
22526 
22527 /*
22528  *    Function: sd_take_ownership()
22529  *
22530  * Description: This routine implements an algorithm to achieve a stable
22531  *		reservation on disks which don't implement priority reserve,
22532  *		and makes sure that other host lose re-reservation attempts.
22533  *		This algorithm contains of a loop that keeps issuing the RESERVE
22534  *		for some period of time (min_ownership_delay, default 6 seconds)
22535  *		During that loop, it looks to see if there has been a bus device
22536  *		reset or bus reset (both of which cause an existing reservation
22537  *		to be lost). If the reservation is lost issue RESERVE until a
22538  *		period of min_ownership_delay with no resets has gone by, or
22539  *		until max_ownership_delay has expired. This loop ensures that
22540  *		the host really did manage to reserve the device, in spite of
22541  *		resets. The looping for min_ownership_delay (default six
22542  *		seconds) is important to early generation clustering products,
22543  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
22544  *		MHIOCENFAILFAST periodic timer of two seconds. By having
22545  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
22546  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
22547  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
22548  *		have already noticed, via the MHIOCENFAILFAST polling, that it
22549  *		no longer "owns" the disk and will have panicked itself.  Thus,
22550  *		the host issuing the MHIOCTKOWN is assured (with timing
22551  *		dependencies) that by the time it actually starts to use the
22552  *		disk for real work, the old owner is no longer accessing it.
22553  *
22554  *		min_ownership_delay is the minimum amount of time for which the
22555  *		disk must be reserved continuously devoid of resets before the
22556  *		MHIOCTKOWN ioctl will return success.
22557  *
22558  *		max_ownership_delay indicates the amount of time by which the
22559  *		take ownership should succeed or timeout with an error.
22560  *
22561  *   Arguments: dev - the device 'dev_t'
22562  *		*p  - struct containing timing info.
22563  *
22564  * Return Code: 0 for success or error code
22565  */
22566 
22567 static int
22568 sd_take_ownership(dev_t dev, struct mhioctkown *p)
22569 {
22570 	struct sd_lun	*un;
22571 	int		rval;
22572 	int		err;
22573 	int		reservation_count   = 0;
22574 	int		min_ownership_delay =  6000000; /* in usec */
22575 	int		max_ownership_delay = 30000000; /* in usec */
22576 	clock_t		start_time;	/* starting time of this algorithm */
22577 	clock_t		end_time;	/* time limit for giving up */
22578 	clock_t		ownership_time;	/* time limit for stable ownership */
22579 	clock_t		current_time;
22580 	clock_t		previous_current_time;
22581 
22582 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22583 		return (ENXIO);
22584 	}
22585 
22586 	/*
22587 	 * Attempt a device reservation. A priority reservation is requested.
22588 	 */
22589 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
22590 	    != SD_SUCCESS) {
22591 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
22592 		    "sd_take_ownership: return(1)=%d\n", rval);
22593 		return (rval);
22594 	}
22595 
22596 	/* Update the softstate reserved status to indicate the reservation */
22597 	mutex_enter(SD_MUTEX(un));
22598 	un->un_resvd_status |= SD_RESERVE;
22599 	un->un_resvd_status &=
22600 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
22601 	mutex_exit(SD_MUTEX(un));
22602 
22603 	if (p != NULL) {
22604 		if (p->min_ownership_delay != 0) {
22605 			min_ownership_delay = p->min_ownership_delay * 1000;
22606 		}
22607 		if (p->max_ownership_delay != 0) {
22608 			max_ownership_delay = p->max_ownership_delay * 1000;
22609 		}
22610 	}
22611 	SD_INFO(SD_LOG_IOCTL_MHD, un,
22612 	    "sd_take_ownership: min, max delays: %d, %d\n",
22613 	    min_ownership_delay, max_ownership_delay);
22614 
22615 	start_time = ddi_get_lbolt();
22616 	current_time	= start_time;
22617 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
22618 	end_time	= start_time + drv_usectohz(max_ownership_delay);
22619 
22620 	while (current_time - end_time < 0) {
22621 		delay(drv_usectohz(500000));
22622 
22623 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
22624 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
22625 				mutex_enter(SD_MUTEX(un));
22626 				rval = (un->un_resvd_status &
22627 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
22628 				mutex_exit(SD_MUTEX(un));
22629 				break;
22630 			}
22631 		}
22632 		previous_current_time = current_time;
22633 		current_time = ddi_get_lbolt();
22634 		mutex_enter(SD_MUTEX(un));
22635 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
22636 			ownership_time = ddi_get_lbolt() +
22637 			    drv_usectohz(min_ownership_delay);
22638 			reservation_count = 0;
22639 		} else {
22640 			reservation_count++;
22641 		}
22642 		un->un_resvd_status |= SD_RESERVE;
22643 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
22644 		mutex_exit(SD_MUTEX(un));
22645 
22646 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22647 		    "sd_take_ownership: ticks for loop iteration=%ld, "
22648 		    "reservation=%s\n", (current_time - previous_current_time),
22649 		    reservation_count ? "ok" : "reclaimed");
22650 
22651 		if (current_time - ownership_time >= 0 &&
22652 		    reservation_count >= 4) {
22653 			rval = 0; /* Achieved a stable ownership */
22654 			break;
22655 		}
22656 		if (current_time - end_time >= 0) {
22657 			rval = EACCES; /* No ownership in max possible time */
22658 			break;
22659 		}
22660 	}
22661 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
22662 	    "sd_take_ownership: return(2)=%d\n", rval);
22663 	return (rval);
22664 }
22665 
22666 
22667 /*
22668  *    Function: sd_reserve_release()
22669  *
22670  * Description: This function builds and sends scsi RESERVE, RELEASE, and
22671  *		PRIORITY RESERVE commands based on a user specified command type
22672  *
22673  *   Arguments: dev - the device 'dev_t'
22674  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
22675  *		      SD_RESERVE, SD_RELEASE
22676  *
22677  * Return Code: 0 or Error Code
22678  */
22679 
22680 static int
22681 sd_reserve_release(dev_t dev, int cmd)
22682 {
22683 	struct uscsi_cmd	*com = NULL;
22684 	struct sd_lun		*un = NULL;
22685 	char			cdb[CDB_GROUP0];
22686 	int			rval;
22687 
22688 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
22689 	    (cmd == SD_PRIORITY_RESERVE));
22690 
22691 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22692 		return (ENXIO);
22693 	}
22694 
22695 	/* instantiate and initialize the command and cdb */
22696 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
22697 	bzero(cdb, CDB_GROUP0);
22698 	com->uscsi_flags   = USCSI_SILENT;
22699 	com->uscsi_timeout = un->un_reserve_release_time;
22700 	com->uscsi_cdblen  = CDB_GROUP0;
22701 	com->uscsi_cdb	   = cdb;
22702 	if (cmd == SD_RELEASE) {
22703 		cdb[0] = SCMD_RELEASE;
22704 	} else {
22705 		cdb[0] = SCMD_RESERVE;
22706 	}
22707 
22708 	/* Send the command. */
22709 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22710 	    SD_PATH_STANDARD);
22711 
22712 	/*
22713 	 * "break" a reservation that is held by another host, by issuing a
22714 	 * reset if priority reserve is desired, and we could not get the
22715 	 * device.
22716 	 */
22717 	if ((cmd == SD_PRIORITY_RESERVE) &&
22718 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22719 		/*
22720 		 * First try to reset the LUN. If we cannot, then try a target
22721 		 * reset, followed by a bus reset if the target reset fails.
22722 		 */
22723 		int reset_retval = 0;
22724 		if (un->un_f_lun_reset_enabled == TRUE) {
22725 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
22726 		}
22727 		if (reset_retval == 0) {
22728 			/* The LUN reset either failed or was not issued */
22729 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
22730 		}
22731 		if ((reset_retval == 0) &&
22732 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
22733 			rval = EIO;
22734 			kmem_free(com, sizeof (*com));
22735 			return (rval);
22736 		}
22737 
22738 		bzero(com, sizeof (struct uscsi_cmd));
22739 		com->uscsi_flags   = USCSI_SILENT;
22740 		com->uscsi_cdb	   = cdb;
22741 		com->uscsi_cdblen  = CDB_GROUP0;
22742 		com->uscsi_timeout = 5;
22743 
22744 		/*
22745 		 * Reissue the last reserve command, this time without request
22746 		 * sense.  Assume that it is just a regular reserve command.
22747 		 */
22748 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22749 		    SD_PATH_STANDARD);
22750 	}
22751 
22752 	/* Return an error if still getting a reservation conflict. */
22753 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22754 		rval = EACCES;
22755 	}
22756 
22757 	kmem_free(com, sizeof (*com));
22758 	return (rval);
22759 }
22760 
22761 
22762 #define	SD_NDUMP_RETRIES	12
22763 /*
22764  *	System Crash Dump routine
22765  */
22766 
22767 static int
22768 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
22769 {
22770 	int		instance;
22771 	int		partition;
22772 	int		i;
22773 	int		err;
22774 	struct sd_lun	*un;
22775 	struct scsi_pkt *wr_pktp;
22776 	struct buf	*wr_bp;
22777 	struct buf	wr_buf;
22778 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
22779 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
22780 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
22781 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
22782 	size_t		io_start_offset;
22783 	int		doing_rmw = FALSE;
22784 	int		rval;
22785 #if defined(__i386) || defined(__amd64)
22786 	ssize_t dma_resid;
22787 	daddr_t oblkno;
22788 #endif
22789 	diskaddr_t	nblks = 0;
22790 	diskaddr_t	start_block;
22791 
22792 	instance = SDUNIT(dev);
22793 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
22794 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
22795 		return (ENXIO);
22796 	}
22797 
22798 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
22799 
22800 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
22801 
22802 	partition = SDPART(dev);
22803 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
22804 
22805 	/* Validate blocks to dump at against partition size. */
22806 
22807 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
22808 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
22809 
22810 	if ((blkno + nblk) > nblks) {
22811 		SD_TRACE(SD_LOG_DUMP, un,
22812 		    "sddump: dump range larger than partition: "
22813 		    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
22814 		    blkno, nblk, nblks);
22815 		return (EINVAL);
22816 	}
22817 
22818 	mutex_enter(&un->un_pm_mutex);
22819 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
22820 		struct scsi_pkt *start_pktp;
22821 
22822 		mutex_exit(&un->un_pm_mutex);
22823 
22824 		/*
22825 		 * use pm framework to power on HBA 1st
22826 		 */
22827 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
22828 
22829 		/*
22830 		 * Dump no long uses sdpower to power on a device, it's
22831 		 * in-line here so it can be done in polled mode.
22832 		 */
22833 
22834 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
22835 
22836 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
22837 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
22838 
22839 		if (start_pktp == NULL) {
22840 			/* We were not given a SCSI packet, fail. */
22841 			return (EIO);
22842 		}
22843 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
22844 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
22845 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
22846 		start_pktp->pkt_flags = FLAG_NOINTR;
22847 
22848 		mutex_enter(SD_MUTEX(un));
22849 		SD_FILL_SCSI1_LUN(un, start_pktp);
22850 		mutex_exit(SD_MUTEX(un));
22851 		/*
22852 		 * Scsi_poll returns 0 (success) if the command completes and
22853 		 * the status block is STATUS_GOOD.
22854 		 */
22855 		if (sd_scsi_poll(un, start_pktp) != 0) {
22856 			scsi_destroy_pkt(start_pktp);
22857 			return (EIO);
22858 		}
22859 		scsi_destroy_pkt(start_pktp);
22860 		(void) sd_ddi_pm_resume(un);
22861 	} else {
22862 		mutex_exit(&un->un_pm_mutex);
22863 	}
22864 
22865 	mutex_enter(SD_MUTEX(un));
22866 	un->un_throttle = 0;
22867 
22868 	/*
22869 	 * The first time through, reset the specific target device.
22870 	 * However, when cpr calls sddump we know that sd is in a
22871 	 * a good state so no bus reset is required.
22872 	 * Clear sense data via Request Sense cmd.
22873 	 * In sddump we don't care about allow_bus_device_reset anymore
22874 	 */
22875 
22876 	if ((un->un_state != SD_STATE_SUSPENDED) &&
22877 	    (un->un_state != SD_STATE_DUMPING)) {
22878 
22879 		New_state(un, SD_STATE_DUMPING);
22880 
22881 		if (un->un_f_is_fibre == FALSE) {
22882 			mutex_exit(SD_MUTEX(un));
22883 			/*
22884 			 * Attempt a bus reset for parallel scsi.
22885 			 *
22886 			 * Note: A bus reset is required because on some host
22887 			 * systems (i.e. E420R) a bus device reset is
22888 			 * insufficient to reset the state of the target.
22889 			 *
22890 			 * Note: Don't issue the reset for fibre-channel,
22891 			 * because this tends to hang the bus (loop) for
22892 			 * too long while everyone is logging out and in
22893 			 * and the deadman timer for dumping will fire
22894 			 * before the dump is complete.
22895 			 */
22896 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
22897 				mutex_enter(SD_MUTEX(un));
22898 				Restore_state(un);
22899 				mutex_exit(SD_MUTEX(un));
22900 				return (EIO);
22901 			}
22902 
22903 			/* Delay to give the device some recovery time. */
22904 			drv_usecwait(10000);
22905 
22906 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
22907 				SD_INFO(SD_LOG_DUMP, un,
22908 				    "sddump: sd_send_polled_RQS failed\n");
22909 			}
22910 			mutex_enter(SD_MUTEX(un));
22911 		}
22912 	}
22913 
22914 	/*
22915 	 * Convert the partition-relative block number to a
22916 	 * disk physical block number.
22917 	 */
22918 	blkno += start_block;
22919 
22920 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
22921 
22922 
22923 	/*
22924 	 * Check if the device has a non-512 block size.
22925 	 */
22926 	wr_bp = NULL;
22927 	if (NOT_DEVBSIZE(un)) {
22928 		tgt_byte_offset = blkno * un->un_sys_blocksize;
22929 		tgt_byte_count = nblk * un->un_sys_blocksize;
22930 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
22931 		    (tgt_byte_count % un->un_tgt_blocksize)) {
22932 			doing_rmw = TRUE;
22933 			/*
22934 			 * Calculate the block number and number of block
22935 			 * in terms of the media block size.
22936 			 */
22937 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
22938 			tgt_nblk =
22939 			    ((tgt_byte_offset + tgt_byte_count +
22940 			    (un->un_tgt_blocksize - 1)) /
22941 			    un->un_tgt_blocksize) - tgt_blkno;
22942 
22943 			/*
22944 			 * Invoke the routine which is going to do read part
22945 			 * of read-modify-write.
22946 			 * Note that this routine returns a pointer to
22947 			 * a valid bp in wr_bp.
22948 			 */
22949 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
22950 			    &wr_bp);
22951 			if (err) {
22952 				mutex_exit(SD_MUTEX(un));
22953 				return (err);
22954 			}
22955 			/*
22956 			 * Offset is being calculated as -
22957 			 * (original block # * system block size) -
22958 			 * (new block # * target block size)
22959 			 */
22960 			io_start_offset =
22961 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
22962 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
22963 
22964 			ASSERT((io_start_offset >= 0) &&
22965 			    (io_start_offset < un->un_tgt_blocksize));
22966 			/*
22967 			 * Do the modify portion of read modify write.
22968 			 */
22969 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
22970 			    (size_t)nblk * un->un_sys_blocksize);
22971 		} else {
22972 			doing_rmw = FALSE;
22973 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
22974 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
22975 		}
22976 
22977 		/* Convert blkno and nblk to target blocks */
22978 		blkno = tgt_blkno;
22979 		nblk = tgt_nblk;
22980 	} else {
22981 		wr_bp = &wr_buf;
22982 		bzero(wr_bp, sizeof (struct buf));
22983 		wr_bp->b_flags		= B_BUSY;
22984 		wr_bp->b_un.b_addr	= addr;
22985 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
22986 		wr_bp->b_resid		= 0;
22987 	}
22988 
22989 	mutex_exit(SD_MUTEX(un));
22990 
22991 	/*
22992 	 * Obtain a SCSI packet for the write command.
22993 	 * It should be safe to call the allocator here without
22994 	 * worrying about being locked for DVMA mapping because
22995 	 * the address we're passed is already a DVMA mapping
22996 	 *
22997 	 * We are also not going to worry about semaphore ownership
22998 	 * in the dump buffer. Dumping is single threaded at present.
22999 	 */
23000 
23001 	wr_pktp = NULL;
23002 
23003 #if defined(__i386) || defined(__amd64)
23004 	dma_resid = wr_bp->b_bcount;
23005 	oblkno = blkno;
23006 	while (dma_resid != 0) {
23007 #endif
23008 
23009 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
23010 		wr_bp->b_flags &= ~B_ERROR;
23011 
23012 #if defined(__i386) || defined(__amd64)
23013 		blkno = oblkno +
23014 		    ((wr_bp->b_bcount - dma_resid) /
23015 		    un->un_tgt_blocksize);
23016 		nblk = dma_resid / un->un_tgt_blocksize;
23017 
23018 		if (wr_pktp) {
23019 			/* Partial DMA transfers after initial transfer */
23020 			rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
23021 			    blkno, nblk);
23022 		} else {
23023 			/* Initial transfer */
23024 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
23025 			    un->un_pkt_flags, NULL_FUNC, NULL,
23026 			    blkno, nblk);
23027 		}
23028 #else
23029 		rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
23030 		    0, NULL_FUNC, NULL, blkno, nblk);
23031 #endif
23032 
23033 		if (rval == 0) {
23034 			/* We were given a SCSI packet, continue. */
23035 			break;
23036 		}
23037 
23038 		if (i == 0) {
23039 			if (wr_bp->b_flags & B_ERROR) {
23040 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23041 				    "no resources for dumping; "
23042 				    "error code: 0x%x, retrying",
23043 				    geterror(wr_bp));
23044 			} else {
23045 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23046 				    "no resources for dumping; retrying");
23047 			}
23048 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
23049 			if (wr_bp->b_flags & B_ERROR) {
23050 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23051 				    "no resources for dumping; error code: "
23052 				    "0x%x, retrying\n", geterror(wr_bp));
23053 			}
23054 		} else {
23055 			if (wr_bp->b_flags & B_ERROR) {
23056 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23057 				    "no resources for dumping; "
23058 				    "error code: 0x%x, retries failed, "
23059 				    "giving up.\n", geterror(wr_bp));
23060 			} else {
23061 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23062 				    "no resources for dumping; "
23063 				    "retries failed, giving up.\n");
23064 			}
23065 			mutex_enter(SD_MUTEX(un));
23066 			Restore_state(un);
23067 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
23068 				mutex_exit(SD_MUTEX(un));
23069 				scsi_free_consistent_buf(wr_bp);
23070 			} else {
23071 				mutex_exit(SD_MUTEX(un));
23072 			}
23073 			return (EIO);
23074 		}
23075 		drv_usecwait(10000);
23076 	}
23077 
23078 #if defined(__i386) || defined(__amd64)
23079 	/*
23080 	 * save the resid from PARTIAL_DMA
23081 	 */
23082 	dma_resid = wr_pktp->pkt_resid;
23083 	if (dma_resid != 0)
23084 		nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
23085 	wr_pktp->pkt_resid = 0;
23086 #endif
23087 
23088 	/* SunBug 1222170 */
23089 	wr_pktp->pkt_flags = FLAG_NOINTR;
23090 
23091 	err = EIO;
23092 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
23093 
23094 		/*
23095 		 * Scsi_poll returns 0 (success) if the command completes and
23096 		 * the status block is STATUS_GOOD.  We should only check
23097 		 * errors if this condition is not true.  Even then we should
23098 		 * send our own request sense packet only if we have a check
23099 		 * condition and auto request sense has not been performed by
23100 		 * the hba.
23101 		 */
23102 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
23103 
23104 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
23105 		    (wr_pktp->pkt_resid == 0)) {
23106 			err = SD_SUCCESS;
23107 			break;
23108 		}
23109 
23110 		/*
23111 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
23112 		 */
23113 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
23114 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23115 			    "Device is gone\n");
23116 			break;
23117 		}
23118 
23119 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
23120 			SD_INFO(SD_LOG_DUMP, un,
23121 			    "sddump: write failed with CHECK, try # %d\n", i);
23122 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
23123 				(void) sd_send_polled_RQS(un);
23124 			}
23125 
23126 			continue;
23127 		}
23128 
23129 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
23130 			int reset_retval = 0;
23131 
23132 			SD_INFO(SD_LOG_DUMP, un,
23133 			    "sddump: write failed with BUSY, try # %d\n", i);
23134 
23135 			if (un->un_f_lun_reset_enabled == TRUE) {
23136 				reset_retval = scsi_reset(SD_ADDRESS(un),
23137 				    RESET_LUN);
23138 			}
23139 			if (reset_retval == 0) {
23140 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
23141 			}
23142 			(void) sd_send_polled_RQS(un);
23143 
23144 		} else {
23145 			SD_INFO(SD_LOG_DUMP, un,
23146 			    "sddump: write failed with 0x%x, try # %d\n",
23147 			    SD_GET_PKT_STATUS(wr_pktp), i);
23148 			mutex_enter(SD_MUTEX(un));
23149 			sd_reset_target(un, wr_pktp);
23150 			mutex_exit(SD_MUTEX(un));
23151 		}
23152 
23153 		/*
23154 		 * If we are not getting anywhere with lun/target resets,
23155 		 * let's reset the bus.
23156 		 */
23157 		if (i == SD_NDUMP_RETRIES/2) {
23158 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
23159 			(void) sd_send_polled_RQS(un);
23160 		}
23161 
23162 	}
23163 #if defined(__i386) || defined(__amd64)
23164 	}	/* dma_resid */
23165 #endif
23166 
23167 	scsi_destroy_pkt(wr_pktp);
23168 	mutex_enter(SD_MUTEX(un));
23169 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
23170 		mutex_exit(SD_MUTEX(un));
23171 		scsi_free_consistent_buf(wr_bp);
23172 	} else {
23173 		mutex_exit(SD_MUTEX(un));
23174 	}
23175 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
23176 	return (err);
23177 }
23178 
23179 /*
23180  *    Function: sd_scsi_poll()
23181  *
23182  * Description: This is a wrapper for the scsi_poll call.
23183  *
23184  *   Arguments: sd_lun - The unit structure
23185  *              scsi_pkt - The scsi packet being sent to the device.
23186  *
23187  * Return Code: 0 - Command completed successfully with good status
23188  *             -1 - Command failed.  This could indicate a check condition
23189  *                  or other status value requiring recovery action.
23190  *
23191  */
23192 
23193 static int
23194 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
23195 {
23196 	int status;
23197 
23198 	ASSERT(un != NULL);
23199 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23200 	ASSERT(pktp != NULL);
23201 
23202 	status = SD_SUCCESS;
23203 
23204 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
23205 		pktp->pkt_flags |= un->un_tagflags;
23206 		pktp->pkt_flags &= ~FLAG_NODISCON;
23207 	}
23208 
23209 	status = sd_ddi_scsi_poll(pktp);
23210 	/*
23211 	 * Scsi_poll returns 0 (success) if the command completes and the
23212 	 * status block is STATUS_GOOD.  We should only check errors if this
23213 	 * condition is not true.  Even then we should send our own request
23214 	 * sense packet only if we have a check condition and auto
23215 	 * request sense has not been performed by the hba.
23216 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
23217 	 */
23218 	if ((status != SD_SUCCESS) &&
23219 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
23220 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
23221 	    (pktp->pkt_reason != CMD_DEV_GONE))
23222 		(void) sd_send_polled_RQS(un);
23223 
23224 	return (status);
23225 }
23226 
23227 /*
23228  *    Function: sd_send_polled_RQS()
23229  *
23230  * Description: This sends the request sense command to a device.
23231  *
23232  *   Arguments: sd_lun - The unit structure
23233  *
23234  * Return Code: 0 - Command completed successfully with good status
23235  *             -1 - Command failed.
23236  *
23237  */
23238 
23239 static int
23240 sd_send_polled_RQS(struct sd_lun *un)
23241 {
23242 	int	ret_val;
23243 	struct	scsi_pkt	*rqs_pktp;
23244 	struct	buf		*rqs_bp;
23245 
23246 	ASSERT(un != NULL);
23247 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23248 
23249 	ret_val = SD_SUCCESS;
23250 
23251 	rqs_pktp = un->un_rqs_pktp;
23252 	rqs_bp	 = un->un_rqs_bp;
23253 
23254 	mutex_enter(SD_MUTEX(un));
23255 
23256 	if (un->un_sense_isbusy) {
23257 		ret_val = SD_FAILURE;
23258 		mutex_exit(SD_MUTEX(un));
23259 		return (ret_val);
23260 	}
23261 
23262 	/*
23263 	 * If the request sense buffer (and packet) is not in use,
23264 	 * let's set the un_sense_isbusy and send our packet
23265 	 */
23266 	un->un_sense_isbusy 	= 1;
23267 	rqs_pktp->pkt_resid  	= 0;
23268 	rqs_pktp->pkt_reason 	= 0;
23269 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
23270 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
23271 
23272 	mutex_exit(SD_MUTEX(un));
23273 
23274 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
23275 	    " 0x%p\n", rqs_bp->b_un.b_addr);
23276 
23277 	/*
23278 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
23279 	 * axle - it has a call into us!
23280 	 */
23281 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
23282 		SD_INFO(SD_LOG_COMMON, un,
23283 		    "sd_send_polled_RQS: RQS failed\n");
23284 	}
23285 
23286 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
23287 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
23288 
23289 	mutex_enter(SD_MUTEX(un));
23290 	un->un_sense_isbusy = 0;
23291 	mutex_exit(SD_MUTEX(un));
23292 
23293 	return (ret_val);
23294 }
23295 
23296 /*
23297  * Defines needed for localized version of the scsi_poll routine.
23298  */
23299 #define	SD_CSEC		10000			/* usecs */
23300 #define	SD_SEC_TO_CSEC	(1000000/SD_CSEC)
23301 
23302 
23303 /*
23304  *    Function: sd_ddi_scsi_poll()
23305  *
23306  * Description: Localized version of the scsi_poll routine.  The purpose is to
23307  *		send a scsi_pkt to a device as a polled command.  This version
23308  *		is to ensure more robust handling of transport errors.
23309  *		Specifically this routine cures not ready, coming ready
23310  *		transition for power up and reset of sonoma's.  This can take
23311  *		up to 45 seconds for power-on and 20 seconds for reset of a
23312  * 		sonoma lun.
23313  *
23314  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
23315  *
23316  * Return Code: 0 - Command completed successfully with good status
23317  *             -1 - Command failed.
23318  *
23319  */
23320 
23321 static int
23322 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
23323 {
23324 	int busy_count;
23325 	int timeout;
23326 	int rval = SD_FAILURE;
23327 	int savef;
23328 	uint8_t *sensep;
23329 	long savet;
23330 	void (*savec)();
23331 	/*
23332 	 * The following is defined in machdep.c and is used in determining if
23333 	 * the scsi transport system will do polled I/O instead of interrupt
23334 	 * I/O when called from xx_dump().
23335 	 */
23336 	extern int do_polled_io;
23337 
23338 	/*
23339 	 * save old flags in pkt, to restore at end
23340 	 */
23341 	savef = pkt->pkt_flags;
23342 	savec = pkt->pkt_comp;
23343 	savet = pkt->pkt_time;
23344 
23345 	pkt->pkt_flags |= FLAG_NOINTR;
23346 
23347 	/*
23348 	 * XXX there is nothing in the SCSA spec that states that we should not
23349 	 * do a callback for polled cmds; however, removing this will break sd
23350 	 * and probably other target drivers
23351 	 */
23352 	pkt->pkt_comp = NULL;
23353 
23354 	/*
23355 	 * we don't like a polled command without timeout.
23356 	 * 60 seconds seems long enough.
23357 	 */
23358 	if (pkt->pkt_time == 0) {
23359 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
23360 	}
23361 
23362 	/*
23363 	 * Send polled cmd.
23364 	 *
23365 	 * We do some error recovery for various errors.  Tran_busy,
23366 	 * queue full, and non-dispatched commands are retried every 10 msec.
23367 	 * as they are typically transient failures.  Busy status and Not
23368 	 * Ready are retried every second as this status takes a while to
23369 	 * change.  Unit attention is retried for pkt_time (60) times
23370 	 * with no delay.
23371 	 */
23372 	timeout = pkt->pkt_time * SD_SEC_TO_CSEC;
23373 
23374 	for (busy_count = 0; busy_count < timeout; busy_count++) {
23375 		int rc;
23376 		int poll_delay;
23377 
23378 		/*
23379 		 * Initialize pkt status variables.
23380 		 */
23381 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
23382 
23383 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
23384 			if (rc != TRAN_BUSY) {
23385 				/* Transport failed - give up. */
23386 				break;
23387 			} else {
23388 				/* Transport busy - try again. */
23389 				poll_delay = 1 * SD_CSEC; /* 10 msec */
23390 			}
23391 		} else {
23392 			/*
23393 			 * Transport accepted - check pkt status.
23394 			 */
23395 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
23396 			if (pkt->pkt_reason == CMD_CMPLT &&
23397 			    rc == STATUS_CHECK &&
23398 			    pkt->pkt_state & STATE_ARQ_DONE) {
23399 				struct scsi_arq_status *arqstat =
23400 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
23401 
23402 				sensep = (uint8_t *)&arqstat->sts_sensedata;
23403 			} else {
23404 				sensep = NULL;
23405 			}
23406 
23407 			if ((pkt->pkt_reason == CMD_CMPLT) &&
23408 			    (rc == STATUS_GOOD)) {
23409 				/* No error - we're done */
23410 				rval = SD_SUCCESS;
23411 				break;
23412 
23413 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
23414 				/* Lost connection - give up */
23415 				break;
23416 
23417 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
23418 			    (pkt->pkt_state == 0)) {
23419 				/* Pkt not dispatched - try again. */
23420 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
23421 
23422 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23423 			    (rc == STATUS_QFULL)) {
23424 				/* Queue full - try again. */
23425 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
23426 
23427 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23428 			    (rc == STATUS_BUSY)) {
23429 				/* Busy - try again. */
23430 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
23431 				busy_count += (SD_SEC_TO_CSEC - 1);
23432 
23433 			} else if ((sensep != NULL) &&
23434 			    (scsi_sense_key(sensep) ==
23435 			    KEY_UNIT_ATTENTION)) {
23436 				/* Unit Attention - try again */
23437 				busy_count += (SD_SEC_TO_CSEC - 1); /* 1 */
23438 				continue;
23439 
23440 			} else if ((sensep != NULL) &&
23441 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
23442 			    (scsi_sense_asc(sensep) == 0x04) &&
23443 			    (scsi_sense_ascq(sensep) == 0x01)) {
23444 				/* Not ready -> ready - try again. */
23445 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
23446 				busy_count += (SD_SEC_TO_CSEC - 1);
23447 
23448 			} else {
23449 				/* BAD status - give up. */
23450 				break;
23451 			}
23452 		}
23453 
23454 		if ((curthread->t_flag & T_INTR_THREAD) == 0 &&
23455 		    !do_polled_io) {
23456 			delay(drv_usectohz(poll_delay));
23457 		} else {
23458 			/* we busy wait during cpr_dump or interrupt threads */
23459 			drv_usecwait(poll_delay);
23460 		}
23461 	}
23462 
23463 	pkt->pkt_flags = savef;
23464 	pkt->pkt_comp = savec;
23465 	pkt->pkt_time = savet;
23466 	return (rval);
23467 }
23468 
23469 
23470 /*
23471  *    Function: sd_persistent_reservation_in_read_keys
23472  *
23473  * Description: This routine is the driver entry point for handling CD-ROM
23474  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
23475  *		by sending the SCSI-3 PRIN commands to the device.
23476  *		Processes the read keys command response by copying the
23477  *		reservation key information into the user provided buffer.
23478  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
23479  *
23480  *   Arguments: un   -  Pointer to soft state struct for the target.
23481  *		usrp -	user provided pointer to multihost Persistent In Read
23482  *			Keys structure (mhioc_inkeys_t)
23483  *		flag -	this argument is a pass through to ddi_copyxxx()
23484  *			directly from the mode argument of ioctl().
23485  *
23486  * Return Code: 0   - Success
23487  *		EACCES
23488  *		ENOTSUP
23489  *		errno return code from sd_send_scsi_cmd()
23490  *
23491  *     Context: Can sleep. Does not return until command is completed.
23492  */
23493 
23494 static int
23495 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
23496     mhioc_inkeys_t *usrp, int flag)
23497 {
23498 #ifdef _MULTI_DATAMODEL
23499 	struct mhioc_key_list32	li32;
23500 #endif
23501 	sd_prin_readkeys_t	*in;
23502 	mhioc_inkeys_t		*ptr;
23503 	mhioc_key_list_t	li;
23504 	uchar_t			*data_bufp;
23505 	int 			data_len;
23506 	int			rval;
23507 	size_t			copysz;
23508 
23509 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
23510 		return (EINVAL);
23511 	}
23512 	bzero(&li, sizeof (mhioc_key_list_t));
23513 
23514 	/*
23515 	 * Get the listsize from user
23516 	 */
23517 #ifdef _MULTI_DATAMODEL
23518 
23519 	switch (ddi_model_convert_from(flag & FMODELS)) {
23520 	case DDI_MODEL_ILP32:
23521 		copysz = sizeof (struct mhioc_key_list32);
23522 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
23523 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23524 			    "sd_persistent_reservation_in_read_keys: "
23525 			    "failed ddi_copyin: mhioc_key_list32_t\n");
23526 			rval = EFAULT;
23527 			goto done;
23528 		}
23529 		li.listsize = li32.listsize;
23530 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
23531 		break;
23532 
23533 	case DDI_MODEL_NONE:
23534 		copysz = sizeof (mhioc_key_list_t);
23535 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23536 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23537 			    "sd_persistent_reservation_in_read_keys: "
23538 			    "failed ddi_copyin: mhioc_key_list_t\n");
23539 			rval = EFAULT;
23540 			goto done;
23541 		}
23542 		break;
23543 	}
23544 
23545 #else /* ! _MULTI_DATAMODEL */
23546 	copysz = sizeof (mhioc_key_list_t);
23547 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23548 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23549 		    "sd_persistent_reservation_in_read_keys: "
23550 		    "failed ddi_copyin: mhioc_key_list_t\n");
23551 		rval = EFAULT;
23552 		goto done;
23553 	}
23554 #endif
23555 
23556 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
23557 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
23558 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23559 
23560 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS,
23561 	    data_len, data_bufp)) != 0) {
23562 		goto done;
23563 	}
23564 	in = (sd_prin_readkeys_t *)data_bufp;
23565 	ptr->generation = BE_32(in->generation);
23566 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
23567 
23568 	/*
23569 	 * Return the min(listsize, listlen) keys
23570 	 */
23571 #ifdef _MULTI_DATAMODEL
23572 
23573 	switch (ddi_model_convert_from(flag & FMODELS)) {
23574 	case DDI_MODEL_ILP32:
23575 		li32.listlen = li.listlen;
23576 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
23577 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23578 			    "sd_persistent_reservation_in_read_keys: "
23579 			    "failed ddi_copyout: mhioc_key_list32_t\n");
23580 			rval = EFAULT;
23581 			goto done;
23582 		}
23583 		break;
23584 
23585 	case DDI_MODEL_NONE:
23586 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23587 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23588 			    "sd_persistent_reservation_in_read_keys: "
23589 			    "failed ddi_copyout: mhioc_key_list_t\n");
23590 			rval = EFAULT;
23591 			goto done;
23592 		}
23593 		break;
23594 	}
23595 
23596 #else /* ! _MULTI_DATAMODEL */
23597 
23598 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23599 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23600 		    "sd_persistent_reservation_in_read_keys: "
23601 		    "failed ddi_copyout: mhioc_key_list_t\n");
23602 		rval = EFAULT;
23603 		goto done;
23604 	}
23605 
23606 #endif /* _MULTI_DATAMODEL */
23607 
23608 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
23609 	    li.listsize * MHIOC_RESV_KEY_SIZE);
23610 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
23611 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23612 		    "sd_persistent_reservation_in_read_keys: "
23613 		    "failed ddi_copyout: keylist\n");
23614 		rval = EFAULT;
23615 	}
23616 done:
23617 	kmem_free(data_bufp, data_len);
23618 	return (rval);
23619 }
23620 
23621 
23622 /*
23623  *    Function: sd_persistent_reservation_in_read_resv
23624  *
23625  * Description: This routine is the driver entry point for handling CD-ROM
23626  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
23627  *		by sending the SCSI-3 PRIN commands to the device.
23628  *		Process the read persistent reservations command response by
23629  *		copying the reservation information into the user provided
23630  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
23631  *
23632  *   Arguments: un   -  Pointer to soft state struct for the target.
23633  *		usrp -	user provided pointer to multihost Persistent In Read
23634  *			Keys structure (mhioc_inkeys_t)
23635  *		flag -	this argument is a pass through to ddi_copyxxx()
23636  *			directly from the mode argument of ioctl().
23637  *
23638  * Return Code: 0   - Success
23639  *		EACCES
23640  *		ENOTSUP
23641  *		errno return code from sd_send_scsi_cmd()
23642  *
23643  *     Context: Can sleep. Does not return until command is completed.
23644  */
23645 
23646 static int
23647 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
23648     mhioc_inresvs_t *usrp, int flag)
23649 {
23650 #ifdef _MULTI_DATAMODEL
23651 	struct mhioc_resv_desc_list32 resvlist32;
23652 #endif
23653 	sd_prin_readresv_t	*in;
23654 	mhioc_inresvs_t		*ptr;
23655 	sd_readresv_desc_t	*readresv_ptr;
23656 	mhioc_resv_desc_list_t	resvlist;
23657 	mhioc_resv_desc_t 	resvdesc;
23658 	uchar_t			*data_bufp;
23659 	int 			data_len;
23660 	int			rval;
23661 	int			i;
23662 	size_t			copysz;
23663 	mhioc_resv_desc_t	*bufp;
23664 
23665 	if ((ptr = usrp) == NULL) {
23666 		return (EINVAL);
23667 	}
23668 
23669 	/*
23670 	 * Get the listsize from user
23671 	 */
23672 #ifdef _MULTI_DATAMODEL
23673 	switch (ddi_model_convert_from(flag & FMODELS)) {
23674 	case DDI_MODEL_ILP32:
23675 		copysz = sizeof (struct mhioc_resv_desc_list32);
23676 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
23677 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23678 			    "sd_persistent_reservation_in_read_resv: "
23679 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23680 			rval = EFAULT;
23681 			goto done;
23682 		}
23683 		resvlist.listsize = resvlist32.listsize;
23684 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
23685 		break;
23686 
23687 	case DDI_MODEL_NONE:
23688 		copysz = sizeof (mhioc_resv_desc_list_t);
23689 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23690 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23691 			    "sd_persistent_reservation_in_read_resv: "
23692 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23693 			rval = EFAULT;
23694 			goto done;
23695 		}
23696 		break;
23697 	}
23698 #else /* ! _MULTI_DATAMODEL */
23699 	copysz = sizeof (mhioc_resv_desc_list_t);
23700 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23701 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23702 		    "sd_persistent_reservation_in_read_resv: "
23703 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23704 		rval = EFAULT;
23705 		goto done;
23706 	}
23707 #endif /* ! _MULTI_DATAMODEL */
23708 
23709 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
23710 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
23711 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23712 
23713 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_RESV,
23714 	    data_len, data_bufp)) != 0) {
23715 		goto done;
23716 	}
23717 	in = (sd_prin_readresv_t *)data_bufp;
23718 	ptr->generation = BE_32(in->generation);
23719 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
23720 
23721 	/*
23722 	 * Return the min(listsize, listlen( keys
23723 	 */
23724 #ifdef _MULTI_DATAMODEL
23725 
23726 	switch (ddi_model_convert_from(flag & FMODELS)) {
23727 	case DDI_MODEL_ILP32:
23728 		resvlist32.listlen = resvlist.listlen;
23729 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
23730 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23731 			    "sd_persistent_reservation_in_read_resv: "
23732 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23733 			rval = EFAULT;
23734 			goto done;
23735 		}
23736 		break;
23737 
23738 	case DDI_MODEL_NONE:
23739 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
23740 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23741 			    "sd_persistent_reservation_in_read_resv: "
23742 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23743 			rval = EFAULT;
23744 			goto done;
23745 		}
23746 		break;
23747 	}
23748 
23749 #else /* ! _MULTI_DATAMODEL */
23750 
23751 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
23752 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23753 		    "sd_persistent_reservation_in_read_resv: "
23754 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23755 		rval = EFAULT;
23756 		goto done;
23757 	}
23758 
23759 #endif /* ! _MULTI_DATAMODEL */
23760 
23761 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
23762 	bufp = resvlist.list;
23763 	copysz = sizeof (mhioc_resv_desc_t);
23764 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
23765 	    i++, readresv_ptr++, bufp++) {
23766 
23767 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
23768 		    MHIOC_RESV_KEY_SIZE);
23769 		resvdesc.type  = readresv_ptr->type;
23770 		resvdesc.scope = readresv_ptr->scope;
23771 		resvdesc.scope_specific_addr =
23772 		    BE_32(readresv_ptr->scope_specific_addr);
23773 
23774 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
23775 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23776 			    "sd_persistent_reservation_in_read_resv: "
23777 			    "failed ddi_copyout: resvlist\n");
23778 			rval = EFAULT;
23779 			goto done;
23780 		}
23781 	}
23782 done:
23783 	kmem_free(data_bufp, data_len);
23784 	return (rval);
23785 }
23786 
23787 
23788 /*
23789  *    Function: sr_change_blkmode()
23790  *
23791  * Description: This routine is the driver entry point for handling CD-ROM
23792  *		block mode ioctl requests. Support for returning and changing
23793  *		the current block size in use by the device is implemented. The
23794  *		LBA size is changed via a MODE SELECT Block Descriptor.
23795  *
23796  *		This routine issues a mode sense with an allocation length of
23797  *		12 bytes for the mode page header and a single block descriptor.
23798  *
23799  *   Arguments: dev - the device 'dev_t'
23800  *		cmd - the request type; one of CDROMGBLKMODE (get) or
23801  *		      CDROMSBLKMODE (set)
23802  *		data - current block size or requested block size
23803  *		flag - this argument is a pass through to ddi_copyxxx() directly
23804  *		       from the mode argument of ioctl().
23805  *
23806  * Return Code: the code returned by sd_send_scsi_cmd()
23807  *		EINVAL if invalid arguments are provided
23808  *		EFAULT if ddi_copyxxx() fails
23809  *		ENXIO if fail ddi_get_soft_state
23810  *		EIO if invalid mode sense block descriptor length
23811  *
23812  */
23813 
23814 static int
23815 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
23816 {
23817 	struct sd_lun			*un = NULL;
23818 	struct mode_header		*sense_mhp, *select_mhp;
23819 	struct block_descriptor		*sense_desc, *select_desc;
23820 	int				current_bsize;
23821 	int				rval = EINVAL;
23822 	uchar_t				*sense = NULL;
23823 	uchar_t				*select = NULL;
23824 
23825 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
23826 
23827 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23828 		return (ENXIO);
23829 	}
23830 
23831 	/*
23832 	 * The block length is changed via the Mode Select block descriptor, the
23833 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
23834 	 * required as part of this routine. Therefore the mode sense allocation
23835 	 * length is specified to be the length of a mode page header and a
23836 	 * block descriptor.
23837 	 */
23838 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
23839 
23840 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
23841 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD)) != 0) {
23842 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23843 		    "sr_change_blkmode: Mode Sense Failed\n");
23844 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23845 		return (rval);
23846 	}
23847 
23848 	/* Check the block descriptor len to handle only 1 block descriptor */
23849 	sense_mhp = (struct mode_header *)sense;
23850 	if ((sense_mhp->bdesc_length == 0) ||
23851 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
23852 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23853 		    "sr_change_blkmode: Mode Sense returned invalid block"
23854 		    " descriptor length\n");
23855 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23856 		return (EIO);
23857 	}
23858 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
23859 	current_bsize = ((sense_desc->blksize_hi << 16) |
23860 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
23861 
23862 	/* Process command */
23863 	switch (cmd) {
23864 	case CDROMGBLKMODE:
23865 		/* Return the block size obtained during the mode sense */
23866 		if (ddi_copyout(&current_bsize, (void *)data,
23867 		    sizeof (int), flag) != 0)
23868 			rval = EFAULT;
23869 		break;
23870 	case CDROMSBLKMODE:
23871 		/* Validate the requested block size */
23872 		switch (data) {
23873 		case CDROM_BLK_512:
23874 		case CDROM_BLK_1024:
23875 		case CDROM_BLK_2048:
23876 		case CDROM_BLK_2056:
23877 		case CDROM_BLK_2336:
23878 		case CDROM_BLK_2340:
23879 		case CDROM_BLK_2352:
23880 		case CDROM_BLK_2368:
23881 		case CDROM_BLK_2448:
23882 		case CDROM_BLK_2646:
23883 		case CDROM_BLK_2647:
23884 			break;
23885 		default:
23886 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23887 			    "sr_change_blkmode: "
23888 			    "Block Size '%ld' Not Supported\n", data);
23889 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23890 			return (EINVAL);
23891 		}
23892 
23893 		/*
23894 		 * The current block size matches the requested block size so
23895 		 * there is no need to send the mode select to change the size
23896 		 */
23897 		if (current_bsize == data) {
23898 			break;
23899 		}
23900 
23901 		/* Build the select data for the requested block size */
23902 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
23903 		select_mhp = (struct mode_header *)select;
23904 		select_desc =
23905 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
23906 		/*
23907 		 * The LBA size is changed via the block descriptor, so the
23908 		 * descriptor is built according to the user data
23909 		 */
23910 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
23911 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
23912 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
23913 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
23914 
23915 		/* Send the mode select for the requested block size */
23916 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
23917 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
23918 		    SD_PATH_STANDARD)) != 0) {
23919 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23920 			    "sr_change_blkmode: Mode Select Failed\n");
23921 			/*
23922 			 * The mode select failed for the requested block size,
23923 			 * so reset the data for the original block size and
23924 			 * send it to the target. The error is indicated by the
23925 			 * return value for the failed mode select.
23926 			 */
23927 			select_desc->blksize_hi  = sense_desc->blksize_hi;
23928 			select_desc->blksize_mid = sense_desc->blksize_mid;
23929 			select_desc->blksize_lo  = sense_desc->blksize_lo;
23930 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
23931 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
23932 			    SD_PATH_STANDARD);
23933 		} else {
23934 			ASSERT(!mutex_owned(SD_MUTEX(un)));
23935 			mutex_enter(SD_MUTEX(un));
23936 			sd_update_block_info(un, (uint32_t)data, 0);
23937 			mutex_exit(SD_MUTEX(un));
23938 		}
23939 		break;
23940 	default:
23941 		/* should not reach here, but check anyway */
23942 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23943 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
23944 		rval = EINVAL;
23945 		break;
23946 	}
23947 
23948 	if (select) {
23949 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
23950 	}
23951 	if (sense) {
23952 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23953 	}
23954 	return (rval);
23955 }
23956 
23957 
23958 /*
23959  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
23960  * implement driver support for getting and setting the CD speed. The command
23961  * set used will be based on the device type. If the device has not been
23962  * identified as MMC the Toshiba vendor specific mode page will be used. If
23963  * the device is MMC but does not support the Real Time Streaming feature
23964  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
23965  * be used to read the speed.
23966  */
23967 
23968 /*
23969  *    Function: sr_change_speed()
23970  *
23971  * Description: This routine is the driver entry point for handling CD-ROM
23972  *		drive speed ioctl requests for devices supporting the Toshiba
23973  *		vendor specific drive speed mode page. Support for returning
23974  *		and changing the current drive speed in use by the device is
23975  *		implemented.
23976  *
23977  *   Arguments: dev - the device 'dev_t'
23978  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
23979  *		      CDROMSDRVSPEED (set)
23980  *		data - current drive speed or requested drive speed
23981  *		flag - this argument is a pass through to ddi_copyxxx() directly
23982  *		       from the mode argument of ioctl().
23983  *
23984  * Return Code: the code returned by sd_send_scsi_cmd()
23985  *		EINVAL if invalid arguments are provided
23986  *		EFAULT if ddi_copyxxx() fails
23987  *		ENXIO if fail ddi_get_soft_state
23988  *		EIO if invalid mode sense block descriptor length
23989  */
23990 
23991 static int
23992 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
23993 {
23994 	struct sd_lun			*un = NULL;
23995 	struct mode_header		*sense_mhp, *select_mhp;
23996 	struct mode_speed		*sense_page, *select_page;
23997 	int				current_speed;
23998 	int				rval = EINVAL;
23999 	int				bd_len;
24000 	uchar_t				*sense = NULL;
24001 	uchar_t				*select = NULL;
24002 
24003 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
24004 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24005 		return (ENXIO);
24006 	}
24007 
24008 	/*
24009 	 * Note: The drive speed is being modified here according to a Toshiba
24010 	 * vendor specific mode page (0x31).
24011 	 */
24012 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
24013 
24014 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
24015 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
24016 	    SD_PATH_STANDARD)) != 0) {
24017 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24018 		    "sr_change_speed: Mode Sense Failed\n");
24019 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24020 		return (rval);
24021 	}
24022 	sense_mhp  = (struct mode_header *)sense;
24023 
24024 	/* Check the block descriptor len to handle only 1 block descriptor */
24025 	bd_len = sense_mhp->bdesc_length;
24026 	if (bd_len > MODE_BLK_DESC_LENGTH) {
24027 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24028 		    "sr_change_speed: Mode Sense returned invalid block "
24029 		    "descriptor length\n");
24030 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24031 		return (EIO);
24032 	}
24033 
24034 	sense_page = (struct mode_speed *)
24035 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
24036 	current_speed = sense_page->speed;
24037 
24038 	/* Process command */
24039 	switch (cmd) {
24040 	case CDROMGDRVSPEED:
24041 		/* Return the drive speed obtained during the mode sense */
24042 		if (current_speed == 0x2) {
24043 			current_speed = CDROM_TWELVE_SPEED;
24044 		}
24045 		if (ddi_copyout(&current_speed, (void *)data,
24046 		    sizeof (int), flag) != 0) {
24047 			rval = EFAULT;
24048 		}
24049 		break;
24050 	case CDROMSDRVSPEED:
24051 		/* Validate the requested drive speed */
24052 		switch ((uchar_t)data) {
24053 		case CDROM_TWELVE_SPEED:
24054 			data = 0x2;
24055 			/*FALLTHROUGH*/
24056 		case CDROM_NORMAL_SPEED:
24057 		case CDROM_DOUBLE_SPEED:
24058 		case CDROM_QUAD_SPEED:
24059 		case CDROM_MAXIMUM_SPEED:
24060 			break;
24061 		default:
24062 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24063 			    "sr_change_speed: "
24064 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
24065 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24066 			return (EINVAL);
24067 		}
24068 
24069 		/*
24070 		 * The current drive speed matches the requested drive speed so
24071 		 * there is no need to send the mode select to change the speed
24072 		 */
24073 		if (current_speed == data) {
24074 			break;
24075 		}
24076 
24077 		/* Build the select data for the requested drive speed */
24078 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
24079 		select_mhp = (struct mode_header *)select;
24080 		select_mhp->bdesc_length = 0;
24081 		select_page =
24082 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
24083 		select_page =
24084 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
24085 		select_page->mode_page.code = CDROM_MODE_SPEED;
24086 		select_page->mode_page.length = 2;
24087 		select_page->speed = (uchar_t)data;
24088 
24089 		/* Send the mode select for the requested block size */
24090 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
24091 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
24092 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
24093 			/*
24094 			 * The mode select failed for the requested drive speed,
24095 			 * so reset the data for the original drive speed and
24096 			 * send it to the target. The error is indicated by the
24097 			 * return value for the failed mode select.
24098 			 */
24099 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24100 			    "sr_drive_speed: Mode Select Failed\n");
24101 			select_page->speed = sense_page->speed;
24102 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
24103 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
24104 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
24105 		}
24106 		break;
24107 	default:
24108 		/* should not reach here, but check anyway */
24109 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24110 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
24111 		rval = EINVAL;
24112 		break;
24113 	}
24114 
24115 	if (select) {
24116 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
24117 	}
24118 	if (sense) {
24119 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24120 	}
24121 
24122 	return (rval);
24123 }
24124 
24125 
24126 /*
24127  *    Function: sr_atapi_change_speed()
24128  *
24129  * Description: This routine is the driver entry point for handling CD-ROM
24130  *		drive speed ioctl requests for MMC devices that do not support
24131  *		the Real Time Streaming feature (0x107).
24132  *
24133  *		Note: This routine will use the SET SPEED command which may not
24134  *		be supported by all devices.
24135  *
24136  *   Arguments: dev- the device 'dev_t'
24137  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
24138  *		     CDROMSDRVSPEED (set)
24139  *		data- current drive speed or requested drive speed
24140  *		flag- this argument is a pass through to ddi_copyxxx() directly
24141  *		      from the mode argument of ioctl().
24142  *
24143  * Return Code: the code returned by sd_send_scsi_cmd()
24144  *		EINVAL if invalid arguments are provided
24145  *		EFAULT if ddi_copyxxx() fails
24146  *		ENXIO if fail ddi_get_soft_state
24147  *		EIO if invalid mode sense block descriptor length
24148  */
24149 
24150 static int
24151 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
24152 {
24153 	struct sd_lun			*un;
24154 	struct uscsi_cmd		*com = NULL;
24155 	struct mode_header_grp2		*sense_mhp;
24156 	uchar_t				*sense_page;
24157 	uchar_t				*sense = NULL;
24158 	char				cdb[CDB_GROUP5];
24159 	int				bd_len;
24160 	int				current_speed = 0;
24161 	int				max_speed = 0;
24162 	int				rval;
24163 
24164 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
24165 
24166 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24167 		return (ENXIO);
24168 	}
24169 
24170 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
24171 
24172 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
24173 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
24174 	    SD_PATH_STANDARD)) != 0) {
24175 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24176 		    "sr_atapi_change_speed: Mode Sense Failed\n");
24177 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24178 		return (rval);
24179 	}
24180 
24181 	/* Check the block descriptor len to handle only 1 block descriptor */
24182 	sense_mhp = (struct mode_header_grp2 *)sense;
24183 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
24184 	if (bd_len > MODE_BLK_DESC_LENGTH) {
24185 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24186 		    "sr_atapi_change_speed: Mode Sense returned invalid "
24187 		    "block descriptor length\n");
24188 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24189 		return (EIO);
24190 	}
24191 
24192 	/* Calculate the current and maximum drive speeds */
24193 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
24194 	current_speed = (sense_page[14] << 8) | sense_page[15];
24195 	max_speed = (sense_page[8] << 8) | sense_page[9];
24196 
24197 	/* Process the command */
24198 	switch (cmd) {
24199 	case CDROMGDRVSPEED:
24200 		current_speed /= SD_SPEED_1X;
24201 		if (ddi_copyout(&current_speed, (void *)data,
24202 		    sizeof (int), flag) != 0)
24203 			rval = EFAULT;
24204 		break;
24205 	case CDROMSDRVSPEED:
24206 		/* Convert the speed code to KB/sec */
24207 		switch ((uchar_t)data) {
24208 		case CDROM_NORMAL_SPEED:
24209 			current_speed = SD_SPEED_1X;
24210 			break;
24211 		case CDROM_DOUBLE_SPEED:
24212 			current_speed = 2 * SD_SPEED_1X;
24213 			break;
24214 		case CDROM_QUAD_SPEED:
24215 			current_speed = 4 * SD_SPEED_1X;
24216 			break;
24217 		case CDROM_TWELVE_SPEED:
24218 			current_speed = 12 * SD_SPEED_1X;
24219 			break;
24220 		case CDROM_MAXIMUM_SPEED:
24221 			current_speed = 0xffff;
24222 			break;
24223 		default:
24224 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24225 			    "sr_atapi_change_speed: invalid drive speed %d\n",
24226 			    (uchar_t)data);
24227 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24228 			return (EINVAL);
24229 		}
24230 
24231 		/* Check the request against the drive's max speed. */
24232 		if (current_speed != 0xffff) {
24233 			if (current_speed > max_speed) {
24234 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24235 				return (EINVAL);
24236 			}
24237 		}
24238 
24239 		/*
24240 		 * Build and send the SET SPEED command
24241 		 *
24242 		 * Note: The SET SPEED (0xBB) command used in this routine is
24243 		 * obsolete per the SCSI MMC spec but still supported in the
24244 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
24245 		 * therefore the command is still implemented in this routine.
24246 		 */
24247 		bzero(cdb, sizeof (cdb));
24248 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
24249 		cdb[2] = (uchar_t)(current_speed >> 8);
24250 		cdb[3] = (uchar_t)current_speed;
24251 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24252 		com->uscsi_cdb	   = (caddr_t)cdb;
24253 		com->uscsi_cdblen  = CDB_GROUP5;
24254 		com->uscsi_bufaddr = NULL;
24255 		com->uscsi_buflen  = 0;
24256 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
24257 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
24258 		break;
24259 	default:
24260 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24261 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
24262 		rval = EINVAL;
24263 	}
24264 
24265 	if (sense) {
24266 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24267 	}
24268 	if (com) {
24269 		kmem_free(com, sizeof (*com));
24270 	}
24271 	return (rval);
24272 }
24273 
24274 
24275 /*
24276  *    Function: sr_pause_resume()
24277  *
24278  * Description: This routine is the driver entry point for handling CD-ROM
24279  *		pause/resume ioctl requests. This only affects the audio play
24280  *		operation.
24281  *
24282  *   Arguments: dev - the device 'dev_t'
24283  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
24284  *		      for setting the resume bit of the cdb.
24285  *
24286  * Return Code: the code returned by sd_send_scsi_cmd()
24287  *		EINVAL if invalid mode specified
24288  *
24289  */
24290 
24291 static int
24292 sr_pause_resume(dev_t dev, int cmd)
24293 {
24294 	struct sd_lun		*un;
24295 	struct uscsi_cmd	*com;
24296 	char			cdb[CDB_GROUP1];
24297 	int			rval;
24298 
24299 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24300 		return (ENXIO);
24301 	}
24302 
24303 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24304 	bzero(cdb, CDB_GROUP1);
24305 	cdb[0] = SCMD_PAUSE_RESUME;
24306 	switch (cmd) {
24307 	case CDROMRESUME:
24308 		cdb[8] = 1;
24309 		break;
24310 	case CDROMPAUSE:
24311 		cdb[8] = 0;
24312 		break;
24313 	default:
24314 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
24315 		    " Command '%x' Not Supported\n", cmd);
24316 		rval = EINVAL;
24317 		goto done;
24318 	}
24319 
24320 	com->uscsi_cdb    = cdb;
24321 	com->uscsi_cdblen = CDB_GROUP1;
24322 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24323 
24324 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24325 	    SD_PATH_STANDARD);
24326 
24327 done:
24328 	kmem_free(com, sizeof (*com));
24329 	return (rval);
24330 }
24331 
24332 
24333 /*
24334  *    Function: sr_play_msf()
24335  *
24336  * Description: This routine is the driver entry point for handling CD-ROM
24337  *		ioctl requests to output the audio signals at the specified
24338  *		starting address and continue the audio play until the specified
24339  *		ending address (CDROMPLAYMSF) The address is in Minute Second
24340  *		Frame (MSF) format.
24341  *
24342  *   Arguments: dev	- the device 'dev_t'
24343  *		data	- pointer to user provided audio msf structure,
24344  *		          specifying start/end addresses.
24345  *		flag	- this argument is a pass through to ddi_copyxxx()
24346  *		          directly from the mode argument of ioctl().
24347  *
24348  * Return Code: the code returned by sd_send_scsi_cmd()
24349  *		EFAULT if ddi_copyxxx() fails
24350  *		ENXIO if fail ddi_get_soft_state
24351  *		EINVAL if data pointer is NULL
24352  */
24353 
24354 static int
24355 sr_play_msf(dev_t dev, caddr_t data, int flag)
24356 {
24357 	struct sd_lun		*un;
24358 	struct uscsi_cmd	*com;
24359 	struct cdrom_msf	msf_struct;
24360 	struct cdrom_msf	*msf = &msf_struct;
24361 	char			cdb[CDB_GROUP1];
24362 	int			rval;
24363 
24364 	if (data == NULL) {
24365 		return (EINVAL);
24366 	}
24367 
24368 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24369 		return (ENXIO);
24370 	}
24371 
24372 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
24373 		return (EFAULT);
24374 	}
24375 
24376 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24377 	bzero(cdb, CDB_GROUP1);
24378 	cdb[0] = SCMD_PLAYAUDIO_MSF;
24379 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
24380 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
24381 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
24382 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
24383 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
24384 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
24385 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
24386 	} else {
24387 		cdb[3] = msf->cdmsf_min0;
24388 		cdb[4] = msf->cdmsf_sec0;
24389 		cdb[5] = msf->cdmsf_frame0;
24390 		cdb[6] = msf->cdmsf_min1;
24391 		cdb[7] = msf->cdmsf_sec1;
24392 		cdb[8] = msf->cdmsf_frame1;
24393 	}
24394 	com->uscsi_cdb    = cdb;
24395 	com->uscsi_cdblen = CDB_GROUP1;
24396 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24397 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24398 	    SD_PATH_STANDARD);
24399 	kmem_free(com, sizeof (*com));
24400 	return (rval);
24401 }
24402 
24403 
24404 /*
24405  *    Function: sr_play_trkind()
24406  *
24407  * Description: This routine is the driver entry point for handling CD-ROM
24408  *		ioctl requests to output the audio signals at the specified
24409  *		starting address and continue the audio play until the specified
24410  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
24411  *		format.
24412  *
24413  *   Arguments: dev	- the device 'dev_t'
24414  *		data	- pointer to user provided audio track/index structure,
24415  *		          specifying start/end addresses.
24416  *		flag	- this argument is a pass through to ddi_copyxxx()
24417  *		          directly from the mode argument of ioctl().
24418  *
24419  * Return Code: the code returned by sd_send_scsi_cmd()
24420  *		EFAULT if ddi_copyxxx() fails
24421  *		ENXIO if fail ddi_get_soft_state
24422  *		EINVAL if data pointer is NULL
24423  */
24424 
24425 static int
24426 sr_play_trkind(dev_t dev, caddr_t data, int flag)
24427 {
24428 	struct cdrom_ti		ti_struct;
24429 	struct cdrom_ti		*ti = &ti_struct;
24430 	struct uscsi_cmd	*com = NULL;
24431 	char			cdb[CDB_GROUP1];
24432 	int			rval;
24433 
24434 	if (data == NULL) {
24435 		return (EINVAL);
24436 	}
24437 
24438 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
24439 		return (EFAULT);
24440 	}
24441 
24442 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24443 	bzero(cdb, CDB_GROUP1);
24444 	cdb[0] = SCMD_PLAYAUDIO_TI;
24445 	cdb[4] = ti->cdti_trk0;
24446 	cdb[5] = ti->cdti_ind0;
24447 	cdb[7] = ti->cdti_trk1;
24448 	cdb[8] = ti->cdti_ind1;
24449 	com->uscsi_cdb    = cdb;
24450 	com->uscsi_cdblen = CDB_GROUP1;
24451 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24452 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24453 	    SD_PATH_STANDARD);
24454 	kmem_free(com, sizeof (*com));
24455 	return (rval);
24456 }
24457 
24458 
24459 /*
24460  *    Function: sr_read_all_subcodes()
24461  *
24462  * Description: This routine is the driver entry point for handling CD-ROM
24463  *		ioctl requests to return raw subcode data while the target is
24464  *		playing audio (CDROMSUBCODE).
24465  *
24466  *   Arguments: dev	- the device 'dev_t'
24467  *		data	- pointer to user provided cdrom subcode structure,
24468  *		          specifying the transfer length and address.
24469  *		flag	- this argument is a pass through to ddi_copyxxx()
24470  *		          directly from the mode argument of ioctl().
24471  *
24472  * Return Code: the code returned by sd_send_scsi_cmd()
24473  *		EFAULT if ddi_copyxxx() fails
24474  *		ENXIO if fail ddi_get_soft_state
24475  *		EINVAL if data pointer is NULL
24476  */
24477 
24478 static int
24479 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
24480 {
24481 	struct sd_lun		*un = NULL;
24482 	struct uscsi_cmd	*com = NULL;
24483 	struct cdrom_subcode	*subcode = NULL;
24484 	int			rval;
24485 	size_t			buflen;
24486 	char			cdb[CDB_GROUP5];
24487 
24488 #ifdef _MULTI_DATAMODEL
24489 	/* To support ILP32 applications in an LP64 world */
24490 	struct cdrom_subcode32		cdrom_subcode32;
24491 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
24492 #endif
24493 	if (data == NULL) {
24494 		return (EINVAL);
24495 	}
24496 
24497 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24498 		return (ENXIO);
24499 	}
24500 
24501 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
24502 
24503 #ifdef _MULTI_DATAMODEL
24504 	switch (ddi_model_convert_from(flag & FMODELS)) {
24505 	case DDI_MODEL_ILP32:
24506 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
24507 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24508 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24509 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24510 			return (EFAULT);
24511 		}
24512 		/* Convert the ILP32 uscsi data from the application to LP64 */
24513 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
24514 		break;
24515 	case DDI_MODEL_NONE:
24516 		if (ddi_copyin(data, subcode,
24517 		    sizeof (struct cdrom_subcode), flag)) {
24518 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24519 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24520 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24521 			return (EFAULT);
24522 		}
24523 		break;
24524 	}
24525 #else /* ! _MULTI_DATAMODEL */
24526 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
24527 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24528 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
24529 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24530 		return (EFAULT);
24531 	}
24532 #endif /* _MULTI_DATAMODEL */
24533 
24534 	/*
24535 	 * Since MMC-2 expects max 3 bytes for length, check if the
24536 	 * length input is greater than 3 bytes
24537 	 */
24538 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
24539 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24540 		    "sr_read_all_subcodes: "
24541 		    "cdrom transfer length too large: %d (limit %d)\n",
24542 		    subcode->cdsc_length, 0xFFFFFF);
24543 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24544 		return (EINVAL);
24545 	}
24546 
24547 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
24548 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24549 	bzero(cdb, CDB_GROUP5);
24550 
24551 	if (un->un_f_mmc_cap == TRUE) {
24552 		cdb[0] = (char)SCMD_READ_CD;
24553 		cdb[2] = (char)0xff;
24554 		cdb[3] = (char)0xff;
24555 		cdb[4] = (char)0xff;
24556 		cdb[5] = (char)0xff;
24557 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24558 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24559 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
24560 		cdb[10] = 1;
24561 	} else {
24562 		/*
24563 		 * Note: A vendor specific command (0xDF) is being used her to
24564 		 * request a read of all subcodes.
24565 		 */
24566 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
24567 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
24568 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24569 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24570 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
24571 	}
24572 	com->uscsi_cdb	   = cdb;
24573 	com->uscsi_cdblen  = CDB_GROUP5;
24574 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
24575 	com->uscsi_buflen  = buflen;
24576 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24577 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
24578 	    SD_PATH_STANDARD);
24579 	kmem_free(subcode, sizeof (struct cdrom_subcode));
24580 	kmem_free(com, sizeof (*com));
24581 	return (rval);
24582 }
24583 
24584 
24585 /*
24586  *    Function: sr_read_subchannel()
24587  *
24588  * Description: This routine is the driver entry point for handling CD-ROM
24589  *		ioctl requests to return the Q sub-channel data of the CD
24590  *		current position block. (CDROMSUBCHNL) The data includes the
24591  *		track number, index number, absolute CD-ROM address (LBA or MSF
24592  *		format per the user) , track relative CD-ROM address (LBA or MSF
24593  *		format per the user), control data and audio status.
24594  *
24595  *   Arguments: dev	- the device 'dev_t'
24596  *		data	- pointer to user provided cdrom sub-channel structure
24597  *		flag	- this argument is a pass through to ddi_copyxxx()
24598  *		          directly from the mode argument of ioctl().
24599  *
24600  * Return Code: the code returned by sd_send_scsi_cmd()
24601  *		EFAULT if ddi_copyxxx() fails
24602  *		ENXIO if fail ddi_get_soft_state
24603  *		EINVAL if data pointer is NULL
24604  */
24605 
24606 static int
24607 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
24608 {
24609 	struct sd_lun		*un;
24610 	struct uscsi_cmd	*com;
24611 	struct cdrom_subchnl	subchanel;
24612 	struct cdrom_subchnl	*subchnl = &subchanel;
24613 	char			cdb[CDB_GROUP1];
24614 	caddr_t			buffer;
24615 	int			rval;
24616 
24617 	if (data == NULL) {
24618 		return (EINVAL);
24619 	}
24620 
24621 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24622 	    (un->un_state == SD_STATE_OFFLINE)) {
24623 		return (ENXIO);
24624 	}
24625 
24626 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
24627 		return (EFAULT);
24628 	}
24629 
24630 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
24631 	bzero(cdb, CDB_GROUP1);
24632 	cdb[0] = SCMD_READ_SUBCHANNEL;
24633 	/* Set the MSF bit based on the user requested address format */
24634 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
24635 	/*
24636 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
24637 	 * returned
24638 	 */
24639 	cdb[2] = 0x40;
24640 	/*
24641 	 * Set byte 3 to specify the return data format. A value of 0x01
24642 	 * indicates that the CD-ROM current position should be returned.
24643 	 */
24644 	cdb[3] = 0x01;
24645 	cdb[8] = 0x10;
24646 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24647 	com->uscsi_cdb	   = cdb;
24648 	com->uscsi_cdblen  = CDB_GROUP1;
24649 	com->uscsi_bufaddr = buffer;
24650 	com->uscsi_buflen  = 16;
24651 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24652 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24653 	    SD_PATH_STANDARD);
24654 	if (rval != 0) {
24655 		kmem_free(buffer, 16);
24656 		kmem_free(com, sizeof (*com));
24657 		return (rval);
24658 	}
24659 
24660 	/* Process the returned Q sub-channel data */
24661 	subchnl->cdsc_audiostatus = buffer[1];
24662 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
24663 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
24664 	subchnl->cdsc_trk	= buffer[6];
24665 	subchnl->cdsc_ind	= buffer[7];
24666 	if (subchnl->cdsc_format & CDROM_LBA) {
24667 		subchnl->cdsc_absaddr.lba =
24668 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
24669 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
24670 		subchnl->cdsc_reladdr.lba =
24671 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
24672 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
24673 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
24674 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
24675 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
24676 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
24677 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
24678 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
24679 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
24680 	} else {
24681 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
24682 		subchnl->cdsc_absaddr.msf.second = buffer[10];
24683 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
24684 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
24685 		subchnl->cdsc_reladdr.msf.second = buffer[14];
24686 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
24687 	}
24688 	kmem_free(buffer, 16);
24689 	kmem_free(com, sizeof (*com));
24690 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
24691 	    != 0) {
24692 		return (EFAULT);
24693 	}
24694 	return (rval);
24695 }
24696 
24697 
24698 /*
24699  *    Function: sr_read_tocentry()
24700  *
24701  * Description: This routine is the driver entry point for handling CD-ROM
24702  *		ioctl requests to read from the Table of Contents (TOC)
24703  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
24704  *		fields, the starting address (LBA or MSF format per the user)
24705  *		and the data mode if the user specified track is a data track.
24706  *
24707  *		Note: The READ HEADER (0x44) command used in this routine is
24708  *		obsolete per the SCSI MMC spec but still supported in the
24709  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
24710  *		therefore the command is still implemented in this routine.
24711  *
24712  *   Arguments: dev	- the device 'dev_t'
24713  *		data	- pointer to user provided toc entry structure,
24714  *			  specifying the track # and the address format
24715  *			  (LBA or MSF).
24716  *		flag	- this argument is a pass through to ddi_copyxxx()
24717  *		          directly from the mode argument of ioctl().
24718  *
24719  * Return Code: the code returned by sd_send_scsi_cmd()
24720  *		EFAULT if ddi_copyxxx() fails
24721  *		ENXIO if fail ddi_get_soft_state
24722  *		EINVAL if data pointer is NULL
24723  */
24724 
24725 static int
24726 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
24727 {
24728 	struct sd_lun		*un = NULL;
24729 	struct uscsi_cmd	*com;
24730 	struct cdrom_tocentry	toc_entry;
24731 	struct cdrom_tocentry	*entry = &toc_entry;
24732 	caddr_t			buffer;
24733 	int			rval;
24734 	char			cdb[CDB_GROUP1];
24735 
24736 	if (data == NULL) {
24737 		return (EINVAL);
24738 	}
24739 
24740 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24741 	    (un->un_state == SD_STATE_OFFLINE)) {
24742 		return (ENXIO);
24743 	}
24744 
24745 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
24746 		return (EFAULT);
24747 	}
24748 
24749 	/* Validate the requested track and address format */
24750 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
24751 		return (EINVAL);
24752 	}
24753 
24754 	if (entry->cdte_track == 0) {
24755 		return (EINVAL);
24756 	}
24757 
24758 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
24759 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24760 	bzero(cdb, CDB_GROUP1);
24761 
24762 	cdb[0] = SCMD_READ_TOC;
24763 	/* Set the MSF bit based on the user requested address format  */
24764 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
24765 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
24766 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
24767 	} else {
24768 		cdb[6] = entry->cdte_track;
24769 	}
24770 
24771 	/*
24772 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
24773 	 * (4 byte TOC response header + 8 byte track descriptor)
24774 	 */
24775 	cdb[8] = 12;
24776 	com->uscsi_cdb	   = cdb;
24777 	com->uscsi_cdblen  = CDB_GROUP1;
24778 	com->uscsi_bufaddr = buffer;
24779 	com->uscsi_buflen  = 0x0C;
24780 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
24781 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24782 	    SD_PATH_STANDARD);
24783 	if (rval != 0) {
24784 		kmem_free(buffer, 12);
24785 		kmem_free(com, sizeof (*com));
24786 		return (rval);
24787 	}
24788 
24789 	/* Process the toc entry */
24790 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
24791 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
24792 	if (entry->cdte_format & CDROM_LBA) {
24793 		entry->cdte_addr.lba =
24794 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
24795 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
24796 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
24797 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
24798 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
24799 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
24800 		/*
24801 		 * Send a READ TOC command using the LBA address format to get
24802 		 * the LBA for the track requested so it can be used in the
24803 		 * READ HEADER request
24804 		 *
24805 		 * Note: The MSF bit of the READ HEADER command specifies the
24806 		 * output format. The block address specified in that command
24807 		 * must be in LBA format.
24808 		 */
24809 		cdb[1] = 0;
24810 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24811 		    SD_PATH_STANDARD);
24812 		if (rval != 0) {
24813 			kmem_free(buffer, 12);
24814 			kmem_free(com, sizeof (*com));
24815 			return (rval);
24816 		}
24817 	} else {
24818 		entry->cdte_addr.msf.minute	= buffer[9];
24819 		entry->cdte_addr.msf.second	= buffer[10];
24820 		entry->cdte_addr.msf.frame	= buffer[11];
24821 		/*
24822 		 * Send a READ TOC command using the LBA address format to get
24823 		 * the LBA for the track requested so it can be used in the
24824 		 * READ HEADER request
24825 		 *
24826 		 * Note: The MSF bit of the READ HEADER command specifies the
24827 		 * output format. The block address specified in that command
24828 		 * must be in LBA format.
24829 		 */
24830 		cdb[1] = 0;
24831 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24832 		    SD_PATH_STANDARD);
24833 		if (rval != 0) {
24834 			kmem_free(buffer, 12);
24835 			kmem_free(com, sizeof (*com));
24836 			return (rval);
24837 		}
24838 	}
24839 
24840 	/*
24841 	 * Build and send the READ HEADER command to determine the data mode of
24842 	 * the user specified track.
24843 	 */
24844 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
24845 	    (entry->cdte_track != CDROM_LEADOUT)) {
24846 		bzero(cdb, CDB_GROUP1);
24847 		cdb[0] = SCMD_READ_HEADER;
24848 		cdb[2] = buffer[8];
24849 		cdb[3] = buffer[9];
24850 		cdb[4] = buffer[10];
24851 		cdb[5] = buffer[11];
24852 		cdb[8] = 0x08;
24853 		com->uscsi_buflen = 0x08;
24854 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24855 		    SD_PATH_STANDARD);
24856 		if (rval == 0) {
24857 			entry->cdte_datamode = buffer[0];
24858 		} else {
24859 			/*
24860 			 * READ HEADER command failed, since this is
24861 			 * obsoleted in one spec, its better to return
24862 			 * -1 for an invlid track so that we can still
24863 			 * receive the rest of the TOC data.
24864 			 */
24865 			entry->cdte_datamode = (uchar_t)-1;
24866 		}
24867 	} else {
24868 		entry->cdte_datamode = (uchar_t)-1;
24869 	}
24870 
24871 	kmem_free(buffer, 12);
24872 	kmem_free(com, sizeof (*com));
24873 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
24874 		return (EFAULT);
24875 
24876 	return (rval);
24877 }
24878 
24879 
24880 /*
24881  *    Function: sr_read_tochdr()
24882  *
24883  * Description: This routine is the driver entry point for handling CD-ROM
24884  * 		ioctl requests to read the Table of Contents (TOC) header
24885  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
24886  *		and ending track numbers
24887  *
24888  *   Arguments: dev	- the device 'dev_t'
24889  *		data	- pointer to user provided toc header structure,
24890  *			  specifying the starting and ending track numbers.
24891  *		flag	- this argument is a pass through to ddi_copyxxx()
24892  *			  directly from the mode argument of ioctl().
24893  *
24894  * Return Code: the code returned by sd_send_scsi_cmd()
24895  *		EFAULT if ddi_copyxxx() fails
24896  *		ENXIO if fail ddi_get_soft_state
24897  *		EINVAL if data pointer is NULL
24898  */
24899 
24900 static int
24901 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
24902 {
24903 	struct sd_lun		*un;
24904 	struct uscsi_cmd	*com;
24905 	struct cdrom_tochdr	toc_header;
24906 	struct cdrom_tochdr	*hdr = &toc_header;
24907 	char			cdb[CDB_GROUP1];
24908 	int			rval;
24909 	caddr_t			buffer;
24910 
24911 	if (data == NULL) {
24912 		return (EINVAL);
24913 	}
24914 
24915 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24916 	    (un->un_state == SD_STATE_OFFLINE)) {
24917 		return (ENXIO);
24918 	}
24919 
24920 	buffer = kmem_zalloc(4, KM_SLEEP);
24921 	bzero(cdb, CDB_GROUP1);
24922 	cdb[0] = SCMD_READ_TOC;
24923 	/*
24924 	 * Specifying a track number of 0x00 in the READ TOC command indicates
24925 	 * that the TOC header should be returned
24926 	 */
24927 	cdb[6] = 0x00;
24928 	/*
24929 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
24930 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
24931 	 */
24932 	cdb[8] = 0x04;
24933 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24934 	com->uscsi_cdb	   = cdb;
24935 	com->uscsi_cdblen  = CDB_GROUP1;
24936 	com->uscsi_bufaddr = buffer;
24937 	com->uscsi_buflen  = 0x04;
24938 	com->uscsi_timeout = 300;
24939 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24940 
24941 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24942 	    SD_PATH_STANDARD);
24943 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
24944 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
24945 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
24946 	} else {
24947 		hdr->cdth_trk0 = buffer[2];
24948 		hdr->cdth_trk1 = buffer[3];
24949 	}
24950 	kmem_free(buffer, 4);
24951 	kmem_free(com, sizeof (*com));
24952 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
24953 		return (EFAULT);
24954 	}
24955 	return (rval);
24956 }
24957 
24958 
24959 /*
24960  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
24961  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
24962  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
24963  * digital audio and extended architecture digital audio. These modes are
24964  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
24965  * MMC specs.
24966  *
24967  * In addition to support for the various data formats these routines also
24968  * include support for devices that implement only the direct access READ
24969  * commands (0x08, 0x28), devices that implement the READ_CD commands
24970  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
24971  * READ CDXA commands (0xD8, 0xDB)
24972  */
24973 
24974 /*
24975  *    Function: sr_read_mode1()
24976  *
24977  * Description: This routine is the driver entry point for handling CD-ROM
24978  *		ioctl read mode1 requests (CDROMREADMODE1).
24979  *
24980  *   Arguments: dev	- the device 'dev_t'
24981  *		data	- pointer to user provided cd read structure specifying
24982  *			  the lba buffer address and length.
24983  *		flag	- this argument is a pass through to ddi_copyxxx()
24984  *			  directly from the mode argument of ioctl().
24985  *
24986  * Return Code: the code returned by sd_send_scsi_cmd()
24987  *		EFAULT if ddi_copyxxx() fails
24988  *		ENXIO if fail ddi_get_soft_state
24989  *		EINVAL if data pointer is NULL
24990  */
24991 
24992 static int
24993 sr_read_mode1(dev_t dev, caddr_t data, int flag)
24994 {
24995 	struct sd_lun		*un;
24996 	struct cdrom_read	mode1_struct;
24997 	struct cdrom_read	*mode1 = &mode1_struct;
24998 	int			rval;
24999 #ifdef _MULTI_DATAMODEL
25000 	/* To support ILP32 applications in an LP64 world */
25001 	struct cdrom_read32	cdrom_read32;
25002 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25003 #endif /* _MULTI_DATAMODEL */
25004 
25005 	if (data == NULL) {
25006 		return (EINVAL);
25007 	}
25008 
25009 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25010 	    (un->un_state == SD_STATE_OFFLINE)) {
25011 		return (ENXIO);
25012 	}
25013 
25014 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25015 	    "sd_read_mode1: entry: un:0x%p\n", un);
25016 
25017 #ifdef _MULTI_DATAMODEL
25018 	switch (ddi_model_convert_from(flag & FMODELS)) {
25019 	case DDI_MODEL_ILP32:
25020 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25021 			return (EFAULT);
25022 		}
25023 		/* Convert the ILP32 uscsi data from the application to LP64 */
25024 		cdrom_read32tocdrom_read(cdrd32, mode1);
25025 		break;
25026 	case DDI_MODEL_NONE:
25027 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
25028 			return (EFAULT);
25029 		}
25030 	}
25031 #else /* ! _MULTI_DATAMODEL */
25032 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
25033 		return (EFAULT);
25034 	}
25035 #endif /* _MULTI_DATAMODEL */
25036 
25037 	rval = sd_send_scsi_READ(un, mode1->cdread_bufaddr,
25038 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
25039 
25040 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25041 	    "sd_read_mode1: exit: un:0x%p\n", un);
25042 
25043 	return (rval);
25044 }
25045 
25046 
25047 /*
25048  *    Function: sr_read_cd_mode2()
25049  *
25050  * Description: This routine is the driver entry point for handling CD-ROM
25051  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
25052  *		support the READ CD (0xBE) command or the 1st generation
25053  *		READ CD (0xD4) command.
25054  *
25055  *   Arguments: dev	- the device 'dev_t'
25056  *		data	- pointer to user provided cd read structure specifying
25057  *			  the lba buffer address and length.
25058  *		flag	- this argument is a pass through to ddi_copyxxx()
25059  *			  directly from the mode argument of ioctl().
25060  *
25061  * Return Code: the code returned by sd_send_scsi_cmd()
25062  *		EFAULT if ddi_copyxxx() fails
25063  *		ENXIO if fail ddi_get_soft_state
25064  *		EINVAL if data pointer is NULL
25065  */
25066 
25067 static int
25068 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
25069 {
25070 	struct sd_lun		*un;
25071 	struct uscsi_cmd	*com;
25072 	struct cdrom_read	mode2_struct;
25073 	struct cdrom_read	*mode2 = &mode2_struct;
25074 	uchar_t			cdb[CDB_GROUP5];
25075 	int			nblocks;
25076 	int			rval;
25077 #ifdef _MULTI_DATAMODEL
25078 	/*  To support ILP32 applications in an LP64 world */
25079 	struct cdrom_read32	cdrom_read32;
25080 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25081 #endif /* _MULTI_DATAMODEL */
25082 
25083 	if (data == NULL) {
25084 		return (EINVAL);
25085 	}
25086 
25087 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25088 	    (un->un_state == SD_STATE_OFFLINE)) {
25089 		return (ENXIO);
25090 	}
25091 
25092 #ifdef _MULTI_DATAMODEL
25093 	switch (ddi_model_convert_from(flag & FMODELS)) {
25094 	case DDI_MODEL_ILP32:
25095 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25096 			return (EFAULT);
25097 		}
25098 		/* Convert the ILP32 uscsi data from the application to LP64 */
25099 		cdrom_read32tocdrom_read(cdrd32, mode2);
25100 		break;
25101 	case DDI_MODEL_NONE:
25102 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25103 			return (EFAULT);
25104 		}
25105 		break;
25106 	}
25107 
25108 #else /* ! _MULTI_DATAMODEL */
25109 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25110 		return (EFAULT);
25111 	}
25112 #endif /* _MULTI_DATAMODEL */
25113 
25114 	bzero(cdb, sizeof (cdb));
25115 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
25116 		/* Read command supported by 1st generation atapi drives */
25117 		cdb[0] = SCMD_READ_CDD4;
25118 	} else {
25119 		/* Universal CD Access Command */
25120 		cdb[0] = SCMD_READ_CD;
25121 	}
25122 
25123 	/*
25124 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
25125 	 */
25126 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
25127 
25128 	/* set the start address */
25129 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
25130 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
25131 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
25132 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
25133 
25134 	/* set the transfer length */
25135 	nblocks = mode2->cdread_buflen / 2336;
25136 	cdb[6] = (uchar_t)(nblocks >> 16);
25137 	cdb[7] = (uchar_t)(nblocks >> 8);
25138 	cdb[8] = (uchar_t)nblocks;
25139 
25140 	/* set the filter bits */
25141 	cdb[9] = CDROM_READ_CD_USERDATA;
25142 
25143 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25144 	com->uscsi_cdb = (caddr_t)cdb;
25145 	com->uscsi_cdblen = sizeof (cdb);
25146 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
25147 	com->uscsi_buflen = mode2->cdread_buflen;
25148 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25149 
25150 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25151 	    SD_PATH_STANDARD);
25152 	kmem_free(com, sizeof (*com));
25153 	return (rval);
25154 }
25155 
25156 
25157 /*
25158  *    Function: sr_read_mode2()
25159  *
25160  * Description: This routine is the driver entry point for handling CD-ROM
25161  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
25162  *		do not support the READ CD (0xBE) command.
25163  *
25164  *   Arguments: dev	- the device 'dev_t'
25165  *		data	- pointer to user provided cd read structure specifying
25166  *			  the lba buffer address and length.
25167  *		flag	- this argument is a pass through to ddi_copyxxx()
25168  *			  directly from the mode argument of ioctl().
25169  *
25170  * Return Code: the code returned by sd_send_scsi_cmd()
25171  *		EFAULT if ddi_copyxxx() fails
25172  *		ENXIO if fail ddi_get_soft_state
25173  *		EINVAL if data pointer is NULL
25174  *		EIO if fail to reset block size
25175  *		EAGAIN if commands are in progress in the driver
25176  */
25177 
25178 static int
25179 sr_read_mode2(dev_t dev, caddr_t data, int flag)
25180 {
25181 	struct sd_lun		*un;
25182 	struct cdrom_read	mode2_struct;
25183 	struct cdrom_read	*mode2 = &mode2_struct;
25184 	int			rval;
25185 	uint32_t		restore_blksize;
25186 	struct uscsi_cmd	*com;
25187 	uchar_t			cdb[CDB_GROUP0];
25188 	int			nblocks;
25189 
25190 #ifdef _MULTI_DATAMODEL
25191 	/* To support ILP32 applications in an LP64 world */
25192 	struct cdrom_read32	cdrom_read32;
25193 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25194 #endif /* _MULTI_DATAMODEL */
25195 
25196 	if (data == NULL) {
25197 		return (EINVAL);
25198 	}
25199 
25200 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25201 	    (un->un_state == SD_STATE_OFFLINE)) {
25202 		return (ENXIO);
25203 	}
25204 
25205 	/*
25206 	 * Because this routine will update the device and driver block size
25207 	 * being used we want to make sure there are no commands in progress.
25208 	 * If commands are in progress the user will have to try again.
25209 	 *
25210 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
25211 	 * in sdioctl to protect commands from sdioctl through to the top of
25212 	 * sd_uscsi_strategy. See sdioctl for details.
25213 	 */
25214 	mutex_enter(SD_MUTEX(un));
25215 	if (un->un_ncmds_in_driver != 1) {
25216 		mutex_exit(SD_MUTEX(un));
25217 		return (EAGAIN);
25218 	}
25219 	mutex_exit(SD_MUTEX(un));
25220 
25221 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25222 	    "sd_read_mode2: entry: un:0x%p\n", un);
25223 
25224 #ifdef _MULTI_DATAMODEL
25225 	switch (ddi_model_convert_from(flag & FMODELS)) {
25226 	case DDI_MODEL_ILP32:
25227 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25228 			return (EFAULT);
25229 		}
25230 		/* Convert the ILP32 uscsi data from the application to LP64 */
25231 		cdrom_read32tocdrom_read(cdrd32, mode2);
25232 		break;
25233 	case DDI_MODEL_NONE:
25234 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25235 			return (EFAULT);
25236 		}
25237 		break;
25238 	}
25239 #else /* ! _MULTI_DATAMODEL */
25240 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
25241 		return (EFAULT);
25242 	}
25243 #endif /* _MULTI_DATAMODEL */
25244 
25245 	/* Store the current target block size for restoration later */
25246 	restore_blksize = un->un_tgt_blocksize;
25247 
25248 	/* Change the device and soft state target block size to 2336 */
25249 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
25250 		rval = EIO;
25251 		goto done;
25252 	}
25253 
25254 
25255 	bzero(cdb, sizeof (cdb));
25256 
25257 	/* set READ operation */
25258 	cdb[0] = SCMD_READ;
25259 
25260 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
25261 	mode2->cdread_lba >>= 2;
25262 
25263 	/* set the start address */
25264 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
25265 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
25266 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
25267 
25268 	/* set the transfer length */
25269 	nblocks = mode2->cdread_buflen / 2336;
25270 	cdb[4] = (uchar_t)nblocks & 0xFF;
25271 
25272 	/* build command */
25273 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25274 	com->uscsi_cdb = (caddr_t)cdb;
25275 	com->uscsi_cdblen = sizeof (cdb);
25276 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
25277 	com->uscsi_buflen = mode2->cdread_buflen;
25278 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25279 
25280 	/*
25281 	 * Issue SCSI command with user space address for read buffer.
25282 	 *
25283 	 * This sends the command through main channel in the driver.
25284 	 *
25285 	 * Since this is accessed via an IOCTL call, we go through the
25286 	 * standard path, so that if the device was powered down, then
25287 	 * it would be 'awakened' to handle the command.
25288 	 */
25289 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25290 	    SD_PATH_STANDARD);
25291 
25292 	kmem_free(com, sizeof (*com));
25293 
25294 	/* Restore the device and soft state target block size */
25295 	if (sr_sector_mode(dev, restore_blksize) != 0) {
25296 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25297 		    "can't do switch back to mode 1\n");
25298 		/*
25299 		 * If sd_send_scsi_READ succeeded we still need to report
25300 		 * an error because we failed to reset the block size
25301 		 */
25302 		if (rval == 0) {
25303 			rval = EIO;
25304 		}
25305 	}
25306 
25307 done:
25308 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25309 	    "sd_read_mode2: exit: un:0x%p\n", un);
25310 
25311 	return (rval);
25312 }
25313 
25314 
25315 /*
25316  *    Function: sr_sector_mode()
25317  *
25318  * Description: This utility function is used by sr_read_mode2 to set the target
25319  *		block size based on the user specified size. This is a legacy
25320  *		implementation based upon a vendor specific mode page
25321  *
25322  *   Arguments: dev	- the device 'dev_t'
25323  *		data	- flag indicating if block size is being set to 2336 or
25324  *			  512.
25325  *
25326  * Return Code: the code returned by sd_send_scsi_cmd()
25327  *		EFAULT if ddi_copyxxx() fails
25328  *		ENXIO if fail ddi_get_soft_state
25329  *		EINVAL if data pointer is NULL
25330  */
25331 
25332 static int
25333 sr_sector_mode(dev_t dev, uint32_t blksize)
25334 {
25335 	struct sd_lun	*un;
25336 	uchar_t		*sense;
25337 	uchar_t		*select;
25338 	int		rval;
25339 
25340 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25341 	    (un->un_state == SD_STATE_OFFLINE)) {
25342 		return (ENXIO);
25343 	}
25344 
25345 	sense = kmem_zalloc(20, KM_SLEEP);
25346 
25347 	/* Note: This is a vendor specific mode page (0x81) */
25348 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, 20, 0x81,
25349 	    SD_PATH_STANDARD)) != 0) {
25350 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25351 		    "sr_sector_mode: Mode Sense failed\n");
25352 		kmem_free(sense, 20);
25353 		return (rval);
25354 	}
25355 	select = kmem_zalloc(20, KM_SLEEP);
25356 	select[3] = 0x08;
25357 	select[10] = ((blksize >> 8) & 0xff);
25358 	select[11] = (blksize & 0xff);
25359 	select[12] = 0x01;
25360 	select[13] = 0x06;
25361 	select[14] = sense[14];
25362 	select[15] = sense[15];
25363 	if (blksize == SD_MODE2_BLKSIZE) {
25364 		select[14] |= 0x01;
25365 	}
25366 
25367 	if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select, 20,
25368 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
25369 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25370 		    "sr_sector_mode: Mode Select failed\n");
25371 	} else {
25372 		/*
25373 		 * Only update the softstate block size if we successfully
25374 		 * changed the device block mode.
25375 		 */
25376 		mutex_enter(SD_MUTEX(un));
25377 		sd_update_block_info(un, blksize, 0);
25378 		mutex_exit(SD_MUTEX(un));
25379 	}
25380 	kmem_free(sense, 20);
25381 	kmem_free(select, 20);
25382 	return (rval);
25383 }
25384 
25385 
25386 /*
25387  *    Function: sr_read_cdda()
25388  *
25389  * Description: This routine is the driver entry point for handling CD-ROM
25390  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
25391  *		the target supports CDDA these requests are handled via a vendor
25392  *		specific command (0xD8) If the target does not support CDDA
25393  *		these requests are handled via the READ CD command (0xBE).
25394  *
25395  *   Arguments: dev	- the device 'dev_t'
25396  *		data	- pointer to user provided CD-DA structure specifying
25397  *			  the track starting address, transfer length, and
25398  *			  subcode options.
25399  *		flag	- this argument is a pass through to ddi_copyxxx()
25400  *			  directly from the mode argument of ioctl().
25401  *
25402  * Return Code: the code returned by sd_send_scsi_cmd()
25403  *		EFAULT if ddi_copyxxx() fails
25404  *		ENXIO if fail ddi_get_soft_state
25405  *		EINVAL if invalid arguments are provided
25406  *		ENOTTY
25407  */
25408 
25409 static int
25410 sr_read_cdda(dev_t dev, caddr_t data, int flag)
25411 {
25412 	struct sd_lun			*un;
25413 	struct uscsi_cmd		*com;
25414 	struct cdrom_cdda		*cdda;
25415 	int				rval;
25416 	size_t				buflen;
25417 	char				cdb[CDB_GROUP5];
25418 
25419 #ifdef _MULTI_DATAMODEL
25420 	/* To support ILP32 applications in an LP64 world */
25421 	struct cdrom_cdda32	cdrom_cdda32;
25422 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
25423 #endif /* _MULTI_DATAMODEL */
25424 
25425 	if (data == NULL) {
25426 		return (EINVAL);
25427 	}
25428 
25429 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25430 		return (ENXIO);
25431 	}
25432 
25433 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
25434 
25435 #ifdef _MULTI_DATAMODEL
25436 	switch (ddi_model_convert_from(flag & FMODELS)) {
25437 	case DDI_MODEL_ILP32:
25438 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
25439 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25440 			    "sr_read_cdda: ddi_copyin Failed\n");
25441 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25442 			return (EFAULT);
25443 		}
25444 		/* Convert the ILP32 uscsi data from the application to LP64 */
25445 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
25446 		break;
25447 	case DDI_MODEL_NONE:
25448 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25449 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25450 			    "sr_read_cdda: ddi_copyin Failed\n");
25451 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25452 			return (EFAULT);
25453 		}
25454 		break;
25455 	}
25456 #else /* ! _MULTI_DATAMODEL */
25457 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25458 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25459 		    "sr_read_cdda: ddi_copyin Failed\n");
25460 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25461 		return (EFAULT);
25462 	}
25463 #endif /* _MULTI_DATAMODEL */
25464 
25465 	/*
25466 	 * Since MMC-2 expects max 3 bytes for length, check if the
25467 	 * length input is greater than 3 bytes
25468 	 */
25469 	if ((cdda->cdda_length & 0xFF000000) != 0) {
25470 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
25471 		    "cdrom transfer length too large: %d (limit %d)\n",
25472 		    cdda->cdda_length, 0xFFFFFF);
25473 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25474 		return (EINVAL);
25475 	}
25476 
25477 	switch (cdda->cdda_subcode) {
25478 	case CDROM_DA_NO_SUBCODE:
25479 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
25480 		break;
25481 	case CDROM_DA_SUBQ:
25482 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
25483 		break;
25484 	case CDROM_DA_ALL_SUBCODE:
25485 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
25486 		break;
25487 	case CDROM_DA_SUBCODE_ONLY:
25488 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
25489 		break;
25490 	default:
25491 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25492 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
25493 		    cdda->cdda_subcode);
25494 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25495 		return (EINVAL);
25496 	}
25497 
25498 	/* Build and send the command */
25499 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25500 	bzero(cdb, CDB_GROUP5);
25501 
25502 	if (un->un_f_cfg_cdda == TRUE) {
25503 		cdb[0] = (char)SCMD_READ_CD;
25504 		cdb[1] = 0x04;
25505 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25506 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25507 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25508 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25509 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25510 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25511 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
25512 		cdb[9] = 0x10;
25513 		switch (cdda->cdda_subcode) {
25514 		case CDROM_DA_NO_SUBCODE :
25515 			cdb[10] = 0x0;
25516 			break;
25517 		case CDROM_DA_SUBQ :
25518 			cdb[10] = 0x2;
25519 			break;
25520 		case CDROM_DA_ALL_SUBCODE :
25521 			cdb[10] = 0x1;
25522 			break;
25523 		case CDROM_DA_SUBCODE_ONLY :
25524 			/* FALLTHROUGH */
25525 		default :
25526 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25527 			kmem_free(com, sizeof (*com));
25528 			return (ENOTTY);
25529 		}
25530 	} else {
25531 		cdb[0] = (char)SCMD_READ_CDDA;
25532 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25533 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25534 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25535 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25536 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
25537 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25538 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25539 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
25540 		cdb[10] = cdda->cdda_subcode;
25541 	}
25542 
25543 	com->uscsi_cdb = cdb;
25544 	com->uscsi_cdblen = CDB_GROUP5;
25545 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
25546 	com->uscsi_buflen = buflen;
25547 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25548 
25549 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25550 	    SD_PATH_STANDARD);
25551 
25552 	kmem_free(cdda, sizeof (struct cdrom_cdda));
25553 	kmem_free(com, sizeof (*com));
25554 	return (rval);
25555 }
25556 
25557 
25558 /*
25559  *    Function: sr_read_cdxa()
25560  *
25561  * Description: This routine is the driver entry point for handling CD-ROM
25562  *		ioctl requests to return CD-XA (Extended Architecture) data.
25563  *		(CDROMCDXA).
25564  *
25565  *   Arguments: dev	- the device 'dev_t'
25566  *		data	- pointer to user provided CD-XA structure specifying
25567  *			  the data starting address, transfer length, and format
25568  *		flag	- this argument is a pass through to ddi_copyxxx()
25569  *			  directly from the mode argument of ioctl().
25570  *
25571  * Return Code: the code returned by sd_send_scsi_cmd()
25572  *		EFAULT if ddi_copyxxx() fails
25573  *		ENXIO if fail ddi_get_soft_state
25574  *		EINVAL if data pointer is NULL
25575  */
25576 
25577 static int
25578 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
25579 {
25580 	struct sd_lun		*un;
25581 	struct uscsi_cmd	*com;
25582 	struct cdrom_cdxa	*cdxa;
25583 	int			rval;
25584 	size_t			buflen;
25585 	char			cdb[CDB_GROUP5];
25586 	uchar_t			read_flags;
25587 
25588 #ifdef _MULTI_DATAMODEL
25589 	/* To support ILP32 applications in an LP64 world */
25590 	struct cdrom_cdxa32		cdrom_cdxa32;
25591 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
25592 #endif /* _MULTI_DATAMODEL */
25593 
25594 	if (data == NULL) {
25595 		return (EINVAL);
25596 	}
25597 
25598 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25599 		return (ENXIO);
25600 	}
25601 
25602 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
25603 
25604 #ifdef _MULTI_DATAMODEL
25605 	switch (ddi_model_convert_from(flag & FMODELS)) {
25606 	case DDI_MODEL_ILP32:
25607 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
25608 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25609 			return (EFAULT);
25610 		}
25611 		/*
25612 		 * Convert the ILP32 uscsi data from the
25613 		 * application to LP64 for internal use.
25614 		 */
25615 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
25616 		break;
25617 	case DDI_MODEL_NONE:
25618 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25619 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25620 			return (EFAULT);
25621 		}
25622 		break;
25623 	}
25624 #else /* ! _MULTI_DATAMODEL */
25625 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25626 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25627 		return (EFAULT);
25628 	}
25629 #endif /* _MULTI_DATAMODEL */
25630 
25631 	/*
25632 	 * Since MMC-2 expects max 3 bytes for length, check if the
25633 	 * length input is greater than 3 bytes
25634 	 */
25635 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
25636 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
25637 		    "cdrom transfer length too large: %d (limit %d)\n",
25638 		    cdxa->cdxa_length, 0xFFFFFF);
25639 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25640 		return (EINVAL);
25641 	}
25642 
25643 	switch (cdxa->cdxa_format) {
25644 	case CDROM_XA_DATA:
25645 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
25646 		read_flags = 0x10;
25647 		break;
25648 	case CDROM_XA_SECTOR_DATA:
25649 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
25650 		read_flags = 0xf8;
25651 		break;
25652 	case CDROM_XA_DATA_W_ERROR:
25653 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
25654 		read_flags = 0xfc;
25655 		break;
25656 	default:
25657 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25658 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
25659 		    cdxa->cdxa_format);
25660 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25661 		return (EINVAL);
25662 	}
25663 
25664 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25665 	bzero(cdb, CDB_GROUP5);
25666 	if (un->un_f_mmc_cap == TRUE) {
25667 		cdb[0] = (char)SCMD_READ_CD;
25668 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25669 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25670 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25671 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25672 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25673 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25674 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
25675 		cdb[9] = (char)read_flags;
25676 	} else {
25677 		/*
25678 		 * Note: A vendor specific command (0xDB) is being used her to
25679 		 * request a read of all subcodes.
25680 		 */
25681 		cdb[0] = (char)SCMD_READ_CDXA;
25682 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25683 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25684 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25685 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25686 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
25687 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25688 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25689 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
25690 		cdb[10] = cdxa->cdxa_format;
25691 	}
25692 	com->uscsi_cdb	   = cdb;
25693 	com->uscsi_cdblen  = CDB_GROUP5;
25694 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
25695 	com->uscsi_buflen  = buflen;
25696 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25697 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25698 	    SD_PATH_STANDARD);
25699 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25700 	kmem_free(com, sizeof (*com));
25701 	return (rval);
25702 }
25703 
25704 
25705 /*
25706  *    Function: sr_eject()
25707  *
25708  * Description: This routine is the driver entry point for handling CD-ROM
25709  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
25710  *
25711  *   Arguments: dev	- the device 'dev_t'
25712  *
25713  * Return Code: the code returned by sd_send_scsi_cmd()
25714  */
25715 
25716 static int
25717 sr_eject(dev_t dev)
25718 {
25719 	struct sd_lun	*un;
25720 	int		rval;
25721 
25722 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25723 	    (un->un_state == SD_STATE_OFFLINE)) {
25724 		return (ENXIO);
25725 	}
25726 
25727 	/*
25728 	 * To prevent race conditions with the eject
25729 	 * command, keep track of an eject command as
25730 	 * it progresses. If we are already handling
25731 	 * an eject command in the driver for the given
25732 	 * unit and another request to eject is received
25733 	 * immediately return EAGAIN so we don't lose
25734 	 * the command if the current eject command fails.
25735 	 */
25736 	mutex_enter(SD_MUTEX(un));
25737 	if (un->un_f_ejecting == TRUE) {
25738 		mutex_exit(SD_MUTEX(un));
25739 		return (EAGAIN);
25740 	}
25741 	un->un_f_ejecting = TRUE;
25742 	mutex_exit(SD_MUTEX(un));
25743 
25744 	if ((rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
25745 	    SD_PATH_STANDARD)) != 0) {
25746 		mutex_enter(SD_MUTEX(un));
25747 		un->un_f_ejecting = FALSE;
25748 		mutex_exit(SD_MUTEX(un));
25749 		return (rval);
25750 	}
25751 
25752 	rval = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_EJECT,
25753 	    SD_PATH_STANDARD);
25754 
25755 	if (rval == 0) {
25756 		mutex_enter(SD_MUTEX(un));
25757 		sr_ejected(un);
25758 		un->un_mediastate = DKIO_EJECTED;
25759 		un->un_f_ejecting = FALSE;
25760 		cv_broadcast(&un->un_state_cv);
25761 		mutex_exit(SD_MUTEX(un));
25762 	} else {
25763 		mutex_enter(SD_MUTEX(un));
25764 		un->un_f_ejecting = FALSE;
25765 		mutex_exit(SD_MUTEX(un));
25766 	}
25767 	return (rval);
25768 }
25769 
25770 
25771 /*
25772  *    Function: sr_ejected()
25773  *
25774  * Description: This routine updates the soft state structure to invalidate the
25775  *		geometry information after the media has been ejected or a
25776  *		media eject has been detected.
25777  *
25778  *   Arguments: un - driver soft state (unit) structure
25779  */
25780 
25781 static void
25782 sr_ejected(struct sd_lun *un)
25783 {
25784 	struct sd_errstats *stp;
25785 
25786 	ASSERT(un != NULL);
25787 	ASSERT(mutex_owned(SD_MUTEX(un)));
25788 
25789 	un->un_f_blockcount_is_valid	= FALSE;
25790 	un->un_f_tgt_blocksize_is_valid	= FALSE;
25791 	mutex_exit(SD_MUTEX(un));
25792 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
25793 	mutex_enter(SD_MUTEX(un));
25794 
25795 	if (un->un_errstats != NULL) {
25796 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
25797 		stp->sd_capacity.value.ui64 = 0;
25798 	}
25799 
25800 	/* remove "capacity-of-device" properties */
25801 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
25802 	    "device-nblocks");
25803 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
25804 	    "device-blksize");
25805 }
25806 
25807 
25808 /*
25809  *    Function: sr_check_wp()
25810  *
25811  * Description: This routine checks the write protection of a removable
25812  *      media disk and hotpluggable devices via the write protect bit of
25813  *      the Mode Page Header device specific field. Some devices choke
25814  *      on unsupported mode page. In order to workaround this issue,
25815  *      this routine has been implemented to use 0x3f mode page(request
25816  *      for all pages) for all device types.
25817  *
25818  *   Arguments: dev		- the device 'dev_t'
25819  *
25820  * Return Code: int indicating if the device is write protected (1) or not (0)
25821  *
25822  *     Context: Kernel thread.
25823  *
25824  */
25825 
25826 static int
25827 sr_check_wp(dev_t dev)
25828 {
25829 	struct sd_lun	*un;
25830 	uchar_t		device_specific;
25831 	uchar_t		*sense;
25832 	int		hdrlen;
25833 	int		rval = FALSE;
25834 
25835 	/*
25836 	 * Note: The return codes for this routine should be reworked to
25837 	 * properly handle the case of a NULL softstate.
25838 	 */
25839 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25840 		return (FALSE);
25841 	}
25842 
25843 	if (un->un_f_cfg_is_atapi == TRUE) {
25844 		/*
25845 		 * The mode page contents are not required; set the allocation
25846 		 * length for the mode page header only
25847 		 */
25848 		hdrlen = MODE_HEADER_LENGTH_GRP2;
25849 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
25850 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense, hdrlen,
25851 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
25852 			goto err_exit;
25853 		device_specific =
25854 		    ((struct mode_header_grp2 *)sense)->device_specific;
25855 	} else {
25856 		hdrlen = MODE_HEADER_LENGTH;
25857 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
25858 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, hdrlen,
25859 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
25860 			goto err_exit;
25861 		device_specific =
25862 		    ((struct mode_header *)sense)->device_specific;
25863 	}
25864 
25865 	/*
25866 	 * Write protect mode sense failed; not all disks
25867 	 * understand this query. Return FALSE assuming that
25868 	 * these devices are not writable.
25869 	 */
25870 	if (device_specific & WRITE_PROTECT) {
25871 		rval = TRUE;
25872 	}
25873 
25874 err_exit:
25875 	kmem_free(sense, hdrlen);
25876 	return (rval);
25877 }
25878 
25879 /*
25880  *    Function: sr_volume_ctrl()
25881  *
25882  * Description: This routine is the driver entry point for handling CD-ROM
25883  *		audio output volume ioctl requests. (CDROMVOLCTRL)
25884  *
25885  *   Arguments: dev	- the device 'dev_t'
25886  *		data	- pointer to user audio volume control structure
25887  *		flag	- this argument is a pass through to ddi_copyxxx()
25888  *			  directly from the mode argument of ioctl().
25889  *
25890  * Return Code: the code returned by sd_send_scsi_cmd()
25891  *		EFAULT if ddi_copyxxx() fails
25892  *		ENXIO if fail ddi_get_soft_state
25893  *		EINVAL if data pointer is NULL
25894  *
25895  */
25896 
25897 static int
25898 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
25899 {
25900 	struct sd_lun		*un;
25901 	struct cdrom_volctrl    volume;
25902 	struct cdrom_volctrl    *vol = &volume;
25903 	uchar_t			*sense_page;
25904 	uchar_t			*select_page;
25905 	uchar_t			*sense;
25906 	uchar_t			*select;
25907 	int			sense_buflen;
25908 	int			select_buflen;
25909 	int			rval;
25910 
25911 	if (data == NULL) {
25912 		return (EINVAL);
25913 	}
25914 
25915 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25916 	    (un->un_state == SD_STATE_OFFLINE)) {
25917 		return (ENXIO);
25918 	}
25919 
25920 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
25921 		return (EFAULT);
25922 	}
25923 
25924 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
25925 		struct mode_header_grp2		*sense_mhp;
25926 		struct mode_header_grp2		*select_mhp;
25927 		int				bd_len;
25928 
25929 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
25930 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
25931 		    MODEPAGE_AUDIO_CTRL_LEN;
25932 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
25933 		select = kmem_zalloc(select_buflen, KM_SLEEP);
25934 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
25935 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
25936 		    SD_PATH_STANDARD)) != 0) {
25937 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25938 			    "sr_volume_ctrl: Mode Sense Failed\n");
25939 			kmem_free(sense, sense_buflen);
25940 			kmem_free(select, select_buflen);
25941 			return (rval);
25942 		}
25943 		sense_mhp = (struct mode_header_grp2 *)sense;
25944 		select_mhp = (struct mode_header_grp2 *)select;
25945 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
25946 		    sense_mhp->bdesc_length_lo;
25947 		if (bd_len > MODE_BLK_DESC_LENGTH) {
25948 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25949 			    "sr_volume_ctrl: Mode Sense returned invalid "
25950 			    "block descriptor length\n");
25951 			kmem_free(sense, sense_buflen);
25952 			kmem_free(select, select_buflen);
25953 			return (EIO);
25954 		}
25955 		sense_page = (uchar_t *)
25956 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
25957 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
25958 		select_mhp->length_msb = 0;
25959 		select_mhp->length_lsb = 0;
25960 		select_mhp->bdesc_length_hi = 0;
25961 		select_mhp->bdesc_length_lo = 0;
25962 	} else {
25963 		struct mode_header		*sense_mhp, *select_mhp;
25964 
25965 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
25966 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
25967 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
25968 		select = kmem_zalloc(select_buflen, KM_SLEEP);
25969 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
25970 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
25971 		    SD_PATH_STANDARD)) != 0) {
25972 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25973 			    "sr_volume_ctrl: Mode Sense Failed\n");
25974 			kmem_free(sense, sense_buflen);
25975 			kmem_free(select, select_buflen);
25976 			return (rval);
25977 		}
25978 		sense_mhp  = (struct mode_header *)sense;
25979 		select_mhp = (struct mode_header *)select;
25980 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
25981 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25982 			    "sr_volume_ctrl: Mode Sense returned invalid "
25983 			    "block descriptor length\n");
25984 			kmem_free(sense, sense_buflen);
25985 			kmem_free(select, select_buflen);
25986 			return (EIO);
25987 		}
25988 		sense_page = (uchar_t *)
25989 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
25990 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
25991 		select_mhp->length = 0;
25992 		select_mhp->bdesc_length = 0;
25993 	}
25994 	/*
25995 	 * Note: An audio control data structure could be created and overlayed
25996 	 * on the following in place of the array indexing method implemented.
25997 	 */
25998 
25999 	/* Build the select data for the user volume data */
26000 	select_page[0] = MODEPAGE_AUDIO_CTRL;
26001 	select_page[1] = 0xE;
26002 	/* Set the immediate bit */
26003 	select_page[2] = 0x04;
26004 	/* Zero out reserved fields */
26005 	select_page[3] = 0x00;
26006 	select_page[4] = 0x00;
26007 	/* Return sense data for fields not to be modified */
26008 	select_page[5] = sense_page[5];
26009 	select_page[6] = sense_page[6];
26010 	select_page[7] = sense_page[7];
26011 	/* Set the user specified volume levels for channel 0 and 1 */
26012 	select_page[8] = 0x01;
26013 	select_page[9] = vol->channel0;
26014 	select_page[10] = 0x02;
26015 	select_page[11] = vol->channel1;
26016 	/* Channel 2 and 3 are currently unsupported so return the sense data */
26017 	select_page[12] = sense_page[12];
26018 	select_page[13] = sense_page[13];
26019 	select_page[14] = sense_page[14];
26020 	select_page[15] = sense_page[15];
26021 
26022 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
26023 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, select,
26024 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
26025 	} else {
26026 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
26027 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
26028 	}
26029 
26030 	kmem_free(sense, sense_buflen);
26031 	kmem_free(select, select_buflen);
26032 	return (rval);
26033 }
26034 
26035 
26036 /*
26037  *    Function: sr_read_sony_session_offset()
26038  *
26039  * Description: This routine is the driver entry point for handling CD-ROM
26040  *		ioctl requests for session offset information. (CDROMREADOFFSET)
26041  *		The address of the first track in the last session of a
26042  *		multi-session CD-ROM is returned
26043  *
26044  *		Note: This routine uses a vendor specific key value in the
26045  *		command control field without implementing any vendor check here
26046  *		or in the ioctl routine.
26047  *
26048  *   Arguments: dev	- the device 'dev_t'
26049  *		data	- pointer to an int to hold the requested address
26050  *		flag	- this argument is a pass through to ddi_copyxxx()
26051  *			  directly from the mode argument of ioctl().
26052  *
26053  * Return Code: the code returned by sd_send_scsi_cmd()
26054  *		EFAULT if ddi_copyxxx() fails
26055  *		ENXIO if fail ddi_get_soft_state
26056  *		EINVAL if data pointer is NULL
26057  */
26058 
26059 static int
26060 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
26061 {
26062 	struct sd_lun		*un;
26063 	struct uscsi_cmd	*com;
26064 	caddr_t			buffer;
26065 	char			cdb[CDB_GROUP1];
26066 	int			session_offset = 0;
26067 	int			rval;
26068 
26069 	if (data == NULL) {
26070 		return (EINVAL);
26071 	}
26072 
26073 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26074 	    (un->un_state == SD_STATE_OFFLINE)) {
26075 		return (ENXIO);
26076 	}
26077 
26078 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
26079 	bzero(cdb, CDB_GROUP1);
26080 	cdb[0] = SCMD_READ_TOC;
26081 	/*
26082 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
26083 	 * (4 byte TOC response header + 8 byte response data)
26084 	 */
26085 	cdb[8] = SONY_SESSION_OFFSET_LEN;
26086 	/* Byte 9 is the control byte. A vendor specific value is used */
26087 	cdb[9] = SONY_SESSION_OFFSET_KEY;
26088 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26089 	com->uscsi_cdb = cdb;
26090 	com->uscsi_cdblen = CDB_GROUP1;
26091 	com->uscsi_bufaddr = buffer;
26092 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
26093 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26094 
26095 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26096 	    SD_PATH_STANDARD);
26097 	if (rval != 0) {
26098 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
26099 		kmem_free(com, sizeof (*com));
26100 		return (rval);
26101 	}
26102 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
26103 		session_offset =
26104 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
26105 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
26106 		/*
26107 		 * Offset returned offset in current lbasize block's. Convert to
26108 		 * 2k block's to return to the user
26109 		 */
26110 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
26111 			session_offset >>= 2;
26112 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
26113 			session_offset >>= 1;
26114 		}
26115 	}
26116 
26117 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
26118 		rval = EFAULT;
26119 	}
26120 
26121 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
26122 	kmem_free(com, sizeof (*com));
26123 	return (rval);
26124 }
26125 
26126 
26127 /*
26128  *    Function: sd_wm_cache_constructor()
26129  *
26130  * Description: Cache Constructor for the wmap cache for the read/modify/write
26131  * 		devices.
26132  *
26133  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
26134  *		un	- sd_lun structure for the device.
26135  *		flag	- the km flags passed to constructor
26136  *
26137  * Return Code: 0 on success.
26138  *		-1 on failure.
26139  */
26140 
26141 /*ARGSUSED*/
26142 static int
26143 sd_wm_cache_constructor(void *wm, void *un, int flags)
26144 {
26145 	bzero(wm, sizeof (struct sd_w_map));
26146 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
26147 	return (0);
26148 }
26149 
26150 
26151 /*
26152  *    Function: sd_wm_cache_destructor()
26153  *
26154  * Description: Cache destructor for the wmap cache for the read/modify/write
26155  * 		devices.
26156  *
26157  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
26158  *		un	- sd_lun structure for the device.
26159  */
26160 /*ARGSUSED*/
26161 static void
26162 sd_wm_cache_destructor(void *wm, void *un)
26163 {
26164 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
26165 }
26166 
26167 
26168 /*
26169  *    Function: sd_range_lock()
26170  *
26171  * Description: Lock the range of blocks specified as parameter to ensure
26172  *		that read, modify write is atomic and no other i/o writes
26173  *		to the same location. The range is specified in terms
26174  *		of start and end blocks. Block numbers are the actual
26175  *		media block numbers and not system.
26176  *
26177  *   Arguments: un	- sd_lun structure for the device.
26178  *		startb - The starting block number
26179  *		endb - The end block number
26180  *		typ - type of i/o - simple/read_modify_write
26181  *
26182  * Return Code: wm  - pointer to the wmap structure.
26183  *
26184  *     Context: This routine can sleep.
26185  */
26186 
26187 static struct sd_w_map *
26188 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
26189 {
26190 	struct sd_w_map *wmp = NULL;
26191 	struct sd_w_map *sl_wmp = NULL;
26192 	struct sd_w_map *tmp_wmp;
26193 	wm_state state = SD_WM_CHK_LIST;
26194 
26195 
26196 	ASSERT(un != NULL);
26197 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26198 
26199 	mutex_enter(SD_MUTEX(un));
26200 
26201 	while (state != SD_WM_DONE) {
26202 
26203 		switch (state) {
26204 		case SD_WM_CHK_LIST:
26205 			/*
26206 			 * This is the starting state. Check the wmap list
26207 			 * to see if the range is currently available.
26208 			 */
26209 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
26210 				/*
26211 				 * If this is a simple write and no rmw
26212 				 * i/o is pending then try to lock the
26213 				 * range as the range should be available.
26214 				 */
26215 				state = SD_WM_LOCK_RANGE;
26216 			} else {
26217 				tmp_wmp = sd_get_range(un, startb, endb);
26218 				if (tmp_wmp != NULL) {
26219 					if ((wmp != NULL) && ONLIST(un, wmp)) {
26220 						/*
26221 						 * Should not keep onlist wmps
26222 						 * while waiting this macro
26223 						 * will also do wmp = NULL;
26224 						 */
26225 						FREE_ONLIST_WMAP(un, wmp);
26226 					}
26227 					/*
26228 					 * sl_wmp is the wmap on which wait
26229 					 * is done, since the tmp_wmp points
26230 					 * to the inuse wmap, set sl_wmp to
26231 					 * tmp_wmp and change the state to sleep
26232 					 */
26233 					sl_wmp = tmp_wmp;
26234 					state = SD_WM_WAIT_MAP;
26235 				} else {
26236 					state = SD_WM_LOCK_RANGE;
26237 				}
26238 
26239 			}
26240 			break;
26241 
26242 		case SD_WM_LOCK_RANGE:
26243 			ASSERT(un->un_wm_cache);
26244 			/*
26245 			 * The range need to be locked, try to get a wmap.
26246 			 * First attempt it with NO_SLEEP, want to avoid a sleep
26247 			 * if possible as we will have to release the sd mutex
26248 			 * if we have to sleep.
26249 			 */
26250 			if (wmp == NULL)
26251 				wmp = kmem_cache_alloc(un->un_wm_cache,
26252 				    KM_NOSLEEP);
26253 			if (wmp == NULL) {
26254 				mutex_exit(SD_MUTEX(un));
26255 				_NOTE(DATA_READABLE_WITHOUT_LOCK
26256 				    (sd_lun::un_wm_cache))
26257 				wmp = kmem_cache_alloc(un->un_wm_cache,
26258 				    KM_SLEEP);
26259 				mutex_enter(SD_MUTEX(un));
26260 				/*
26261 				 * we released the mutex so recheck and go to
26262 				 * check list state.
26263 				 */
26264 				state = SD_WM_CHK_LIST;
26265 			} else {
26266 				/*
26267 				 * We exit out of state machine since we
26268 				 * have the wmap. Do the housekeeping first.
26269 				 * place the wmap on the wmap list if it is not
26270 				 * on it already and then set the state to done.
26271 				 */
26272 				wmp->wm_start = startb;
26273 				wmp->wm_end = endb;
26274 				wmp->wm_flags = typ | SD_WM_BUSY;
26275 				if (typ & SD_WTYPE_RMW) {
26276 					un->un_rmw_count++;
26277 				}
26278 				/*
26279 				 * If not already on the list then link
26280 				 */
26281 				if (!ONLIST(un, wmp)) {
26282 					wmp->wm_next = un->un_wm;
26283 					wmp->wm_prev = NULL;
26284 					if (wmp->wm_next)
26285 						wmp->wm_next->wm_prev = wmp;
26286 					un->un_wm = wmp;
26287 				}
26288 				state = SD_WM_DONE;
26289 			}
26290 			break;
26291 
26292 		case SD_WM_WAIT_MAP:
26293 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
26294 			/*
26295 			 * Wait is done on sl_wmp, which is set in the
26296 			 * check_list state.
26297 			 */
26298 			sl_wmp->wm_wanted_count++;
26299 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
26300 			sl_wmp->wm_wanted_count--;
26301 			/*
26302 			 * We can reuse the memory from the completed sl_wmp
26303 			 * lock range for our new lock, but only if noone is
26304 			 * waiting for it.
26305 			 */
26306 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
26307 			if (sl_wmp->wm_wanted_count == 0) {
26308 				if (wmp != NULL)
26309 					CHK_N_FREEWMP(un, wmp);
26310 				wmp = sl_wmp;
26311 			}
26312 			sl_wmp = NULL;
26313 			/*
26314 			 * After waking up, need to recheck for availability of
26315 			 * range.
26316 			 */
26317 			state = SD_WM_CHK_LIST;
26318 			break;
26319 
26320 		default:
26321 			panic("sd_range_lock: "
26322 			    "Unknown state %d in sd_range_lock", state);
26323 			/*NOTREACHED*/
26324 		} /* switch(state) */
26325 
26326 	} /* while(state != SD_WM_DONE) */
26327 
26328 	mutex_exit(SD_MUTEX(un));
26329 
26330 	ASSERT(wmp != NULL);
26331 
26332 	return (wmp);
26333 }
26334 
26335 
26336 /*
26337  *    Function: sd_get_range()
26338  *
26339  * Description: Find if there any overlapping I/O to this one
26340  *		Returns the write-map of 1st such I/O, NULL otherwise.
26341  *
26342  *   Arguments: un	- sd_lun structure for the device.
26343  *		startb - The starting block number
26344  *		endb - The end block number
26345  *
26346  * Return Code: wm  - pointer to the wmap structure.
26347  */
26348 
26349 static struct sd_w_map *
26350 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
26351 {
26352 	struct sd_w_map *wmp;
26353 
26354 	ASSERT(un != NULL);
26355 
26356 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
26357 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
26358 			continue;
26359 		}
26360 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
26361 			break;
26362 		}
26363 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
26364 			break;
26365 		}
26366 	}
26367 
26368 	return (wmp);
26369 }
26370 
26371 
26372 /*
26373  *    Function: sd_free_inlist_wmap()
26374  *
26375  * Description: Unlink and free a write map struct.
26376  *
26377  *   Arguments: un      - sd_lun structure for the device.
26378  *		wmp	- sd_w_map which needs to be unlinked.
26379  */
26380 
26381 static void
26382 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
26383 {
26384 	ASSERT(un != NULL);
26385 
26386 	if (un->un_wm == wmp) {
26387 		un->un_wm = wmp->wm_next;
26388 	} else {
26389 		wmp->wm_prev->wm_next = wmp->wm_next;
26390 	}
26391 
26392 	if (wmp->wm_next) {
26393 		wmp->wm_next->wm_prev = wmp->wm_prev;
26394 	}
26395 
26396 	wmp->wm_next = wmp->wm_prev = NULL;
26397 
26398 	kmem_cache_free(un->un_wm_cache, wmp);
26399 }
26400 
26401 
26402 /*
26403  *    Function: sd_range_unlock()
26404  *
26405  * Description: Unlock the range locked by wm.
26406  *		Free write map if nobody else is waiting on it.
26407  *
26408  *   Arguments: un      - sd_lun structure for the device.
26409  *              wmp     - sd_w_map which needs to be unlinked.
26410  */
26411 
26412 static void
26413 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
26414 {
26415 	ASSERT(un != NULL);
26416 	ASSERT(wm != NULL);
26417 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26418 
26419 	mutex_enter(SD_MUTEX(un));
26420 
26421 	if (wm->wm_flags & SD_WTYPE_RMW) {
26422 		un->un_rmw_count--;
26423 	}
26424 
26425 	if (wm->wm_wanted_count) {
26426 		wm->wm_flags = 0;
26427 		/*
26428 		 * Broadcast that the wmap is available now.
26429 		 */
26430 		cv_broadcast(&wm->wm_avail);
26431 	} else {
26432 		/*
26433 		 * If no one is waiting on the map, it should be free'ed.
26434 		 */
26435 		sd_free_inlist_wmap(un, wm);
26436 	}
26437 
26438 	mutex_exit(SD_MUTEX(un));
26439 }
26440 
26441 
26442 /*
26443  *    Function: sd_read_modify_write_task
26444  *
26445  * Description: Called from a taskq thread to initiate the write phase of
26446  *		a read-modify-write request.  This is used for targets where
26447  *		un->un_sys_blocksize != un->un_tgt_blocksize.
26448  *
26449  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
26450  *
26451  *     Context: Called under taskq thread context.
26452  */
26453 
26454 static void
26455 sd_read_modify_write_task(void *arg)
26456 {
26457 	struct sd_mapblocksize_info	*bsp;
26458 	struct buf	*bp;
26459 	struct sd_xbuf	*xp;
26460 	struct sd_lun	*un;
26461 
26462 	bp = arg;	/* The bp is given in arg */
26463 	ASSERT(bp != NULL);
26464 
26465 	/* Get the pointer to the layer-private data struct */
26466 	xp = SD_GET_XBUF(bp);
26467 	ASSERT(xp != NULL);
26468 	bsp = xp->xb_private;
26469 	ASSERT(bsp != NULL);
26470 
26471 	un = SD_GET_UN(bp);
26472 	ASSERT(un != NULL);
26473 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26474 
26475 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26476 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
26477 
26478 	/*
26479 	 * This is the write phase of a read-modify-write request, called
26480 	 * under the context of a taskq thread in response to the completion
26481 	 * of the read portion of the rmw request completing under interrupt
26482 	 * context. The write request must be sent from here down the iostart
26483 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
26484 	 * we use the layer index saved in the layer-private data area.
26485 	 */
26486 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
26487 
26488 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26489 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
26490 }
26491 
26492 
26493 /*
26494  *    Function: sddump_do_read_of_rmw()
26495  *
26496  * Description: This routine will be called from sddump, If sddump is called
26497  *		with an I/O which not aligned on device blocksize boundary
26498  *		then the write has to be converted to read-modify-write.
26499  *		Do the read part here in order to keep sddump simple.
26500  *		Note - That the sd_mutex is held across the call to this
26501  *		routine.
26502  *
26503  *   Arguments: un	- sd_lun
26504  *		blkno	- block number in terms of media block size.
26505  *		nblk	- number of blocks.
26506  *		bpp	- pointer to pointer to the buf structure. On return
26507  *			from this function, *bpp points to the valid buffer
26508  *			to which the write has to be done.
26509  *
26510  * Return Code: 0 for success or errno-type return code
26511  */
26512 
26513 static int
26514 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
26515 	struct buf **bpp)
26516 {
26517 	int err;
26518 	int i;
26519 	int rval;
26520 	struct buf *bp;
26521 	struct scsi_pkt *pkt = NULL;
26522 	uint32_t target_blocksize;
26523 
26524 	ASSERT(un != NULL);
26525 	ASSERT(mutex_owned(SD_MUTEX(un)));
26526 
26527 	target_blocksize = un->un_tgt_blocksize;
26528 
26529 	mutex_exit(SD_MUTEX(un));
26530 
26531 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
26532 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
26533 	if (bp == NULL) {
26534 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26535 		    "no resources for dumping; giving up");
26536 		err = ENOMEM;
26537 		goto done;
26538 	}
26539 
26540 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
26541 	    blkno, nblk);
26542 	if (rval != 0) {
26543 		scsi_free_consistent_buf(bp);
26544 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26545 		    "no resources for dumping; giving up");
26546 		err = ENOMEM;
26547 		goto done;
26548 	}
26549 
26550 	pkt->pkt_flags |= FLAG_NOINTR;
26551 
26552 	err = EIO;
26553 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26554 
26555 		/*
26556 		 * Scsi_poll returns 0 (success) if the command completes and
26557 		 * the status block is STATUS_GOOD.  We should only check
26558 		 * errors if this condition is not true.  Even then we should
26559 		 * send our own request sense packet only if we have a check
26560 		 * condition and auto request sense has not been performed by
26561 		 * the hba.
26562 		 */
26563 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
26564 
26565 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
26566 			err = 0;
26567 			break;
26568 		}
26569 
26570 		/*
26571 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
26572 		 * no need to read RQS data.
26573 		 */
26574 		if (pkt->pkt_reason == CMD_DEV_GONE) {
26575 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26576 			    "Device is gone\n");
26577 			break;
26578 		}
26579 
26580 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
26581 			SD_INFO(SD_LOG_DUMP, un,
26582 			    "sddump: read failed with CHECK, try # %d\n", i);
26583 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
26584 				(void) sd_send_polled_RQS(un);
26585 			}
26586 
26587 			continue;
26588 		}
26589 
26590 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
26591 			int reset_retval = 0;
26592 
26593 			SD_INFO(SD_LOG_DUMP, un,
26594 			    "sddump: read failed with BUSY, try # %d\n", i);
26595 
26596 			if (un->un_f_lun_reset_enabled == TRUE) {
26597 				reset_retval = scsi_reset(SD_ADDRESS(un),
26598 				    RESET_LUN);
26599 			}
26600 			if (reset_retval == 0) {
26601 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26602 			}
26603 			(void) sd_send_polled_RQS(un);
26604 
26605 		} else {
26606 			SD_INFO(SD_LOG_DUMP, un,
26607 			    "sddump: read failed with 0x%x, try # %d\n",
26608 			    SD_GET_PKT_STATUS(pkt), i);
26609 			mutex_enter(SD_MUTEX(un));
26610 			sd_reset_target(un, pkt);
26611 			mutex_exit(SD_MUTEX(un));
26612 		}
26613 
26614 		/*
26615 		 * If we are not getting anywhere with lun/target resets,
26616 		 * let's reset the bus.
26617 		 */
26618 		if (i > SD_NDUMP_RETRIES/2) {
26619 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26620 			(void) sd_send_polled_RQS(un);
26621 		}
26622 
26623 	}
26624 	scsi_destroy_pkt(pkt);
26625 
26626 	if (err != 0) {
26627 		scsi_free_consistent_buf(bp);
26628 		*bpp = NULL;
26629 	} else {
26630 		*bpp = bp;
26631 	}
26632 
26633 done:
26634 	mutex_enter(SD_MUTEX(un));
26635 	return (err);
26636 }
26637 
26638 
26639 /*
26640  *    Function: sd_failfast_flushq
26641  *
26642  * Description: Take all bp's on the wait queue that have B_FAILFAST set
26643  *		in b_flags and move them onto the failfast queue, then kick
26644  *		off a thread to return all bp's on the failfast queue to
26645  *		their owners with an error set.
26646  *
26647  *   Arguments: un - pointer to the soft state struct for the instance.
26648  *
26649  *     Context: may execute in interrupt context.
26650  */
26651 
26652 static void
26653 sd_failfast_flushq(struct sd_lun *un)
26654 {
26655 	struct buf *bp;
26656 	struct buf *next_waitq_bp;
26657 	struct buf *prev_waitq_bp = NULL;
26658 
26659 	ASSERT(un != NULL);
26660 	ASSERT(mutex_owned(SD_MUTEX(un)));
26661 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
26662 	ASSERT(un->un_failfast_bp == NULL);
26663 
26664 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
26665 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
26666 
26667 	/*
26668 	 * Check if we should flush all bufs when entering failfast state, or
26669 	 * just those with B_FAILFAST set.
26670 	 */
26671 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
26672 		/*
26673 		 * Move *all* bp's on the wait queue to the failfast flush
26674 		 * queue, including those that do NOT have B_FAILFAST set.
26675 		 */
26676 		if (un->un_failfast_headp == NULL) {
26677 			ASSERT(un->un_failfast_tailp == NULL);
26678 			un->un_failfast_headp = un->un_waitq_headp;
26679 		} else {
26680 			ASSERT(un->un_failfast_tailp != NULL);
26681 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
26682 		}
26683 
26684 		un->un_failfast_tailp = un->un_waitq_tailp;
26685 
26686 		/* update kstat for each bp moved out of the waitq */
26687 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
26688 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
26689 		}
26690 
26691 		/* empty the waitq */
26692 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
26693 
26694 	} else {
26695 		/*
26696 		 * Go thru the wait queue, pick off all entries with
26697 		 * B_FAILFAST set, and move these onto the failfast queue.
26698 		 */
26699 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
26700 			/*
26701 			 * Save the pointer to the next bp on the wait queue,
26702 			 * so we get to it on the next iteration of this loop.
26703 			 */
26704 			next_waitq_bp = bp->av_forw;
26705 
26706 			/*
26707 			 * If this bp from the wait queue does NOT have
26708 			 * B_FAILFAST set, just move on to the next element
26709 			 * in the wait queue. Note, this is the only place
26710 			 * where it is correct to set prev_waitq_bp.
26711 			 */
26712 			if ((bp->b_flags & B_FAILFAST) == 0) {
26713 				prev_waitq_bp = bp;
26714 				continue;
26715 			}
26716 
26717 			/*
26718 			 * Remove the bp from the wait queue.
26719 			 */
26720 			if (bp == un->un_waitq_headp) {
26721 				/* The bp is the first element of the waitq. */
26722 				un->un_waitq_headp = next_waitq_bp;
26723 				if (un->un_waitq_headp == NULL) {
26724 					/* The wait queue is now empty */
26725 					un->un_waitq_tailp = NULL;
26726 				}
26727 			} else {
26728 				/*
26729 				 * The bp is either somewhere in the middle
26730 				 * or at the end of the wait queue.
26731 				 */
26732 				ASSERT(un->un_waitq_headp != NULL);
26733 				ASSERT(prev_waitq_bp != NULL);
26734 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
26735 				    == 0);
26736 				if (bp == un->un_waitq_tailp) {
26737 					/* bp is the last entry on the waitq. */
26738 					ASSERT(next_waitq_bp == NULL);
26739 					un->un_waitq_tailp = prev_waitq_bp;
26740 				}
26741 				prev_waitq_bp->av_forw = next_waitq_bp;
26742 			}
26743 			bp->av_forw = NULL;
26744 
26745 			/*
26746 			 * update kstat since the bp is moved out of
26747 			 * the waitq
26748 			 */
26749 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
26750 
26751 			/*
26752 			 * Now put the bp onto the failfast queue.
26753 			 */
26754 			if (un->un_failfast_headp == NULL) {
26755 				/* failfast queue is currently empty */
26756 				ASSERT(un->un_failfast_tailp == NULL);
26757 				un->un_failfast_headp =
26758 				    un->un_failfast_tailp = bp;
26759 			} else {
26760 				/* Add the bp to the end of the failfast q */
26761 				ASSERT(un->un_failfast_tailp != NULL);
26762 				ASSERT(un->un_failfast_tailp->b_flags &
26763 				    B_FAILFAST);
26764 				un->un_failfast_tailp->av_forw = bp;
26765 				un->un_failfast_tailp = bp;
26766 			}
26767 		}
26768 	}
26769 
26770 	/*
26771 	 * Now return all bp's on the failfast queue to their owners.
26772 	 */
26773 	while ((bp = un->un_failfast_headp) != NULL) {
26774 
26775 		un->un_failfast_headp = bp->av_forw;
26776 		if (un->un_failfast_headp == NULL) {
26777 			un->un_failfast_tailp = NULL;
26778 		}
26779 
26780 		/*
26781 		 * We want to return the bp with a failure error code, but
26782 		 * we do not want a call to sd_start_cmds() to occur here,
26783 		 * so use sd_return_failed_command_no_restart() instead of
26784 		 * sd_return_failed_command().
26785 		 */
26786 		sd_return_failed_command_no_restart(un, bp, EIO);
26787 	}
26788 
26789 	/* Flush the xbuf queues if required. */
26790 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
26791 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
26792 	}
26793 
26794 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
26795 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
26796 }
26797 
26798 
26799 /*
26800  *    Function: sd_failfast_flushq_callback
26801  *
26802  * Description: Return TRUE if the given bp meets the criteria for failfast
26803  *		flushing. Used with ddi_xbuf_flushq(9F).
26804  *
26805  *   Arguments: bp - ptr to buf struct to be examined.
26806  *
26807  *     Context: Any
26808  */
26809 
26810 static int
26811 sd_failfast_flushq_callback(struct buf *bp)
26812 {
26813 	/*
26814 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
26815 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
26816 	 */
26817 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
26818 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
26819 }
26820 
26821 
26822 
26823 #if defined(__i386) || defined(__amd64)
26824 /*
26825  * Function: sd_setup_next_xfer
26826  *
26827  * Description: Prepare next I/O operation using DMA_PARTIAL
26828  *
26829  */
26830 
26831 static int
26832 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
26833     struct scsi_pkt *pkt, struct sd_xbuf *xp)
26834 {
26835 	ssize_t	num_blks_not_xfered;
26836 	daddr_t	strt_blk_num;
26837 	ssize_t	bytes_not_xfered;
26838 	int	rval;
26839 
26840 	ASSERT(pkt->pkt_resid == 0);
26841 
26842 	/*
26843 	 * Calculate next block number and amount to be transferred.
26844 	 *
26845 	 * How much data NOT transfered to the HBA yet.
26846 	 */
26847 	bytes_not_xfered = xp->xb_dma_resid;
26848 
26849 	/*
26850 	 * figure how many blocks NOT transfered to the HBA yet.
26851 	 */
26852 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
26853 
26854 	/*
26855 	 * set starting block number to the end of what WAS transfered.
26856 	 */
26857 	strt_blk_num = xp->xb_blkno +
26858 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
26859 
26860 	/*
26861 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
26862 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
26863 	 * the disk mutex here.
26864 	 */
26865 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
26866 	    strt_blk_num, num_blks_not_xfered);
26867 
26868 	if (rval == 0) {
26869 
26870 		/*
26871 		 * Success.
26872 		 *
26873 		 * Adjust things if there are still more blocks to be
26874 		 * transfered.
26875 		 */
26876 		xp->xb_dma_resid = pkt->pkt_resid;
26877 		pkt->pkt_resid = 0;
26878 
26879 		return (1);
26880 	}
26881 
26882 	/*
26883 	 * There's really only one possible return value from
26884 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
26885 	 * returns NULL.
26886 	 */
26887 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
26888 
26889 	bp->b_resid = bp->b_bcount;
26890 	bp->b_flags |= B_ERROR;
26891 
26892 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26893 	    "Error setting up next portion of DMA transfer\n");
26894 
26895 	return (0);
26896 }
26897 #endif
26898 
26899 /*
26900  *    Function: sd_panic_for_res_conflict
26901  *
26902  * Description: Call panic with a string formatted with "Reservation Conflict"
26903  *		and a human readable identifier indicating the SD instance
26904  *		that experienced the reservation conflict.
26905  *
26906  *   Arguments: un - pointer to the soft state struct for the instance.
26907  *
26908  *     Context: may execute in interrupt context.
26909  */
26910 
26911 #define	SD_RESV_CONFLICT_FMT_LEN 40
26912 void
26913 sd_panic_for_res_conflict(struct sd_lun *un)
26914 {
26915 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
26916 	char path_str[MAXPATHLEN];
26917 
26918 	(void) snprintf(panic_str, sizeof (panic_str),
26919 	    "Reservation Conflict\nDisk: %s",
26920 	    ddi_pathname(SD_DEVINFO(un), path_str));
26921 
26922 	panic(panic_str);
26923 }
26924 
26925 /*
26926  * Note: The following sd_faultinjection_ioctl( ) routines implement
26927  * driver support for handling fault injection for error analysis
26928  * causing faults in multiple layers of the driver.
26929  *
26930  */
26931 
26932 #ifdef SD_FAULT_INJECTION
26933 static uint_t   sd_fault_injection_on = 0;
26934 
26935 /*
26936  *    Function: sd_faultinjection_ioctl()
26937  *
26938  * Description: This routine is the driver entry point for handling
26939  *              faultinjection ioctls to inject errors into the
26940  *              layer model
26941  *
26942  *   Arguments: cmd	- the ioctl cmd received
26943  *		arg	- the arguments from user and returns
26944  */
26945 
26946 static void
26947 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
26948 
26949 	uint_t i;
26950 	uint_t rval;
26951 
26952 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
26953 
26954 	mutex_enter(SD_MUTEX(un));
26955 
26956 	switch (cmd) {
26957 	case SDIOCRUN:
26958 		/* Allow pushed faults to be injected */
26959 		SD_INFO(SD_LOG_SDTEST, un,
26960 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
26961 
26962 		sd_fault_injection_on = 1;
26963 
26964 		SD_INFO(SD_LOG_IOERR, un,
26965 		    "sd_faultinjection_ioctl: run finished\n");
26966 		break;
26967 
26968 	case SDIOCSTART:
26969 		/* Start Injection Session */
26970 		SD_INFO(SD_LOG_SDTEST, un,
26971 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
26972 
26973 		sd_fault_injection_on = 0;
26974 		un->sd_injection_mask = 0xFFFFFFFF;
26975 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
26976 			un->sd_fi_fifo_pkt[i] = NULL;
26977 			un->sd_fi_fifo_xb[i] = NULL;
26978 			un->sd_fi_fifo_un[i] = NULL;
26979 			un->sd_fi_fifo_arq[i] = NULL;
26980 		}
26981 		un->sd_fi_fifo_start = 0;
26982 		un->sd_fi_fifo_end = 0;
26983 
26984 		mutex_enter(&(un->un_fi_mutex));
26985 		un->sd_fi_log[0] = '\0';
26986 		un->sd_fi_buf_len = 0;
26987 		mutex_exit(&(un->un_fi_mutex));
26988 
26989 		SD_INFO(SD_LOG_IOERR, un,
26990 		    "sd_faultinjection_ioctl: start finished\n");
26991 		break;
26992 
26993 	case SDIOCSTOP:
26994 		/* Stop Injection Session */
26995 		SD_INFO(SD_LOG_SDTEST, un,
26996 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
26997 		sd_fault_injection_on = 0;
26998 		un->sd_injection_mask = 0x0;
26999 
27000 		/* Empty stray or unuseds structs from fifo */
27001 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
27002 			if (un->sd_fi_fifo_pkt[i] != NULL) {
27003 				kmem_free(un->sd_fi_fifo_pkt[i],
27004 				    sizeof (struct sd_fi_pkt));
27005 			}
27006 			if (un->sd_fi_fifo_xb[i] != NULL) {
27007 				kmem_free(un->sd_fi_fifo_xb[i],
27008 				    sizeof (struct sd_fi_xb));
27009 			}
27010 			if (un->sd_fi_fifo_un[i] != NULL) {
27011 				kmem_free(un->sd_fi_fifo_un[i],
27012 				    sizeof (struct sd_fi_un));
27013 			}
27014 			if (un->sd_fi_fifo_arq[i] != NULL) {
27015 				kmem_free(un->sd_fi_fifo_arq[i],
27016 				    sizeof (struct sd_fi_arq));
27017 			}
27018 			un->sd_fi_fifo_pkt[i] = NULL;
27019 			un->sd_fi_fifo_un[i] = NULL;
27020 			un->sd_fi_fifo_xb[i] = NULL;
27021 			un->sd_fi_fifo_arq[i] = NULL;
27022 		}
27023 		un->sd_fi_fifo_start = 0;
27024 		un->sd_fi_fifo_end = 0;
27025 
27026 		SD_INFO(SD_LOG_IOERR, un,
27027 		    "sd_faultinjection_ioctl: stop finished\n");
27028 		break;
27029 
27030 	case SDIOCINSERTPKT:
27031 		/* Store a packet struct to be pushed onto fifo */
27032 		SD_INFO(SD_LOG_SDTEST, un,
27033 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
27034 
27035 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27036 
27037 		sd_fault_injection_on = 0;
27038 
27039 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
27040 		if (un->sd_fi_fifo_pkt[i] != NULL) {
27041 			kmem_free(un->sd_fi_fifo_pkt[i],
27042 			    sizeof (struct sd_fi_pkt));
27043 		}
27044 		if (arg != NULL) {
27045 			un->sd_fi_fifo_pkt[i] =
27046 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
27047 			if (un->sd_fi_fifo_pkt[i] == NULL) {
27048 				/* Alloc failed don't store anything */
27049 				break;
27050 			}
27051 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
27052 			    sizeof (struct sd_fi_pkt), 0);
27053 			if (rval == -1) {
27054 				kmem_free(un->sd_fi_fifo_pkt[i],
27055 				    sizeof (struct sd_fi_pkt));
27056 				un->sd_fi_fifo_pkt[i] = NULL;
27057 			}
27058 		} else {
27059 			SD_INFO(SD_LOG_IOERR, un,
27060 			    "sd_faultinjection_ioctl: pkt null\n");
27061 		}
27062 		break;
27063 
27064 	case SDIOCINSERTXB:
27065 		/* Store a xb struct to be pushed onto fifo */
27066 		SD_INFO(SD_LOG_SDTEST, un,
27067 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
27068 
27069 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27070 
27071 		sd_fault_injection_on = 0;
27072 
27073 		if (un->sd_fi_fifo_xb[i] != NULL) {
27074 			kmem_free(un->sd_fi_fifo_xb[i],
27075 			    sizeof (struct sd_fi_xb));
27076 			un->sd_fi_fifo_xb[i] = NULL;
27077 		}
27078 		if (arg != NULL) {
27079 			un->sd_fi_fifo_xb[i] =
27080 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
27081 			if (un->sd_fi_fifo_xb[i] == NULL) {
27082 				/* Alloc failed don't store anything */
27083 				break;
27084 			}
27085 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
27086 			    sizeof (struct sd_fi_xb), 0);
27087 
27088 			if (rval == -1) {
27089 				kmem_free(un->sd_fi_fifo_xb[i],
27090 				    sizeof (struct sd_fi_xb));
27091 				un->sd_fi_fifo_xb[i] = NULL;
27092 			}
27093 		} else {
27094 			SD_INFO(SD_LOG_IOERR, un,
27095 			    "sd_faultinjection_ioctl: xb null\n");
27096 		}
27097 		break;
27098 
27099 	case SDIOCINSERTUN:
27100 		/* Store a un struct to be pushed onto fifo */
27101 		SD_INFO(SD_LOG_SDTEST, un,
27102 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
27103 
27104 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27105 
27106 		sd_fault_injection_on = 0;
27107 
27108 		if (un->sd_fi_fifo_un[i] != NULL) {
27109 			kmem_free(un->sd_fi_fifo_un[i],
27110 			    sizeof (struct sd_fi_un));
27111 			un->sd_fi_fifo_un[i] = NULL;
27112 		}
27113 		if (arg != NULL) {
27114 			un->sd_fi_fifo_un[i] =
27115 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
27116 			if (un->sd_fi_fifo_un[i] == NULL) {
27117 				/* Alloc failed don't store anything */
27118 				break;
27119 			}
27120 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
27121 			    sizeof (struct sd_fi_un), 0);
27122 			if (rval == -1) {
27123 				kmem_free(un->sd_fi_fifo_un[i],
27124 				    sizeof (struct sd_fi_un));
27125 				un->sd_fi_fifo_un[i] = NULL;
27126 			}
27127 
27128 		} else {
27129 			SD_INFO(SD_LOG_IOERR, un,
27130 			    "sd_faultinjection_ioctl: un null\n");
27131 		}
27132 
27133 		break;
27134 
27135 	case SDIOCINSERTARQ:
27136 		/* Store a arq struct to be pushed onto fifo */
27137 		SD_INFO(SD_LOG_SDTEST, un,
27138 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
27139 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27140 
27141 		sd_fault_injection_on = 0;
27142 
27143 		if (un->sd_fi_fifo_arq[i] != NULL) {
27144 			kmem_free(un->sd_fi_fifo_arq[i],
27145 			    sizeof (struct sd_fi_arq));
27146 			un->sd_fi_fifo_arq[i] = NULL;
27147 		}
27148 		if (arg != NULL) {
27149 			un->sd_fi_fifo_arq[i] =
27150 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
27151 			if (un->sd_fi_fifo_arq[i] == NULL) {
27152 				/* Alloc failed don't store anything */
27153 				break;
27154 			}
27155 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
27156 			    sizeof (struct sd_fi_arq), 0);
27157 			if (rval == -1) {
27158 				kmem_free(un->sd_fi_fifo_arq[i],
27159 				    sizeof (struct sd_fi_arq));
27160 				un->sd_fi_fifo_arq[i] = NULL;
27161 			}
27162 
27163 		} else {
27164 			SD_INFO(SD_LOG_IOERR, un,
27165 			    "sd_faultinjection_ioctl: arq null\n");
27166 		}
27167 
27168 		break;
27169 
27170 	case SDIOCPUSH:
27171 		/* Push stored xb, pkt, un, and arq onto fifo */
27172 		sd_fault_injection_on = 0;
27173 
27174 		if (arg != NULL) {
27175 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
27176 			if (rval != -1 &&
27177 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
27178 				un->sd_fi_fifo_end += i;
27179 			}
27180 		} else {
27181 			SD_INFO(SD_LOG_IOERR, un,
27182 			    "sd_faultinjection_ioctl: push arg null\n");
27183 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
27184 				un->sd_fi_fifo_end++;
27185 			}
27186 		}
27187 		SD_INFO(SD_LOG_IOERR, un,
27188 		    "sd_faultinjection_ioctl: push to end=%d\n",
27189 		    un->sd_fi_fifo_end);
27190 		break;
27191 
27192 	case SDIOCRETRIEVE:
27193 		/* Return buffer of log from Injection session */
27194 		SD_INFO(SD_LOG_SDTEST, un,
27195 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
27196 
27197 		sd_fault_injection_on = 0;
27198 
27199 		mutex_enter(&(un->un_fi_mutex));
27200 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
27201 		    un->sd_fi_buf_len+1, 0);
27202 		mutex_exit(&(un->un_fi_mutex));
27203 
27204 		if (rval == -1) {
27205 			/*
27206 			 * arg is possibly invalid setting
27207 			 * it to NULL for return
27208 			 */
27209 			arg = NULL;
27210 		}
27211 		break;
27212 	}
27213 
27214 	mutex_exit(SD_MUTEX(un));
27215 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
27216 			    " exit\n");
27217 }
27218 
27219 
27220 /*
27221  *    Function: sd_injection_log()
27222  *
27223  * Description: This routine adds buff to the already existing injection log
27224  *              for retrieval via faultinjection_ioctl for use in fault
27225  *              detection and recovery
27226  *
27227  *   Arguments: buf - the string to add to the log
27228  */
27229 
27230 static void
27231 sd_injection_log(char *buf, struct sd_lun *un)
27232 {
27233 	uint_t len;
27234 
27235 	ASSERT(un != NULL);
27236 	ASSERT(buf != NULL);
27237 
27238 	mutex_enter(&(un->un_fi_mutex));
27239 
27240 	len = min(strlen(buf), 255);
27241 	/* Add logged value to Injection log to be returned later */
27242 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
27243 		uint_t	offset = strlen((char *)un->sd_fi_log);
27244 		char *destp = (char *)un->sd_fi_log + offset;
27245 		int i;
27246 		for (i = 0; i < len; i++) {
27247 			*destp++ = *buf++;
27248 		}
27249 		un->sd_fi_buf_len += len;
27250 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
27251 	}
27252 
27253 	mutex_exit(&(un->un_fi_mutex));
27254 }
27255 
27256 
27257 /*
27258  *    Function: sd_faultinjection()
27259  *
27260  * Description: This routine takes the pkt and changes its
27261  *		content based on error injection scenerio.
27262  *
27263  *   Arguments: pktp	- packet to be changed
27264  */
27265 
27266 static void
27267 sd_faultinjection(struct scsi_pkt *pktp)
27268 {
27269 	uint_t i;
27270 	struct sd_fi_pkt *fi_pkt;
27271 	struct sd_fi_xb *fi_xb;
27272 	struct sd_fi_un *fi_un;
27273 	struct sd_fi_arq *fi_arq;
27274 	struct buf *bp;
27275 	struct sd_xbuf *xb;
27276 	struct sd_lun *un;
27277 
27278 	ASSERT(pktp != NULL);
27279 
27280 	/* pull bp xb and un from pktp */
27281 	bp = (struct buf *)pktp->pkt_private;
27282 	xb = SD_GET_XBUF(bp);
27283 	un = SD_GET_UN(bp);
27284 
27285 	ASSERT(un != NULL);
27286 
27287 	mutex_enter(SD_MUTEX(un));
27288 
27289 	SD_TRACE(SD_LOG_SDTEST, un,
27290 	    "sd_faultinjection: entry Injection from sdintr\n");
27291 
27292 	/* if injection is off return */
27293 	if (sd_fault_injection_on == 0 ||
27294 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
27295 		mutex_exit(SD_MUTEX(un));
27296 		return;
27297 	}
27298 
27299 
27300 	/* take next set off fifo */
27301 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
27302 
27303 	fi_pkt = un->sd_fi_fifo_pkt[i];
27304 	fi_xb = un->sd_fi_fifo_xb[i];
27305 	fi_un = un->sd_fi_fifo_un[i];
27306 	fi_arq = un->sd_fi_fifo_arq[i];
27307 
27308 
27309 	/* set variables accordingly */
27310 	/* set pkt if it was on fifo */
27311 	if (fi_pkt != NULL) {
27312 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
27313 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
27314 		SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
27315 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
27316 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
27317 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
27318 
27319 	}
27320 
27321 	/* set xb if it was on fifo */
27322 	if (fi_xb != NULL) {
27323 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
27324 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
27325 		SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
27326 		SD_CONDSET(xb, xb, xb_victim_retry_count,
27327 		    "xb_victim_retry_count");
27328 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
27329 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
27330 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
27331 
27332 		/* copy in block data from sense */
27333 		if (fi_xb->xb_sense_data[0] != -1) {
27334 			bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
27335 			    SENSE_LENGTH);
27336 		}
27337 
27338 		/* copy in extended sense codes */
27339 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_code,
27340 		    "es_code");
27341 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_key,
27342 		    "es_key");
27343 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_add_code,
27344 		    "es_add_code");
27345 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb,
27346 		    es_qual_code, "es_qual_code");
27347 	}
27348 
27349 	/* set un if it was on fifo */
27350 	if (fi_un != NULL) {
27351 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
27352 		SD_CONDSET(un, un, un_ctype, "un_ctype");
27353 		SD_CONDSET(un, un, un_reset_retry_count,
27354 		    "un_reset_retry_count");
27355 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
27356 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
27357 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
27358 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
27359 		    "un_f_allow_bus_device_reset");
27360 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
27361 
27362 	}
27363 
27364 	/* copy in auto request sense if it was on fifo */
27365 	if (fi_arq != NULL) {
27366 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
27367 	}
27368 
27369 	/* free structs */
27370 	if (un->sd_fi_fifo_pkt[i] != NULL) {
27371 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
27372 	}
27373 	if (un->sd_fi_fifo_xb[i] != NULL) {
27374 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
27375 	}
27376 	if (un->sd_fi_fifo_un[i] != NULL) {
27377 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
27378 	}
27379 	if (un->sd_fi_fifo_arq[i] != NULL) {
27380 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
27381 	}
27382 
27383 	/*
27384 	 * kmem_free does not gurantee to set to NULL
27385 	 * since we uses these to determine if we set
27386 	 * values or not lets confirm they are always
27387 	 * NULL after free
27388 	 */
27389 	un->sd_fi_fifo_pkt[i] = NULL;
27390 	un->sd_fi_fifo_un[i] = NULL;
27391 	un->sd_fi_fifo_xb[i] = NULL;
27392 	un->sd_fi_fifo_arq[i] = NULL;
27393 
27394 	un->sd_fi_fifo_start++;
27395 
27396 	mutex_exit(SD_MUTEX(un));
27397 
27398 	SD_TRACE(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
27399 }
27400 
27401 #endif /* SD_FAULT_INJECTION */
27402 
27403 /*
27404  * This routine is invoked in sd_unit_attach(). Before calling it, the
27405  * properties in conf file should be processed already, and "hotpluggable"
27406  * property was processed also.
27407  *
27408  * The sd driver distinguishes 3 different type of devices: removable media,
27409  * non-removable media, and hotpluggable. Below the differences are defined:
27410  *
27411  * 1. Device ID
27412  *
27413  *     The device ID of a device is used to identify this device. Refer to
27414  *     ddi_devid_register(9F).
27415  *
27416  *     For a non-removable media disk device which can provide 0x80 or 0x83
27417  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
27418  *     device ID is created to identify this device. For other non-removable
27419  *     media devices, a default device ID is created only if this device has
27420  *     at least 2 alter cylinders. Otherwise, this device has no devid.
27421  *
27422  *     -------------------------------------------------------
27423  *     removable media   hotpluggable  | Can Have Device ID
27424  *     -------------------------------------------------------
27425  *         false             false     |     Yes
27426  *         false             true      |     Yes
27427  *         true                x       |     No
27428  *     ------------------------------------------------------
27429  *
27430  *
27431  * 2. SCSI group 4 commands
27432  *
27433  *     In SCSI specs, only some commands in group 4 command set can use
27434  *     8-byte addresses that can be used to access >2TB storage spaces.
27435  *     Other commands have no such capability. Without supporting group4,
27436  *     it is impossible to make full use of storage spaces of a disk with
27437  *     capacity larger than 2TB.
27438  *
27439  *     -----------------------------------------------
27440  *     removable media   hotpluggable   LP64  |  Group
27441  *     -----------------------------------------------
27442  *           false          false       false |   1
27443  *           false          false       true  |   4
27444  *           false          true        false |   1
27445  *           false          true        true  |   4
27446  *           true             x           x   |   5
27447  *     -----------------------------------------------
27448  *
27449  *
27450  * 3. Check for VTOC Label
27451  *
27452  *     If a direct-access disk has no EFI label, sd will check if it has a
27453  *     valid VTOC label. Now, sd also does that check for removable media
27454  *     and hotpluggable devices.
27455  *
27456  *     --------------------------------------------------------------
27457  *     Direct-Access   removable media    hotpluggable |  Check Label
27458  *     -------------------------------------------------------------
27459  *         false          false           false        |   No
27460  *         false          false           true         |   No
27461  *         false          true            false        |   Yes
27462  *         false          true            true         |   Yes
27463  *         true            x                x          |   Yes
27464  *     --------------------------------------------------------------
27465  *
27466  *
27467  * 4. Building default VTOC label
27468  *
27469  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
27470  *     If those devices have no valid VTOC label, sd(7d) will attempt to
27471  *     create default VTOC for them. Currently sd creates default VTOC label
27472  *     for all devices on x86 platform (VTOC_16), but only for removable
27473  *     media devices on SPARC (VTOC_8).
27474  *
27475  *     -----------------------------------------------------------
27476  *       removable media hotpluggable platform   |   Default Label
27477  *     -----------------------------------------------------------
27478  *             false          false    sparc     |     No
27479  *             false          true      x86      |     Yes
27480  *             false          true     sparc     |     Yes
27481  *             true             x        x       |     Yes
27482  *     ----------------------------------------------------------
27483  *
27484  *
27485  * 5. Supported blocksizes of target devices
27486  *
27487  *     Sd supports non-512-byte blocksize for removable media devices only.
27488  *     For other devices, only 512-byte blocksize is supported. This may be
27489  *     changed in near future because some RAID devices require non-512-byte
27490  *     blocksize
27491  *
27492  *     -----------------------------------------------------------
27493  *     removable media    hotpluggable    | non-512-byte blocksize
27494  *     -----------------------------------------------------------
27495  *           false          false         |   No
27496  *           false          true          |   No
27497  *           true             x           |   Yes
27498  *     -----------------------------------------------------------
27499  *
27500  *
27501  * 6. Automatic mount & unmount
27502  *
27503  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
27504  *     if a device is removable media device. It return 1 for removable media
27505  *     devices, and 0 for others.
27506  *
27507  *     The automatic mounting subsystem should distinguish between the types
27508  *     of devices and apply automounting policies to each.
27509  *
27510  *
27511  * 7. fdisk partition management
27512  *
27513  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
27514  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
27515  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
27516  *     fdisk partitions on both x86 and SPARC platform.
27517  *
27518  *     -----------------------------------------------------------
27519  *       platform   removable media  USB/1394  |  fdisk supported
27520  *     -----------------------------------------------------------
27521  *        x86         X               X        |       true
27522  *     ------------------------------------------------------------
27523  *        sparc       X               X        |       false
27524  *     ------------------------------------------------------------
27525  *
27526  *
27527  * 8. MBOOT/MBR
27528  *
27529  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
27530  *     read/write mboot for removable media devices on sparc platform.
27531  *
27532  *     -----------------------------------------------------------
27533  *       platform   removable media  USB/1394  |  mboot supported
27534  *     -----------------------------------------------------------
27535  *        x86         X               X        |       true
27536  *     ------------------------------------------------------------
27537  *        sparc      false           false     |       false
27538  *        sparc      false           true      |       true
27539  *        sparc      true            false     |       true
27540  *        sparc      true            true      |       true
27541  *     ------------------------------------------------------------
27542  *
27543  *
27544  * 9.  error handling during opening device
27545  *
27546  *     If failed to open a disk device, an errno is returned. For some kinds
27547  *     of errors, different errno is returned depending on if this device is
27548  *     a removable media device. This brings USB/1394 hard disks in line with
27549  *     expected hard disk behavior. It is not expected that this breaks any
27550  *     application.
27551  *
27552  *     ------------------------------------------------------
27553  *       removable media    hotpluggable   |  errno
27554  *     ------------------------------------------------------
27555  *             false          false        |   EIO
27556  *             false          true         |   EIO
27557  *             true             x          |   ENXIO
27558  *     ------------------------------------------------------
27559  *
27560  *
27561  * 11. ioctls: DKIOCEJECT, CDROMEJECT
27562  *
27563  *     These IOCTLs are applicable only to removable media devices.
27564  *
27565  *     -----------------------------------------------------------
27566  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
27567  *     -----------------------------------------------------------
27568  *             false          false        |     No
27569  *             false          true         |     No
27570  *             true            x           |     Yes
27571  *     -----------------------------------------------------------
27572  *
27573  *
27574  * 12. Kstats for partitions
27575  *
27576  *     sd creates partition kstat for non-removable media devices. USB and
27577  *     Firewire hard disks now have partition kstats
27578  *
27579  *      ------------------------------------------------------
27580  *       removable media    hotpluggable   |   kstat
27581  *      ------------------------------------------------------
27582  *             false          false        |    Yes
27583  *             false          true         |    Yes
27584  *             true             x          |    No
27585  *       ------------------------------------------------------
27586  *
27587  *
27588  * 13. Removable media & hotpluggable properties
27589  *
27590  *     Sd driver creates a "removable-media" property for removable media
27591  *     devices. Parent nexus drivers create a "hotpluggable" property if
27592  *     it supports hotplugging.
27593  *
27594  *     ---------------------------------------------------------------------
27595  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
27596  *     ---------------------------------------------------------------------
27597  *       false            false       |    No                   No
27598  *       false            true        |    No                   Yes
27599  *       true             false       |    Yes                  No
27600  *       true             true        |    Yes                  Yes
27601  *     ---------------------------------------------------------------------
27602  *
27603  *
27604  * 14. Power Management
27605  *
27606  *     sd only power manages removable media devices or devices that support
27607  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
27608  *
27609  *     A parent nexus that supports hotplugging can also set "pm-capable"
27610  *     if the disk can be power managed.
27611  *
27612  *     ------------------------------------------------------------
27613  *       removable media hotpluggable pm-capable  |   power manage
27614  *     ------------------------------------------------------------
27615  *             false          false     false     |     No
27616  *             false          false     true      |     Yes
27617  *             false          true      false     |     No
27618  *             false          true      true      |     Yes
27619  *             true             x        x        |     Yes
27620  *     ------------------------------------------------------------
27621  *
27622  *      USB and firewire hard disks can now be power managed independently
27623  *      of the framebuffer
27624  *
27625  *
27626  * 15. Support for USB disks with capacity larger than 1TB
27627  *
27628  *     Currently, sd doesn't permit a fixed disk device with capacity
27629  *     larger than 1TB to be used in a 32-bit operating system environment.
27630  *     However, sd doesn't do that for removable media devices. Instead, it
27631  *     assumes that removable media devices cannot have a capacity larger
27632  *     than 1TB. Therefore, using those devices on 32-bit system is partially
27633  *     supported, which can cause some unexpected results.
27634  *
27635  *     ---------------------------------------------------------------------
27636  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
27637  *     ---------------------------------------------------------------------
27638  *             false          false  |   true         |     no
27639  *             false          true   |   true         |     no
27640  *             true           false  |   true         |     Yes
27641  *             true           true   |   true         |     Yes
27642  *     ---------------------------------------------------------------------
27643  *
27644  *
27645  * 16. Check write-protection at open time
27646  *
27647  *     When a removable media device is being opened for writing without NDELAY
27648  *     flag, sd will check if this device is writable. If attempting to open
27649  *     without NDELAY flag a write-protected device, this operation will abort.
27650  *
27651  *     ------------------------------------------------------------
27652  *       removable media    USB/1394   |   WP Check
27653  *     ------------------------------------------------------------
27654  *             false          false    |     No
27655  *             false          true     |     No
27656  *             true           false    |     Yes
27657  *             true           true     |     Yes
27658  *     ------------------------------------------------------------
27659  *
27660  *
27661  * 17. syslog when corrupted VTOC is encountered
27662  *
27663  *      Currently, if an invalid VTOC is encountered, sd only print syslog
27664  *      for fixed SCSI disks.
27665  *     ------------------------------------------------------------
27666  *       removable media    USB/1394   |   print syslog
27667  *     ------------------------------------------------------------
27668  *             false          false    |     Yes
27669  *             false          true     |     No
27670  *             true           false    |     No
27671  *             true           true     |     No
27672  *     ------------------------------------------------------------
27673  */
27674 static void
27675 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
27676 {
27677 	int	pm_capable_prop;
27678 
27679 	ASSERT(un->un_sd);
27680 	ASSERT(un->un_sd->sd_inq);
27681 
27682 	/*
27683 	 * Enable SYNC CACHE support for all devices.
27684 	 */
27685 	un->un_f_sync_cache_supported = TRUE;
27686 
27687 	if (un->un_sd->sd_inq->inq_rmb) {
27688 		/*
27689 		 * The media of this device is removable. And for this kind
27690 		 * of devices, it is possible to change medium after opening
27691 		 * devices. Thus we should support this operation.
27692 		 */
27693 		un->un_f_has_removable_media = TRUE;
27694 
27695 		/*
27696 		 * support non-512-byte blocksize of removable media devices
27697 		 */
27698 		un->un_f_non_devbsize_supported = TRUE;
27699 
27700 		/*
27701 		 * Assume that all removable media devices support DOOR_LOCK
27702 		 */
27703 		un->un_f_doorlock_supported = TRUE;
27704 
27705 		/*
27706 		 * For a removable media device, it is possible to be opened
27707 		 * with NDELAY flag when there is no media in drive, in this
27708 		 * case we don't care if device is writable. But if without
27709 		 * NDELAY flag, we need to check if media is write-protected.
27710 		 */
27711 		un->un_f_chk_wp_open = TRUE;
27712 
27713 		/*
27714 		 * need to start a SCSI watch thread to monitor media state,
27715 		 * when media is being inserted or ejected, notify syseventd.
27716 		 */
27717 		un->un_f_monitor_media_state = TRUE;
27718 
27719 		/*
27720 		 * Some devices don't support START_STOP_UNIT command.
27721 		 * Therefore, we'd better check if a device supports it
27722 		 * before sending it.
27723 		 */
27724 		un->un_f_check_start_stop = TRUE;
27725 
27726 		/*
27727 		 * support eject media ioctl:
27728 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
27729 		 */
27730 		un->un_f_eject_media_supported = TRUE;
27731 
27732 		/*
27733 		 * Because many removable-media devices don't support
27734 		 * LOG_SENSE, we couldn't use this command to check if
27735 		 * a removable media device support power-management.
27736 		 * We assume that they support power-management via
27737 		 * START_STOP_UNIT command and can be spun up and down
27738 		 * without limitations.
27739 		 */
27740 		un->un_f_pm_supported = TRUE;
27741 
27742 		/*
27743 		 * Need to create a zero length (Boolean) property
27744 		 * removable-media for the removable media devices.
27745 		 * Note that the return value of the property is not being
27746 		 * checked, since if unable to create the property
27747 		 * then do not want the attach to fail altogether. Consistent
27748 		 * with other property creation in attach.
27749 		 */
27750 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
27751 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
27752 
27753 	} else {
27754 		/*
27755 		 * create device ID for device
27756 		 */
27757 		un->un_f_devid_supported = TRUE;
27758 
27759 		/*
27760 		 * Spin up non-removable-media devices once it is attached
27761 		 */
27762 		un->un_f_attach_spinup = TRUE;
27763 
27764 		/*
27765 		 * According to SCSI specification, Sense data has two kinds of
27766 		 * format: fixed format, and descriptor format. At present, we
27767 		 * don't support descriptor format sense data for removable
27768 		 * media.
27769 		 */
27770 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
27771 			un->un_f_descr_format_supported = TRUE;
27772 		}
27773 
27774 		/*
27775 		 * kstats are created only for non-removable media devices.
27776 		 *
27777 		 * Set this in sd.conf to 0 in order to disable kstats.  The
27778 		 * default is 1, so they are enabled by default.
27779 		 */
27780 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
27781 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
27782 		    "enable-partition-kstats", 1));
27783 
27784 		/*
27785 		 * Check if HBA has set the "pm-capable" property.
27786 		 * If "pm-capable" exists and is non-zero then we can
27787 		 * power manage the device without checking the start/stop
27788 		 * cycle count log sense page.
27789 		 *
27790 		 * If "pm-capable" exists and is SD_PM_CAPABLE_FALSE (0)
27791 		 * then we should not power manage the device.
27792 		 *
27793 		 * If "pm-capable" doesn't exist then pm_capable_prop will
27794 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
27795 		 * sd will check the start/stop cycle count log sense page
27796 		 * and power manage the device if the cycle count limit has
27797 		 * not been exceeded.
27798 		 */
27799 		pm_capable_prop = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
27800 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
27801 		if (pm_capable_prop == SD_PM_CAPABLE_UNDEFINED) {
27802 			un->un_f_log_sense_supported = TRUE;
27803 		} else {
27804 			/*
27805 			 * pm-capable property exists.
27806 			 *
27807 			 * Convert "TRUE" values for pm_capable_prop to
27808 			 * SD_PM_CAPABLE_TRUE (1) to make it easier to check
27809 			 * later. "TRUE" values are any values except
27810 			 * SD_PM_CAPABLE_FALSE (0) and
27811 			 * SD_PM_CAPABLE_UNDEFINED (-1)
27812 			 */
27813 			if (pm_capable_prop == SD_PM_CAPABLE_FALSE) {
27814 				un->un_f_log_sense_supported = FALSE;
27815 			} else {
27816 				un->un_f_pm_supported = TRUE;
27817 			}
27818 
27819 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
27820 			    "sd_unit_attach: un:0x%p pm-capable "
27821 			    "property set to %d.\n", un, un->un_f_pm_supported);
27822 		}
27823 	}
27824 
27825 	if (un->un_f_is_hotpluggable) {
27826 
27827 		/*
27828 		 * Have to watch hotpluggable devices as well, since
27829 		 * that's the only way for userland applications to
27830 		 * detect hot removal while device is busy/mounted.
27831 		 */
27832 		un->un_f_monitor_media_state = TRUE;
27833 
27834 		un->un_f_check_start_stop = TRUE;
27835 
27836 	}
27837 }
27838 
27839 /*
27840  * sd_tg_rdwr:
27841  * Provides rdwr access for cmlb via sd_tgops. The start_block is
27842  * in sys block size, req_length in bytes.
27843  *
27844  */
27845 static int
27846 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
27847     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
27848 {
27849 	struct sd_lun *un;
27850 	int path_flag = (int)(uintptr_t)tg_cookie;
27851 	char *dkl = NULL;
27852 	diskaddr_t real_addr = start_block;
27853 	diskaddr_t first_byte, end_block;
27854 
27855 	size_t	buffer_size = reqlength;
27856 	int rval;
27857 	diskaddr_t	cap;
27858 	uint32_t	lbasize;
27859 
27860 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
27861 	if (un == NULL)
27862 		return (ENXIO);
27863 
27864 	if (cmd != TG_READ && cmd != TG_WRITE)
27865 		return (EINVAL);
27866 
27867 	mutex_enter(SD_MUTEX(un));
27868 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
27869 		mutex_exit(SD_MUTEX(un));
27870 		rval = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
27871 		    &lbasize, path_flag);
27872 		if (rval != 0)
27873 			return (rval);
27874 		mutex_enter(SD_MUTEX(un));
27875 		sd_update_block_info(un, lbasize, cap);
27876 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
27877 			mutex_exit(SD_MUTEX(un));
27878 			return (EIO);
27879 		}
27880 	}
27881 
27882 	if (NOT_DEVBSIZE(un)) {
27883 		/*
27884 		 * sys_blocksize != tgt_blocksize, need to re-adjust
27885 		 * blkno and save the index to beginning of dk_label
27886 		 */
27887 		first_byte  = SD_SYSBLOCKS2BYTES(un, start_block);
27888 		real_addr = first_byte / un->un_tgt_blocksize;
27889 
27890 		end_block = (first_byte + reqlength +
27891 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
27892 
27893 		/* round up buffer size to multiple of target block size */
27894 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
27895 
27896 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
27897 		    "label_addr: 0x%x allocation size: 0x%x\n",
27898 		    real_addr, buffer_size);
27899 
27900 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
27901 		    (reqlength % un->un_tgt_blocksize) != 0)
27902 			/* the request is not aligned */
27903 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
27904 	}
27905 
27906 	/*
27907 	 * The MMC standard allows READ CAPACITY to be
27908 	 * inaccurate by a bounded amount (in the interest of
27909 	 * response latency).  As a result, failed READs are
27910 	 * commonplace (due to the reading of metadata and not
27911 	 * data). Depending on the per-Vendor/drive Sense data,
27912 	 * the failed READ can cause many (unnecessary) retries.
27913 	 */
27914 
27915 	if (ISCD(un) && (cmd == TG_READ) &&
27916 	    (un->un_f_blockcount_is_valid == TRUE) &&
27917 	    ((start_block == (un->un_blockcount - 1))||
27918 	    (start_block == (un->un_blockcount - 2)))) {
27919 			path_flag = SD_PATH_DIRECT_PRIORITY;
27920 	}
27921 
27922 	mutex_exit(SD_MUTEX(un));
27923 	if (cmd == TG_READ) {
27924 		rval = sd_send_scsi_READ(un, (dkl != NULL)? dkl: bufaddr,
27925 		    buffer_size, real_addr, path_flag);
27926 		if (dkl != NULL)
27927 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
27928 			    real_addr), bufaddr, reqlength);
27929 	} else {
27930 		if (dkl) {
27931 			rval = sd_send_scsi_READ(un, dkl, buffer_size,
27932 			    real_addr, path_flag);
27933 			if (rval) {
27934 				kmem_free(dkl, buffer_size);
27935 				return (rval);
27936 			}
27937 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
27938 			    real_addr), reqlength);
27939 		}
27940 		rval = sd_send_scsi_WRITE(un, (dkl != NULL)? dkl: bufaddr,
27941 		    buffer_size, real_addr, path_flag);
27942 	}
27943 
27944 	if (dkl != NULL)
27945 		kmem_free(dkl, buffer_size);
27946 
27947 	return (rval);
27948 }
27949 
27950 
27951 static int
27952 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
27953 {
27954 
27955 	struct sd_lun *un;
27956 	diskaddr_t	cap;
27957 	uint32_t	lbasize;
27958 	int		path_flag = (int)(uintptr_t)tg_cookie;
27959 	int		ret = 0;
27960 
27961 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
27962 	if (un == NULL)
27963 		return (ENXIO);
27964 
27965 	switch (cmd) {
27966 	case TG_GETPHYGEOM:
27967 	case TG_GETVIRTGEOM:
27968 	case TG_GETCAPACITY:
27969 	case  TG_GETBLOCKSIZE:
27970 		mutex_enter(SD_MUTEX(un));
27971 
27972 		if ((un->un_f_blockcount_is_valid == TRUE) &&
27973 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
27974 			cap = un->un_blockcount;
27975 			lbasize = un->un_tgt_blocksize;
27976 			mutex_exit(SD_MUTEX(un));
27977 		} else {
27978 			mutex_exit(SD_MUTEX(un));
27979 			ret = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
27980 			    &lbasize, path_flag);
27981 			if (ret != 0)
27982 				return (ret);
27983 			mutex_enter(SD_MUTEX(un));
27984 			sd_update_block_info(un, lbasize, cap);
27985 			if ((un->un_f_blockcount_is_valid == FALSE) ||
27986 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
27987 				mutex_exit(SD_MUTEX(un));
27988 				return (EIO);
27989 			}
27990 			mutex_exit(SD_MUTEX(un));
27991 		}
27992 
27993 		if (cmd == TG_GETCAPACITY) {
27994 			*(diskaddr_t *)arg = cap;
27995 			return (0);
27996 		}
27997 
27998 		if (cmd == TG_GETBLOCKSIZE) {
27999 			*(uint32_t *)arg = lbasize;
28000 			return (0);
28001 		}
28002 
28003 		if (cmd == TG_GETPHYGEOM)
28004 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
28005 			    cap, lbasize, path_flag);
28006 		else
28007 			/* TG_GETVIRTGEOM */
28008 			ret = sd_get_virtual_geometry(un,
28009 			    (cmlb_geom_t *)arg, cap, lbasize);
28010 
28011 		return (ret);
28012 
28013 	case TG_GETATTR:
28014 		mutex_enter(SD_MUTEX(un));
28015 		((tg_attribute_t *)arg)->media_is_writable =
28016 		    un->un_f_mmc_writable_media;
28017 		mutex_exit(SD_MUTEX(un));
28018 		return (0);
28019 	default:
28020 		return (ENOTTY);
28021 
28022 	}
28023 
28024 }
28025