xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 30ab6db6)
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 static int sd_setup_next_rw_pkt(struct sd_lun *un, struct scsi_pkt *pktp,
1240 	struct buf *bp, diskaddr_t lba, uint32_t blockcount);
1241 
1242 /*
1243  * Prototypes for functions to support USCSI IO.
1244  */
1245 static int sd_uscsi_strategy(struct buf *bp);
1246 static int sd_initpkt_for_uscsi(struct buf *, struct scsi_pkt **);
1247 static void sd_destroypkt_for_uscsi(struct buf *);
1248 
1249 static void sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
1250 	uchar_t chain_type, void *pktinfop);
1251 
1252 static int  sd_pm_entry(struct sd_lun *un);
1253 static void sd_pm_exit(struct sd_lun *un);
1254 
1255 static void sd_pm_idletimeout_handler(void *arg);
1256 
1257 /*
1258  * sd_core internal functions (used at the sd_core_io layer).
1259  */
1260 static void sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp);
1261 static void sdintr(struct scsi_pkt *pktp);
1262 static void sd_start_cmds(struct sd_lun *un, struct buf *immed_bp);
1263 
1264 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1265 	enum uio_seg dataspace, int path_flag);
1266 
1267 static struct buf *sd_bioclone_alloc(struct buf *bp, size_t datalen,
1268 	daddr_t blkno, int (*func)(struct buf *));
1269 static struct buf *sd_shadow_buf_alloc(struct buf *bp, size_t datalen,
1270 	uint_t bflags, daddr_t blkno, int (*func)(struct buf *));
1271 static void sd_bioclone_free(struct buf *bp);
1272 static void sd_shadow_buf_free(struct buf *bp);
1273 
1274 static void sd_print_transport_rejected_message(struct sd_lun *un,
1275 	struct sd_xbuf *xp, int code);
1276 static void sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp,
1277     void *arg, int code);
1278 static void sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp,
1279     void *arg, int code);
1280 static void sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp,
1281     void *arg, int code);
1282 
1283 static void sd_retry_command(struct sd_lun *un, struct buf *bp,
1284 	int retry_check_flag,
1285 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp,
1286 		int c),
1287 	void *user_arg, int failure_code,  clock_t retry_delay,
1288 	void (*statp)(kstat_io_t *));
1289 
1290 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1291 	clock_t retry_delay, void (*statp)(kstat_io_t *));
1292 
1293 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1294 	struct scsi_pkt *pktp);
1295 static void sd_start_retry_command(void *arg);
1296 static void sd_start_direct_priority_command(void *arg);
1297 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1298 	int errcode);
1299 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1300 	struct buf *bp, int errcode);
1301 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1302 static void sd_sync_with_callback(struct sd_lun *un);
1303 static int sdrunout(caddr_t arg);
1304 
1305 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1306 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1307 
1308 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1309 static void sd_restore_throttle(void *arg);
1310 
1311 static void sd_init_cdb_limits(struct sd_lun *un);
1312 
1313 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1314 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1315 
1316 /*
1317  * Error handling functions
1318  */
1319 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1320 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1321 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1322 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1323 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1324 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1325 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1326 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1327 
1328 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1329 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1330 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1331 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1332 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1333 	struct sd_xbuf *xp, size_t actual_len);
1334 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1335 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1336 
1337 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1338 	void *arg, int code);
1339 
1340 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1341 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1342 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1343 	uint8_t *sense_datap,
1344 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1345 static void sd_sense_key_not_ready(struct sd_lun *un,
1346 	uint8_t *sense_datap,
1347 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1348 static void sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
1349 	uint8_t *sense_datap,
1350 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1351 static void sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
1352 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1353 static void sd_sense_key_unit_attention(struct sd_lun *un,
1354 	uint8_t *sense_datap,
1355 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1356 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1357 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1358 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1359 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1360 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1361 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1362 static void sd_sense_key_default(struct sd_lun *un,
1363 	uint8_t *sense_datap,
1364 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1365 
1366 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1367 	void *arg, int flag);
1368 
1369 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1370 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1371 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1372 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1373 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1374 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1375 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1376 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1377 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1378 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1379 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1380 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1381 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1382 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1383 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1384 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1385 
1386 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1387 
1388 static void sd_start_stop_unit_callback(void *arg);
1389 static void sd_start_stop_unit_task(void *arg);
1390 
1391 static void sd_taskq_create(void);
1392 static void sd_taskq_delete(void);
1393 static void sd_media_change_task(void *arg);
1394 
1395 static int sd_handle_mchange(struct sd_lun *un);
1396 static int sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag);
1397 static int sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp,
1398 	uint32_t *lbap, int path_flag);
1399 static int sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
1400 	uint32_t *lbap, int path_flag);
1401 static int sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag,
1402 	int path_flag);
1403 static int sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr,
1404 	size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1405 static int sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag);
1406 static int sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un,
1407 	uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1408 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un,
1409 	uchar_t usr_cmd, uchar_t *usr_bufp);
1410 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1411 	struct dk_callback *dkc);
1412 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1413 static int sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un,
1414 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1415 	uchar_t *bufaddr, uint_t buflen, int path_flag);
1416 static int sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
1417 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1418 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag);
1419 static int sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize,
1420 	uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1421 static int sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize,
1422 	uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1423 static int sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
1424 	size_t buflen, daddr_t start_block, int path_flag);
1425 #define	sd_send_scsi_READ(un, bufaddr, buflen, start_block, path_flag)	\
1426 	sd_send_scsi_RDWR(un, SCMD_READ, bufaddr, buflen, start_block, \
1427 	path_flag)
1428 #define	sd_send_scsi_WRITE(un, bufaddr, buflen, start_block, path_flag)	\
1429 	sd_send_scsi_RDWR(un, SCMD_WRITE, bufaddr, buflen, start_block,\
1430 	path_flag)
1431 
1432 static int sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr,
1433 	uint16_t buflen, uchar_t page_code, uchar_t page_control,
1434 	uint16_t param_ptr, int path_flag);
1435 
1436 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1437 static void sd_free_rqs(struct sd_lun *un);
1438 
1439 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1440 	uchar_t *data, int len, int fmt);
1441 static void sd_panic_for_res_conflict(struct sd_lun *un);
1442 
1443 /*
1444  * Disk Ioctl Function Prototypes
1445  */
1446 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1447 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1448 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1449 
1450 /*
1451  * Multi-host Ioctl Prototypes
1452  */
1453 static int sd_check_mhd(dev_t dev, int interval);
1454 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1455 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1456 static char *sd_sname(uchar_t status);
1457 static void sd_mhd_resvd_recover(void *arg);
1458 static void sd_resv_reclaim_thread();
1459 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1460 static int sd_reserve_release(dev_t dev, int cmd);
1461 static void sd_rmv_resv_reclaim_req(dev_t dev);
1462 static void sd_mhd_reset_notify_cb(caddr_t arg);
1463 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1464 	mhioc_inkeys_t *usrp, int flag);
1465 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1466 	mhioc_inresvs_t *usrp, int flag);
1467 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1468 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1469 static int sd_mhdioc_release(dev_t dev);
1470 static int sd_mhdioc_register_devid(dev_t dev);
1471 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1472 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1473 
1474 /*
1475  * SCSI removable prototypes
1476  */
1477 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1478 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1479 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1480 static int sr_pause_resume(dev_t dev, int mode);
1481 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1482 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1483 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1484 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1485 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1486 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1487 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1488 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1489 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1490 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1491 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1492 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1493 static int sr_eject(dev_t dev);
1494 static void sr_ejected(register struct sd_lun *un);
1495 static int sr_check_wp(dev_t dev);
1496 static int sd_check_media(dev_t dev, enum dkio_state state);
1497 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1498 static void sd_delayed_cv_broadcast(void *arg);
1499 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1500 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1501 
1502 static int sd_log_page_supported(struct sd_lun *un, int log_page);
1503 
1504 /*
1505  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1506  */
1507 static void sd_check_for_writable_cd(struct sd_lun *un, int path_flag);
1508 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1509 static void sd_wm_cache_destructor(void *wm, void *un);
1510 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1511 	daddr_t endb, ushort_t typ);
1512 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1513 	daddr_t endb);
1514 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1515 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1516 static void sd_read_modify_write_task(void * arg);
1517 static int
1518 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1519 	struct buf **bpp);
1520 
1521 
1522 /*
1523  * Function prototypes for failfast support.
1524  */
1525 static void sd_failfast_flushq(struct sd_lun *un);
1526 static int sd_failfast_flushq_callback(struct buf *bp);
1527 
1528 /*
1529  * Function prototypes to check for lsi devices
1530  */
1531 static void sd_is_lsi(struct sd_lun *un);
1532 
1533 /*
1534  * Function prototypes for partial DMA support
1535  */
1536 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1537 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1538 
1539 
1540 /* Function prototypes for cmlb */
1541 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1542     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1543 
1544 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1545 
1546 /*
1547  * Constants for failfast support:
1548  *
1549  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1550  * failfast processing being performed.
1551  *
1552  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1553  * failfast processing on all bufs with B_FAILFAST set.
1554  */
1555 
1556 #define	SD_FAILFAST_INACTIVE		0
1557 #define	SD_FAILFAST_ACTIVE		1
1558 
1559 /*
1560  * Bitmask to control behavior of buf(9S) flushes when a transition to
1561  * the failfast state occurs. Optional bits include:
1562  *
1563  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1564  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1565  * be flushed.
1566  *
1567  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1568  * driver, in addition to the regular wait queue. This includes the xbuf
1569  * queues. When clear, only the driver's wait queue will be flushed.
1570  */
1571 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1572 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1573 
1574 /*
1575  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1576  * to flush all queues within the driver.
1577  */
1578 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1579 
1580 
1581 /*
1582  * SD Testing Fault Injection
1583  */
1584 #ifdef SD_FAULT_INJECTION
1585 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1586 static void sd_faultinjection(struct scsi_pkt *pktp);
1587 static void sd_injection_log(char *buf, struct sd_lun *un);
1588 #endif
1589 
1590 /*
1591  * Device driver ops vector
1592  */
1593 static struct cb_ops sd_cb_ops = {
1594 	sdopen,			/* open */
1595 	sdclose,		/* close */
1596 	sdstrategy,		/* strategy */
1597 	nodev,			/* print */
1598 	sddump,			/* dump */
1599 	sdread,			/* read */
1600 	sdwrite,		/* write */
1601 	sdioctl,		/* ioctl */
1602 	nodev,			/* devmap */
1603 	nodev,			/* mmap */
1604 	nodev,			/* segmap */
1605 	nochpoll,		/* poll */
1606 	sd_prop_op,		/* cb_prop_op */
1607 	0,			/* streamtab  */
1608 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1609 	CB_REV,			/* cb_rev */
1610 	sdaread, 		/* async I/O read entry point */
1611 	sdawrite		/* async I/O write entry point */
1612 };
1613 
1614 static struct dev_ops sd_ops = {
1615 	DEVO_REV,		/* devo_rev, */
1616 	0,			/* refcnt  */
1617 	sdinfo,			/* info */
1618 	nulldev,		/* identify */
1619 	sdprobe,		/* probe */
1620 	sdattach,		/* attach */
1621 	sddetach,		/* detach */
1622 	nodev,			/* reset */
1623 	&sd_cb_ops,		/* driver operations */
1624 	NULL,			/* bus operations */
1625 	sdpower			/* power */
1626 };
1627 
1628 
1629 /*
1630  * This is the loadable module wrapper.
1631  */
1632 #include <sys/modctl.h>
1633 
1634 static struct modldrv modldrv = {
1635 	&mod_driverops,		/* Type of module. This one is a driver */
1636 	SD_MODULE_NAME,		/* Module name. */
1637 	&sd_ops			/* driver ops */
1638 };
1639 
1640 
1641 static struct modlinkage modlinkage = {
1642 	MODREV_1,
1643 	&modldrv,
1644 	NULL
1645 };
1646 
1647 static cmlb_tg_ops_t sd_tgops = {
1648 	TG_DK_OPS_VERSION_1,
1649 	sd_tg_rdwr,
1650 	sd_tg_getinfo
1651 	};
1652 
1653 static struct scsi_asq_key_strings sd_additional_codes[] = {
1654 	0x81, 0, "Logical Unit is Reserved",
1655 	0x85, 0, "Audio Address Not Valid",
1656 	0xb6, 0, "Media Load Mechanism Failed",
1657 	0xB9, 0, "Audio Play Operation Aborted",
1658 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1659 	0x53, 2, "Medium removal prevented",
1660 	0x6f, 0, "Authentication failed during key exchange",
1661 	0x6f, 1, "Key not present",
1662 	0x6f, 2, "Key not established",
1663 	0x6f, 3, "Read without proper authentication",
1664 	0x6f, 4, "Mismatched region to this logical unit",
1665 	0x6f, 5, "Region reset count error",
1666 	0xffff, 0x0, NULL
1667 };
1668 
1669 
1670 /*
1671  * Struct for passing printing information for sense data messages
1672  */
1673 struct sd_sense_info {
1674 	int	ssi_severity;
1675 	int	ssi_pfa_flag;
1676 };
1677 
1678 /*
1679  * Table of function pointers for iostart-side routines. Separate "chains"
1680  * of layered function calls are formed by placing the function pointers
1681  * sequentially in the desired order. Functions are called according to an
1682  * incrementing table index ordering. The last function in each chain must
1683  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1684  * in the sd_iodone_chain[] array.
1685  *
1686  * Note: It may seem more natural to organize both the iostart and iodone
1687  * functions together, into an array of structures (or some similar
1688  * organization) with a common index, rather than two separate arrays which
1689  * must be maintained in synchronization. The purpose of this division is
1690  * to achieve improved performance: individual arrays allows for more
1691  * effective cache line utilization on certain platforms.
1692  */
1693 
1694 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1695 
1696 
1697 static sd_chain_t sd_iostart_chain[] = {
1698 
1699 	/* Chain for buf IO for disk drive targets (PM enabled) */
1700 	sd_mapblockaddr_iostart,	/* Index: 0 */
1701 	sd_pm_iostart,			/* Index: 1 */
1702 	sd_core_iostart,		/* Index: 2 */
1703 
1704 	/* Chain for buf IO for disk drive targets (PM disabled) */
1705 	sd_mapblockaddr_iostart,	/* Index: 3 */
1706 	sd_core_iostart,		/* Index: 4 */
1707 
1708 	/* Chain for buf IO for removable-media targets (PM enabled) */
1709 	sd_mapblockaddr_iostart,	/* Index: 5 */
1710 	sd_mapblocksize_iostart,	/* Index: 6 */
1711 	sd_pm_iostart,			/* Index: 7 */
1712 	sd_core_iostart,		/* Index: 8 */
1713 
1714 	/* Chain for buf IO for removable-media targets (PM disabled) */
1715 	sd_mapblockaddr_iostart,	/* Index: 9 */
1716 	sd_mapblocksize_iostart,	/* Index: 10 */
1717 	sd_core_iostart,		/* Index: 11 */
1718 
1719 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1720 	sd_mapblockaddr_iostart,	/* Index: 12 */
1721 	sd_checksum_iostart,		/* Index: 13 */
1722 	sd_pm_iostart,			/* Index: 14 */
1723 	sd_core_iostart,		/* Index: 15 */
1724 
1725 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1726 	sd_mapblockaddr_iostart,	/* Index: 16 */
1727 	sd_checksum_iostart,		/* Index: 17 */
1728 	sd_core_iostart,		/* Index: 18 */
1729 
1730 	/* Chain for USCSI commands (all targets) */
1731 	sd_pm_iostart,			/* Index: 19 */
1732 	sd_core_iostart,		/* Index: 20 */
1733 
1734 	/* Chain for checksumming USCSI commands (all targets) */
1735 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1736 	sd_pm_iostart,			/* Index: 22 */
1737 	sd_core_iostart,		/* Index: 23 */
1738 
1739 	/* Chain for "direct" USCSI commands (all targets) */
1740 	sd_core_iostart,		/* Index: 24 */
1741 
1742 	/* Chain for "direct priority" USCSI commands (all targets) */
1743 	sd_core_iostart,		/* Index: 25 */
1744 };
1745 
1746 /*
1747  * Macros to locate the first function of each iostart chain in the
1748  * sd_iostart_chain[] array. These are located by the index in the array.
1749  */
1750 #define	SD_CHAIN_DISK_IOSTART			0
1751 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1752 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1753 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1754 #define	SD_CHAIN_CHKSUM_IOSTART			12
1755 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1756 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1757 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1758 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1759 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1760 
1761 
1762 /*
1763  * Table of function pointers for the iodone-side routines for the driver-
1764  * internal layering mechanism.  The calling sequence for iodone routines
1765  * uses a decrementing table index, so the last routine called in a chain
1766  * must be at the lowest array index location for that chain.  The last
1767  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1768  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1769  * of the functions in an iodone side chain must correspond to the ordering
1770  * of the iostart routines for that chain.  Note that there is no iodone
1771  * side routine that corresponds to sd_core_iostart(), so there is no
1772  * entry in the table for this.
1773  */
1774 
1775 static sd_chain_t sd_iodone_chain[] = {
1776 
1777 	/* Chain for buf IO for disk drive targets (PM enabled) */
1778 	sd_buf_iodone,			/* Index: 0 */
1779 	sd_mapblockaddr_iodone,		/* Index: 1 */
1780 	sd_pm_iodone,			/* Index: 2 */
1781 
1782 	/* Chain for buf IO for disk drive targets (PM disabled) */
1783 	sd_buf_iodone,			/* Index: 3 */
1784 	sd_mapblockaddr_iodone,		/* Index: 4 */
1785 
1786 	/* Chain for buf IO for removable-media targets (PM enabled) */
1787 	sd_buf_iodone,			/* Index: 5 */
1788 	sd_mapblockaddr_iodone,		/* Index: 6 */
1789 	sd_mapblocksize_iodone,		/* Index: 7 */
1790 	sd_pm_iodone,			/* Index: 8 */
1791 
1792 	/* Chain for buf IO for removable-media targets (PM disabled) */
1793 	sd_buf_iodone,			/* Index: 9 */
1794 	sd_mapblockaddr_iodone,		/* Index: 10 */
1795 	sd_mapblocksize_iodone,		/* Index: 11 */
1796 
1797 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1798 	sd_buf_iodone,			/* Index: 12 */
1799 	sd_mapblockaddr_iodone,		/* Index: 13 */
1800 	sd_checksum_iodone,		/* Index: 14 */
1801 	sd_pm_iodone,			/* Index: 15 */
1802 
1803 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1804 	sd_buf_iodone,			/* Index: 16 */
1805 	sd_mapblockaddr_iodone,		/* Index: 17 */
1806 	sd_checksum_iodone,		/* Index: 18 */
1807 
1808 	/* Chain for USCSI commands (non-checksum targets) */
1809 	sd_uscsi_iodone,		/* Index: 19 */
1810 	sd_pm_iodone,			/* Index: 20 */
1811 
1812 	/* Chain for USCSI commands (checksum targets) */
1813 	sd_uscsi_iodone,		/* Index: 21 */
1814 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1815 	sd_pm_iodone,			/* Index: 22 */
1816 
1817 	/* Chain for "direct" USCSI commands (all targets) */
1818 	sd_uscsi_iodone,		/* Index: 24 */
1819 
1820 	/* Chain for "direct priority" USCSI commands (all targets) */
1821 	sd_uscsi_iodone,		/* Index: 25 */
1822 };
1823 
1824 
1825 /*
1826  * Macros to locate the "first" function in the sd_iodone_chain[] array for
1827  * each iodone-side chain. These are located by the array index, but as the
1828  * iodone side functions are called in a decrementing-index order, the
1829  * highest index number in each chain must be specified (as these correspond
1830  * to the first function in the iodone chain that will be called by the core
1831  * at IO completion time).
1832  */
1833 
1834 #define	SD_CHAIN_DISK_IODONE			2
1835 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
1836 #define	SD_CHAIN_RMMEDIA_IODONE			8
1837 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
1838 #define	SD_CHAIN_CHKSUM_IODONE			15
1839 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
1840 #define	SD_CHAIN_USCSI_CMD_IODONE		20
1841 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
1842 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
1843 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
1844 
1845 
1846 
1847 
1848 /*
1849  * Array to map a layering chain index to the appropriate initpkt routine.
1850  * The redundant entries are present so that the index used for accessing
1851  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1852  * with this table as well.
1853  */
1854 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
1855 
1856 static sd_initpkt_t	sd_initpkt_map[] = {
1857 
1858 	/* Chain for buf IO for disk drive targets (PM enabled) */
1859 	sd_initpkt_for_buf,		/* Index: 0 */
1860 	sd_initpkt_for_buf,		/* Index: 1 */
1861 	sd_initpkt_for_buf,		/* Index: 2 */
1862 
1863 	/* Chain for buf IO for disk drive targets (PM disabled) */
1864 	sd_initpkt_for_buf,		/* Index: 3 */
1865 	sd_initpkt_for_buf,		/* Index: 4 */
1866 
1867 	/* Chain for buf IO for removable-media targets (PM enabled) */
1868 	sd_initpkt_for_buf,		/* Index: 5 */
1869 	sd_initpkt_for_buf,		/* Index: 6 */
1870 	sd_initpkt_for_buf,		/* Index: 7 */
1871 	sd_initpkt_for_buf,		/* Index: 8 */
1872 
1873 	/* Chain for buf IO for removable-media targets (PM disabled) */
1874 	sd_initpkt_for_buf,		/* Index: 9 */
1875 	sd_initpkt_for_buf,		/* Index: 10 */
1876 	sd_initpkt_for_buf,		/* Index: 11 */
1877 
1878 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1879 	sd_initpkt_for_buf,		/* Index: 12 */
1880 	sd_initpkt_for_buf,		/* Index: 13 */
1881 	sd_initpkt_for_buf,		/* Index: 14 */
1882 	sd_initpkt_for_buf,		/* Index: 15 */
1883 
1884 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1885 	sd_initpkt_for_buf,		/* Index: 16 */
1886 	sd_initpkt_for_buf,		/* Index: 17 */
1887 	sd_initpkt_for_buf,		/* Index: 18 */
1888 
1889 	/* Chain for USCSI commands (non-checksum targets) */
1890 	sd_initpkt_for_uscsi,		/* Index: 19 */
1891 	sd_initpkt_for_uscsi,		/* Index: 20 */
1892 
1893 	/* Chain for USCSI commands (checksum targets) */
1894 	sd_initpkt_for_uscsi,		/* Index: 21 */
1895 	sd_initpkt_for_uscsi,		/* Index: 22 */
1896 	sd_initpkt_for_uscsi,		/* Index: 22 */
1897 
1898 	/* Chain for "direct" USCSI commands (all targets) */
1899 	sd_initpkt_for_uscsi,		/* Index: 24 */
1900 
1901 	/* Chain for "direct priority" USCSI commands (all targets) */
1902 	sd_initpkt_for_uscsi,		/* Index: 25 */
1903 
1904 };
1905 
1906 
1907 /*
1908  * Array to map a layering chain index to the appropriate destroypktpkt routine.
1909  * The redundant entries are present so that the index used for accessing
1910  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1911  * with this table as well.
1912  */
1913 typedef void (*sd_destroypkt_t)(struct buf *);
1914 
1915 static sd_destroypkt_t	sd_destroypkt_map[] = {
1916 
1917 	/* Chain for buf IO for disk drive targets (PM enabled) */
1918 	sd_destroypkt_for_buf,		/* Index: 0 */
1919 	sd_destroypkt_for_buf,		/* Index: 1 */
1920 	sd_destroypkt_for_buf,		/* Index: 2 */
1921 
1922 	/* Chain for buf IO for disk drive targets (PM disabled) */
1923 	sd_destroypkt_for_buf,		/* Index: 3 */
1924 	sd_destroypkt_for_buf,		/* Index: 4 */
1925 
1926 	/* Chain for buf IO for removable-media targets (PM enabled) */
1927 	sd_destroypkt_for_buf,		/* Index: 5 */
1928 	sd_destroypkt_for_buf,		/* Index: 6 */
1929 	sd_destroypkt_for_buf,		/* Index: 7 */
1930 	sd_destroypkt_for_buf,		/* Index: 8 */
1931 
1932 	/* Chain for buf IO for removable-media targets (PM disabled) */
1933 	sd_destroypkt_for_buf,		/* Index: 9 */
1934 	sd_destroypkt_for_buf,		/* Index: 10 */
1935 	sd_destroypkt_for_buf,		/* Index: 11 */
1936 
1937 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1938 	sd_destroypkt_for_buf,		/* Index: 12 */
1939 	sd_destroypkt_for_buf,		/* Index: 13 */
1940 	sd_destroypkt_for_buf,		/* Index: 14 */
1941 	sd_destroypkt_for_buf,		/* Index: 15 */
1942 
1943 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1944 	sd_destroypkt_for_buf,		/* Index: 16 */
1945 	sd_destroypkt_for_buf,		/* Index: 17 */
1946 	sd_destroypkt_for_buf,		/* Index: 18 */
1947 
1948 	/* Chain for USCSI commands (non-checksum targets) */
1949 	sd_destroypkt_for_uscsi,	/* Index: 19 */
1950 	sd_destroypkt_for_uscsi,	/* Index: 20 */
1951 
1952 	/* Chain for USCSI commands (checksum targets) */
1953 	sd_destroypkt_for_uscsi,	/* Index: 21 */
1954 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1955 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1956 
1957 	/* Chain for "direct" USCSI commands (all targets) */
1958 	sd_destroypkt_for_uscsi,	/* Index: 24 */
1959 
1960 	/* Chain for "direct priority" USCSI commands (all targets) */
1961 	sd_destroypkt_for_uscsi,	/* Index: 25 */
1962 
1963 };
1964 
1965 
1966 
1967 /*
1968  * Array to map a layering chain index to the appropriate chain "type".
1969  * The chain type indicates a specific property/usage of the chain.
1970  * The redundant entries are present so that the index used for accessing
1971  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1972  * with this table as well.
1973  */
1974 
1975 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
1976 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
1977 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
1978 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
1979 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
1980 						/* (for error recovery) */
1981 
1982 static int sd_chain_type_map[] = {
1983 
1984 	/* Chain for buf IO for disk drive targets (PM enabled) */
1985 	SD_CHAIN_BUFIO,			/* Index: 0 */
1986 	SD_CHAIN_BUFIO,			/* Index: 1 */
1987 	SD_CHAIN_BUFIO,			/* Index: 2 */
1988 
1989 	/* Chain for buf IO for disk drive targets (PM disabled) */
1990 	SD_CHAIN_BUFIO,			/* Index: 3 */
1991 	SD_CHAIN_BUFIO,			/* Index: 4 */
1992 
1993 	/* Chain for buf IO for removable-media targets (PM enabled) */
1994 	SD_CHAIN_BUFIO,			/* Index: 5 */
1995 	SD_CHAIN_BUFIO,			/* Index: 6 */
1996 	SD_CHAIN_BUFIO,			/* Index: 7 */
1997 	SD_CHAIN_BUFIO,			/* Index: 8 */
1998 
1999 	/* Chain for buf IO for removable-media targets (PM disabled) */
2000 	SD_CHAIN_BUFIO,			/* Index: 9 */
2001 	SD_CHAIN_BUFIO,			/* Index: 10 */
2002 	SD_CHAIN_BUFIO,			/* Index: 11 */
2003 
2004 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2005 	SD_CHAIN_BUFIO,			/* Index: 12 */
2006 	SD_CHAIN_BUFIO,			/* Index: 13 */
2007 	SD_CHAIN_BUFIO,			/* Index: 14 */
2008 	SD_CHAIN_BUFIO,			/* Index: 15 */
2009 
2010 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2011 	SD_CHAIN_BUFIO,			/* Index: 16 */
2012 	SD_CHAIN_BUFIO,			/* Index: 17 */
2013 	SD_CHAIN_BUFIO,			/* Index: 18 */
2014 
2015 	/* Chain for USCSI commands (non-checksum targets) */
2016 	SD_CHAIN_USCSI,			/* Index: 19 */
2017 	SD_CHAIN_USCSI,			/* Index: 20 */
2018 
2019 	/* Chain for USCSI commands (checksum targets) */
2020 	SD_CHAIN_USCSI,			/* Index: 21 */
2021 	SD_CHAIN_USCSI,			/* Index: 22 */
2022 	SD_CHAIN_USCSI,			/* Index: 22 */
2023 
2024 	/* Chain for "direct" USCSI commands (all targets) */
2025 	SD_CHAIN_DIRECT,		/* Index: 24 */
2026 
2027 	/* Chain for "direct priority" USCSI commands (all targets) */
2028 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2029 };
2030 
2031 
2032 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2033 #define	SD_IS_BUFIO(xp)			\
2034 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2035 
2036 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2037 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2038 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2039 
2040 
2041 
2042 /*
2043  * Struct, array, and macros to map a specific chain to the appropriate
2044  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2045  *
2046  * The sd_chain_index_map[] array is used at attach time to set the various
2047  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2048  * chain to be used with the instance. This allows different instances to use
2049  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2050  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2051  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2052  * dynamically & without the use of locking; and (2) a layer may update the
2053  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2054  * to allow for deferred processing of an IO within the same chain from a
2055  * different execution context.
2056  */
2057 
2058 struct sd_chain_index {
2059 	int	sci_iostart_index;
2060 	int	sci_iodone_index;
2061 };
2062 
2063 static struct sd_chain_index	sd_chain_index_map[] = {
2064 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2065 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2066 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2067 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2068 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2069 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2070 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2071 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2072 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2073 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2074 };
2075 
2076 
2077 /*
2078  * The following are indexes into the sd_chain_index_map[] array.
2079  */
2080 
2081 /* un->un_buf_chain_type must be set to one of these */
2082 #define	SD_CHAIN_INFO_DISK		0
2083 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2084 #define	SD_CHAIN_INFO_RMMEDIA		2
2085 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2086 #define	SD_CHAIN_INFO_CHKSUM		4
2087 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2088 
2089 /* un->un_uscsi_chain_type must be set to one of these */
2090 #define	SD_CHAIN_INFO_USCSI_CMD		6
2091 /* USCSI with PM disabled is the same as DIRECT */
2092 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2093 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2094 
2095 /* un->un_direct_chain_type must be set to one of these */
2096 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2097 
2098 /* un->un_priority_chain_type must be set to one of these */
2099 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2100 
2101 /* size for devid inquiries */
2102 #define	MAX_INQUIRY_SIZE		0xF0
2103 
2104 /*
2105  * Macros used by functions to pass a given buf(9S) struct along to the
2106  * next function in the layering chain for further processing.
2107  *
2108  * In the following macros, passing more than three arguments to the called
2109  * routines causes the optimizer for the SPARC compiler to stop doing tail
2110  * call elimination which results in significant performance degradation.
2111  */
2112 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2113 	((*(sd_iostart_chain[index]))(index, un, bp))
2114 
2115 #define	SD_BEGIN_IODONE(index, un, bp)	\
2116 	((*(sd_iodone_chain[index]))(index, un, bp))
2117 
2118 #define	SD_NEXT_IOSTART(index, un, bp)				\
2119 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2120 
2121 #define	SD_NEXT_IODONE(index, un, bp)				\
2122 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2123 
2124 /*
2125  *    Function: _init
2126  *
2127  * Description: This is the driver _init(9E) entry point.
2128  *
2129  * Return Code: Returns the value from mod_install(9F) or
2130  *		ddi_soft_state_init(9F) as appropriate.
2131  *
2132  *     Context: Called when driver module loaded.
2133  */
2134 
2135 int
2136 _init(void)
2137 {
2138 	int	err;
2139 
2140 	/* establish driver name from module name */
2141 	sd_label = mod_modname(&modlinkage);
2142 
2143 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2144 	    SD_MAXUNIT);
2145 
2146 	if (err != 0) {
2147 		return (err);
2148 	}
2149 
2150 	mutex_init(&sd_detach_mutex, NULL, MUTEX_DRIVER, NULL);
2151 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2152 	mutex_init(&sd_label_mutex,  NULL, MUTEX_DRIVER, NULL);
2153 
2154 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2155 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2156 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2157 
2158 	/*
2159 	 * it's ok to init here even for fibre device
2160 	 */
2161 	sd_scsi_probe_cache_init();
2162 
2163 	sd_scsi_target_lun_init();
2164 
2165 	/*
2166 	 * Creating taskq before mod_install ensures that all callers (threads)
2167 	 * that enter the module after a successfull mod_install encounter
2168 	 * a valid taskq.
2169 	 */
2170 	sd_taskq_create();
2171 
2172 	err = mod_install(&modlinkage);
2173 	if (err != 0) {
2174 		/* delete taskq if install fails */
2175 		sd_taskq_delete();
2176 
2177 		mutex_destroy(&sd_detach_mutex);
2178 		mutex_destroy(&sd_log_mutex);
2179 		mutex_destroy(&sd_label_mutex);
2180 
2181 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2182 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2183 		cv_destroy(&sd_tr.srq_inprocess_cv);
2184 
2185 		sd_scsi_probe_cache_fini();
2186 
2187 		sd_scsi_target_lun_fini();
2188 
2189 		ddi_soft_state_fini(&sd_state);
2190 		return (err);
2191 	}
2192 
2193 	return (err);
2194 }
2195 
2196 
2197 /*
2198  *    Function: _fini
2199  *
2200  * Description: This is the driver _fini(9E) entry point.
2201  *
2202  * Return Code: Returns the value from mod_remove(9F)
2203  *
2204  *     Context: Called when driver module is unloaded.
2205  */
2206 
2207 int
2208 _fini(void)
2209 {
2210 	int err;
2211 
2212 	if ((err = mod_remove(&modlinkage)) != 0) {
2213 		return (err);
2214 	}
2215 
2216 	sd_taskq_delete();
2217 
2218 	mutex_destroy(&sd_detach_mutex);
2219 	mutex_destroy(&sd_log_mutex);
2220 	mutex_destroy(&sd_label_mutex);
2221 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2222 
2223 	sd_scsi_probe_cache_fini();
2224 
2225 	sd_scsi_target_lun_fini();
2226 
2227 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2228 	cv_destroy(&sd_tr.srq_inprocess_cv);
2229 
2230 	ddi_soft_state_fini(&sd_state);
2231 
2232 	return (err);
2233 }
2234 
2235 
2236 /*
2237  *    Function: _info
2238  *
2239  * Description: This is the driver _info(9E) entry point.
2240  *
2241  *   Arguments: modinfop - pointer to the driver modinfo structure
2242  *
2243  * Return Code: Returns the value from mod_info(9F).
2244  *
2245  *     Context: Kernel thread context
2246  */
2247 
2248 int
2249 _info(struct modinfo *modinfop)
2250 {
2251 	return (mod_info(&modlinkage, modinfop));
2252 }
2253 
2254 
2255 /*
2256  * The following routines implement the driver message logging facility.
2257  * They provide component- and level- based debug output filtering.
2258  * Output may also be restricted to messages for a single instance by
2259  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2260  * to NULL, then messages for all instances are printed.
2261  *
2262  * These routines have been cloned from each other due to the language
2263  * constraints of macros and variable argument list processing.
2264  */
2265 
2266 
2267 /*
2268  *    Function: sd_log_err
2269  *
2270  * Description: This routine is called by the SD_ERROR macro for debug
2271  *		logging of error conditions.
2272  *
2273  *   Arguments: comp - driver component being logged
2274  *		dev  - pointer to driver info structure
2275  *		fmt  - error string and format to be logged
2276  */
2277 
2278 static void
2279 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2280 {
2281 	va_list		ap;
2282 	dev_info_t	*dev;
2283 
2284 	ASSERT(un != NULL);
2285 	dev = SD_DEVINFO(un);
2286 	ASSERT(dev != NULL);
2287 
2288 	/*
2289 	 * Filter messages based on the global component and level masks.
2290 	 * Also print if un matches the value of sd_debug_un, or if
2291 	 * sd_debug_un is set to NULL.
2292 	 */
2293 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2294 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2295 		mutex_enter(&sd_log_mutex);
2296 		va_start(ap, fmt);
2297 		(void) vsprintf(sd_log_buf, fmt, ap);
2298 		va_end(ap);
2299 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2300 		mutex_exit(&sd_log_mutex);
2301 	}
2302 #ifdef SD_FAULT_INJECTION
2303 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2304 	if (un->sd_injection_mask & comp) {
2305 		mutex_enter(&sd_log_mutex);
2306 		va_start(ap, fmt);
2307 		(void) vsprintf(sd_log_buf, fmt, ap);
2308 		va_end(ap);
2309 		sd_injection_log(sd_log_buf, un);
2310 		mutex_exit(&sd_log_mutex);
2311 	}
2312 #endif
2313 }
2314 
2315 
2316 /*
2317  *    Function: sd_log_info
2318  *
2319  * Description: This routine is called by the SD_INFO macro for debug
2320  *		logging of general purpose informational conditions.
2321  *
2322  *   Arguments: comp - driver component being logged
2323  *		dev  - pointer to driver info structure
2324  *		fmt  - info string and format to be logged
2325  */
2326 
2327 static void
2328 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2329 {
2330 	va_list		ap;
2331 	dev_info_t	*dev;
2332 
2333 	ASSERT(un != NULL);
2334 	dev = SD_DEVINFO(un);
2335 	ASSERT(dev != NULL);
2336 
2337 	/*
2338 	 * Filter messages based on the global component and level masks.
2339 	 * Also print if un matches the value of sd_debug_un, or if
2340 	 * sd_debug_un is set to NULL.
2341 	 */
2342 	if ((sd_component_mask & component) &&
2343 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2344 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2345 		mutex_enter(&sd_log_mutex);
2346 		va_start(ap, fmt);
2347 		(void) vsprintf(sd_log_buf, fmt, ap);
2348 		va_end(ap);
2349 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2350 		mutex_exit(&sd_log_mutex);
2351 	}
2352 #ifdef SD_FAULT_INJECTION
2353 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2354 	if (un->sd_injection_mask & component) {
2355 		mutex_enter(&sd_log_mutex);
2356 		va_start(ap, fmt);
2357 		(void) vsprintf(sd_log_buf, fmt, ap);
2358 		va_end(ap);
2359 		sd_injection_log(sd_log_buf, un);
2360 		mutex_exit(&sd_log_mutex);
2361 	}
2362 #endif
2363 }
2364 
2365 
2366 /*
2367  *    Function: sd_log_trace
2368  *
2369  * Description: This routine is called by the SD_TRACE macro for debug
2370  *		logging of trace conditions (i.e. function entry/exit).
2371  *
2372  *   Arguments: comp - driver component being logged
2373  *		dev  - pointer to driver info structure
2374  *		fmt  - trace string and format to be logged
2375  */
2376 
2377 static void
2378 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2379 {
2380 	va_list		ap;
2381 	dev_info_t	*dev;
2382 
2383 	ASSERT(un != NULL);
2384 	dev = SD_DEVINFO(un);
2385 	ASSERT(dev != NULL);
2386 
2387 	/*
2388 	 * Filter messages based on the global component and level masks.
2389 	 * Also print if un matches the value of sd_debug_un, or if
2390 	 * sd_debug_un is set to NULL.
2391 	 */
2392 	if ((sd_component_mask & component) &&
2393 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2394 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2395 		mutex_enter(&sd_log_mutex);
2396 		va_start(ap, fmt);
2397 		(void) vsprintf(sd_log_buf, fmt, ap);
2398 		va_end(ap);
2399 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2400 		mutex_exit(&sd_log_mutex);
2401 	}
2402 #ifdef SD_FAULT_INJECTION
2403 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2404 	if (un->sd_injection_mask & component) {
2405 		mutex_enter(&sd_log_mutex);
2406 		va_start(ap, fmt);
2407 		(void) vsprintf(sd_log_buf, fmt, ap);
2408 		va_end(ap);
2409 		sd_injection_log(sd_log_buf, un);
2410 		mutex_exit(&sd_log_mutex);
2411 	}
2412 #endif
2413 }
2414 
2415 
2416 /*
2417  *    Function: sdprobe
2418  *
2419  * Description: This is the driver probe(9e) entry point function.
2420  *
2421  *   Arguments: devi - opaque device info handle
2422  *
2423  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2424  *              DDI_PROBE_FAILURE: If the probe failed.
2425  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2426  *				   but may be present in the future.
2427  */
2428 
2429 static int
2430 sdprobe(dev_info_t *devi)
2431 {
2432 	struct scsi_device	*devp;
2433 	int			rval;
2434 	int			instance;
2435 
2436 	/*
2437 	 * if it wasn't for pln, sdprobe could actually be nulldev
2438 	 * in the "__fibre" case.
2439 	 */
2440 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2441 		return (DDI_PROBE_DONTCARE);
2442 	}
2443 
2444 	devp = ddi_get_driver_private(devi);
2445 
2446 	if (devp == NULL) {
2447 		/* Ooops... nexus driver is mis-configured... */
2448 		return (DDI_PROBE_FAILURE);
2449 	}
2450 
2451 	instance = ddi_get_instance(devi);
2452 
2453 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2454 		return (DDI_PROBE_PARTIAL);
2455 	}
2456 
2457 	/*
2458 	 * Call the SCSA utility probe routine to see if we actually
2459 	 * have a target at this SCSI nexus.
2460 	 */
2461 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2462 	case SCSIPROBE_EXISTS:
2463 		switch (devp->sd_inq->inq_dtype) {
2464 		case DTYPE_DIRECT:
2465 			rval = DDI_PROBE_SUCCESS;
2466 			break;
2467 		case DTYPE_RODIRECT:
2468 			/* CDs etc. Can be removable media */
2469 			rval = DDI_PROBE_SUCCESS;
2470 			break;
2471 		case DTYPE_OPTICAL:
2472 			/*
2473 			 * Rewritable optical driver HP115AA
2474 			 * Can also be removable media
2475 			 */
2476 
2477 			/*
2478 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2479 			 * pre solaris 9 sparc sd behavior is required
2480 			 *
2481 			 * If first time through and sd_dtype_optical_bind
2482 			 * has not been set in /etc/system check properties
2483 			 */
2484 
2485 			if (sd_dtype_optical_bind  < 0) {
2486 				sd_dtype_optical_bind = ddi_prop_get_int
2487 				    (DDI_DEV_T_ANY, devi, 0,
2488 				    "optical-device-bind", 1);
2489 			}
2490 
2491 			if (sd_dtype_optical_bind == 0) {
2492 				rval = DDI_PROBE_FAILURE;
2493 			} else {
2494 				rval = DDI_PROBE_SUCCESS;
2495 			}
2496 			break;
2497 
2498 		case DTYPE_NOTPRESENT:
2499 		default:
2500 			rval = DDI_PROBE_FAILURE;
2501 			break;
2502 		}
2503 		break;
2504 	default:
2505 		rval = DDI_PROBE_PARTIAL;
2506 		break;
2507 	}
2508 
2509 	/*
2510 	 * This routine checks for resource allocation prior to freeing,
2511 	 * so it will take care of the "smart probing" case where a
2512 	 * scsi_probe() may or may not have been issued and will *not*
2513 	 * free previously-freed resources.
2514 	 */
2515 	scsi_unprobe(devp);
2516 	return (rval);
2517 }
2518 
2519 
2520 /*
2521  *    Function: sdinfo
2522  *
2523  * Description: This is the driver getinfo(9e) entry point function.
2524  * 		Given the device number, return the devinfo pointer from
2525  *		the scsi_device structure or the instance number
2526  *		associated with the dev_t.
2527  *
2528  *   Arguments: dip     - pointer to device info structure
2529  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2530  *			  DDI_INFO_DEVT2INSTANCE)
2531  *		arg     - driver dev_t
2532  *		resultp - user buffer for request response
2533  *
2534  * Return Code: DDI_SUCCESS
2535  *              DDI_FAILURE
2536  */
2537 /* ARGSUSED */
2538 static int
2539 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2540 {
2541 	struct sd_lun	*un;
2542 	dev_t		dev;
2543 	int		instance;
2544 	int		error;
2545 
2546 	switch (infocmd) {
2547 	case DDI_INFO_DEVT2DEVINFO:
2548 		dev = (dev_t)arg;
2549 		instance = SDUNIT(dev);
2550 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2551 			return (DDI_FAILURE);
2552 		}
2553 		*result = (void *) SD_DEVINFO(un);
2554 		error = DDI_SUCCESS;
2555 		break;
2556 	case DDI_INFO_DEVT2INSTANCE:
2557 		dev = (dev_t)arg;
2558 		instance = SDUNIT(dev);
2559 		*result = (void *)(uintptr_t)instance;
2560 		error = DDI_SUCCESS;
2561 		break;
2562 	default:
2563 		error = DDI_FAILURE;
2564 	}
2565 	return (error);
2566 }
2567 
2568 /*
2569  *    Function: sd_prop_op
2570  *
2571  * Description: This is the driver prop_op(9e) entry point function.
2572  *		Return the number of blocks for the partition in question
2573  *		or forward the request to the property facilities.
2574  *
2575  *   Arguments: dev       - device number
2576  *		dip       - pointer to device info structure
2577  *		prop_op   - property operator
2578  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2579  *		name      - pointer to property name
2580  *		valuep    - pointer or address of the user buffer
2581  *		lengthp   - property length
2582  *
2583  * Return Code: DDI_PROP_SUCCESS
2584  *              DDI_PROP_NOT_FOUND
2585  *              DDI_PROP_UNDEFINED
2586  *              DDI_PROP_NO_MEMORY
2587  *              DDI_PROP_BUF_TOO_SMALL
2588  */
2589 
2590 static int
2591 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2592 	char *name, caddr_t valuep, int *lengthp)
2593 {
2594 	int		instance = ddi_get_instance(dip);
2595 	struct sd_lun	*un;
2596 	uint64_t	nblocks64;
2597 	uint_t		dblk;
2598 
2599 	/*
2600 	 * Our dynamic properties are all device specific and size oriented.
2601 	 * Requests issued under conditions where size is valid are passed
2602 	 * to ddi_prop_op_nblocks with the size information, otherwise the
2603 	 * request is passed to ddi_prop_op. Size depends on valid geometry.
2604 	 */
2605 	un = ddi_get_soft_state(sd_state, instance);
2606 	if ((dev == DDI_DEV_T_ANY) || (un == NULL)) {
2607 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2608 		    name, valuep, lengthp));
2609 	} else if (!SD_IS_VALID_LABEL(un)) {
2610 		return (ddi_prop_op(dev, dip, prop_op, mod_flags, name,
2611 		    valuep, lengthp));
2612 	}
2613 
2614 	/* get nblocks value */
2615 	ASSERT(!mutex_owned(SD_MUTEX(un)));
2616 
2617 	(void) cmlb_partinfo(un->un_cmlbhandle, SDPART(dev),
2618 	    (diskaddr_t *)&nblocks64, NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
2619 
2620 	/* report size in target size blocks */
2621 	dblk = un->un_tgt_blocksize / un->un_sys_blocksize;
2622 	return (ddi_prop_op_nblocks_blksize(dev, dip, prop_op, mod_flags,
2623 	    name, valuep, lengthp, nblocks64 / dblk, un->un_tgt_blocksize));
2624 }
2625 
2626 /*
2627  * The following functions are for smart probing:
2628  * sd_scsi_probe_cache_init()
2629  * sd_scsi_probe_cache_fini()
2630  * sd_scsi_clear_probe_cache()
2631  * sd_scsi_probe_with_cache()
2632  */
2633 
2634 /*
2635  *    Function: sd_scsi_probe_cache_init
2636  *
2637  * Description: Initializes the probe response cache mutex and head pointer.
2638  *
2639  *     Context: Kernel thread context
2640  */
2641 
2642 static void
2643 sd_scsi_probe_cache_init(void)
2644 {
2645 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2646 	sd_scsi_probe_cache_head = NULL;
2647 }
2648 
2649 
2650 /*
2651  *    Function: sd_scsi_probe_cache_fini
2652  *
2653  * Description: Frees all resources associated with the probe response cache.
2654  *
2655  *     Context: Kernel thread context
2656  */
2657 
2658 static void
2659 sd_scsi_probe_cache_fini(void)
2660 {
2661 	struct sd_scsi_probe_cache *cp;
2662 	struct sd_scsi_probe_cache *ncp;
2663 
2664 	/* Clean up our smart probing linked list */
2665 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2666 		ncp = cp->next;
2667 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2668 	}
2669 	sd_scsi_probe_cache_head = NULL;
2670 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2671 }
2672 
2673 
2674 /*
2675  *    Function: sd_scsi_clear_probe_cache
2676  *
2677  * Description: This routine clears the probe response cache. This is
2678  *		done when open() returns ENXIO so that when deferred
2679  *		attach is attempted (possibly after a device has been
2680  *		turned on) we will retry the probe. Since we don't know
2681  *		which target we failed to open, we just clear the
2682  *		entire cache.
2683  *
2684  *     Context: Kernel thread context
2685  */
2686 
2687 static void
2688 sd_scsi_clear_probe_cache(void)
2689 {
2690 	struct sd_scsi_probe_cache	*cp;
2691 	int				i;
2692 
2693 	mutex_enter(&sd_scsi_probe_cache_mutex);
2694 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2695 		/*
2696 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2697 		 * force probing to be performed the next time
2698 		 * sd_scsi_probe_with_cache is called.
2699 		 */
2700 		for (i = 0; i < NTARGETS_WIDE; i++) {
2701 			cp->cache[i] = SCSIPROBE_EXISTS;
2702 		}
2703 	}
2704 	mutex_exit(&sd_scsi_probe_cache_mutex);
2705 }
2706 
2707 
2708 /*
2709  *    Function: sd_scsi_probe_with_cache
2710  *
2711  * Description: This routine implements support for a scsi device probe
2712  *		with cache. The driver maintains a cache of the target
2713  *		responses to scsi probes. If we get no response from a
2714  *		target during a probe inquiry, we remember that, and we
2715  *		avoid additional calls to scsi_probe on non-zero LUNs
2716  *		on the same target until the cache is cleared. By doing
2717  *		so we avoid the 1/4 sec selection timeout for nonzero
2718  *		LUNs. lun0 of a target is always probed.
2719  *
2720  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2721  *              waitfunc - indicates what the allocator routines should
2722  *			   do when resources are not available. This value
2723  *			   is passed on to scsi_probe() when that routine
2724  *			   is called.
2725  *
2726  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2727  *		otherwise the value returned by scsi_probe(9F).
2728  *
2729  *     Context: Kernel thread context
2730  */
2731 
2732 static int
2733 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2734 {
2735 	struct sd_scsi_probe_cache	*cp;
2736 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2737 	int		lun, tgt;
2738 
2739 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2740 	    SCSI_ADDR_PROP_LUN, 0);
2741 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2742 	    SCSI_ADDR_PROP_TARGET, -1);
2743 
2744 	/* Make sure caching enabled and target in range */
2745 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2746 		/* do it the old way (no cache) */
2747 		return (scsi_probe(devp, waitfn));
2748 	}
2749 
2750 	mutex_enter(&sd_scsi_probe_cache_mutex);
2751 
2752 	/* Find the cache for this scsi bus instance */
2753 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2754 		if (cp->pdip == pdip) {
2755 			break;
2756 		}
2757 	}
2758 
2759 	/* If we can't find a cache for this pdip, create one */
2760 	if (cp == NULL) {
2761 		int i;
2762 
2763 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
2764 		    KM_SLEEP);
2765 		cp->pdip = pdip;
2766 		cp->next = sd_scsi_probe_cache_head;
2767 		sd_scsi_probe_cache_head = cp;
2768 		for (i = 0; i < NTARGETS_WIDE; i++) {
2769 			cp->cache[i] = SCSIPROBE_EXISTS;
2770 		}
2771 	}
2772 
2773 	mutex_exit(&sd_scsi_probe_cache_mutex);
2774 
2775 	/* Recompute the cache for this target if LUN zero */
2776 	if (lun == 0) {
2777 		cp->cache[tgt] = SCSIPROBE_EXISTS;
2778 	}
2779 
2780 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
2781 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
2782 		return (SCSIPROBE_NORESP);
2783 	}
2784 
2785 	/* Do the actual probe; save & return the result */
2786 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
2787 }
2788 
2789 
2790 /*
2791  *    Function: sd_scsi_target_lun_init
2792  *
2793  * Description: Initializes the attached lun chain mutex and head pointer.
2794  *
2795  *     Context: Kernel thread context
2796  */
2797 
2798 static void
2799 sd_scsi_target_lun_init(void)
2800 {
2801 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
2802 	sd_scsi_target_lun_head = NULL;
2803 }
2804 
2805 
2806 /*
2807  *    Function: sd_scsi_target_lun_fini
2808  *
2809  * Description: Frees all resources associated with the attached lun
2810  *              chain
2811  *
2812  *     Context: Kernel thread context
2813  */
2814 
2815 static void
2816 sd_scsi_target_lun_fini(void)
2817 {
2818 	struct sd_scsi_hba_tgt_lun	*cp;
2819 	struct sd_scsi_hba_tgt_lun	*ncp;
2820 
2821 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
2822 		ncp = cp->next;
2823 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
2824 	}
2825 	sd_scsi_target_lun_head = NULL;
2826 	mutex_destroy(&sd_scsi_target_lun_mutex);
2827 }
2828 
2829 
2830 /*
2831  *    Function: sd_scsi_get_target_lun_count
2832  *
2833  * Description: This routine will check in the attached lun chain to see
2834  * 		how many luns are attached on the required SCSI controller
2835  * 		and target. Currently, some capabilities like tagged queue
2836  *		are supported per target based by HBA. So all luns in a
2837  *		target have the same capabilities. Based on this assumption,
2838  * 		sd should only set these capabilities once per target. This
2839  *		function is called when sd needs to decide how many luns
2840  *		already attached on a target.
2841  *
2842  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
2843  *			  controller device.
2844  *              target	- The target ID on the controller's SCSI bus.
2845  *
2846  * Return Code: The number of luns attached on the required target and
2847  *		controller.
2848  *		-1 if target ID is not in parallel SCSI scope or the given
2849  * 		dip is not in the chain.
2850  *
2851  *     Context: Kernel thread context
2852  */
2853 
2854 static int
2855 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
2856 {
2857 	struct sd_scsi_hba_tgt_lun	*cp;
2858 
2859 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
2860 		return (-1);
2861 	}
2862 
2863 	mutex_enter(&sd_scsi_target_lun_mutex);
2864 
2865 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2866 		if (cp->pdip == dip) {
2867 			break;
2868 		}
2869 	}
2870 
2871 	mutex_exit(&sd_scsi_target_lun_mutex);
2872 
2873 	if (cp == NULL) {
2874 		return (-1);
2875 	}
2876 
2877 	return (cp->nlun[target]);
2878 }
2879 
2880 
2881 /*
2882  *    Function: sd_scsi_update_lun_on_target
2883  *
2884  * Description: This routine is used to update the attached lun chain when a
2885  *		lun is attached or detached on a target.
2886  *
2887  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
2888  *                        controller device.
2889  *              target  - The target ID on the controller's SCSI bus.
2890  *		flag	- Indicate the lun is attached or detached.
2891  *
2892  *     Context: Kernel thread context
2893  */
2894 
2895 static void
2896 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
2897 {
2898 	struct sd_scsi_hba_tgt_lun	*cp;
2899 
2900 	mutex_enter(&sd_scsi_target_lun_mutex);
2901 
2902 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2903 		if (cp->pdip == dip) {
2904 			break;
2905 		}
2906 	}
2907 
2908 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
2909 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
2910 		    KM_SLEEP);
2911 		cp->pdip = dip;
2912 		cp->next = sd_scsi_target_lun_head;
2913 		sd_scsi_target_lun_head = cp;
2914 	}
2915 
2916 	mutex_exit(&sd_scsi_target_lun_mutex);
2917 
2918 	if (cp != NULL) {
2919 		if (flag == SD_SCSI_LUN_ATTACH) {
2920 			cp->nlun[target] ++;
2921 		} else {
2922 			cp->nlun[target] --;
2923 		}
2924 	}
2925 }
2926 
2927 
2928 /*
2929  *    Function: sd_spin_up_unit
2930  *
2931  * Description: Issues the following commands to spin-up the device:
2932  *		START STOP UNIT, and INQUIRY.
2933  *
2934  *   Arguments: un - driver soft state (unit) structure
2935  *
2936  * Return Code: 0 - success
2937  *		EIO - failure
2938  *		EACCES - reservation conflict
2939  *
2940  *     Context: Kernel thread context
2941  */
2942 
2943 static int
2944 sd_spin_up_unit(struct sd_lun *un)
2945 {
2946 	size_t	resid		= 0;
2947 	int	has_conflict	= FALSE;
2948 	uchar_t *bufaddr;
2949 
2950 	ASSERT(un != NULL);
2951 
2952 	/*
2953 	 * Send a throwaway START UNIT command.
2954 	 *
2955 	 * If we fail on this, we don't care presently what precisely
2956 	 * is wrong.  EMC's arrays will also fail this with a check
2957 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
2958 	 * we don't want to fail the attach because it may become
2959 	 * "active" later.
2960 	 */
2961 	if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START, SD_PATH_DIRECT)
2962 	    == EACCES)
2963 		has_conflict = TRUE;
2964 
2965 	/*
2966 	 * Send another INQUIRY command to the target. This is necessary for
2967 	 * non-removable media direct access devices because their INQUIRY data
2968 	 * may not be fully qualified until they are spun up (perhaps via the
2969 	 * START command above).  Note: This seems to be needed for some
2970 	 * legacy devices only.) The INQUIRY command should succeed even if a
2971 	 * Reservation Conflict is present.
2972 	 */
2973 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
2974 	if (sd_send_scsi_INQUIRY(un, bufaddr, SUN_INQSIZE, 0, 0, &resid) != 0) {
2975 		kmem_free(bufaddr, SUN_INQSIZE);
2976 		return (EIO);
2977 	}
2978 
2979 	/*
2980 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
2981 	 * Note that this routine does not return a failure here even if the
2982 	 * INQUIRY command did not return any data.  This is a legacy behavior.
2983 	 */
2984 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
2985 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
2986 	}
2987 
2988 	kmem_free(bufaddr, SUN_INQSIZE);
2989 
2990 	/* If we hit a reservation conflict above, tell the caller. */
2991 	if (has_conflict == TRUE) {
2992 		return (EACCES);
2993 	}
2994 
2995 	return (0);
2996 }
2997 
2998 #ifdef _LP64
2999 /*
3000  *    Function: sd_enable_descr_sense
3001  *
3002  * Description: This routine attempts to select descriptor sense format
3003  *		using the Control mode page.  Devices that support 64 bit
3004  *		LBAs (for >2TB luns) should also implement descriptor
3005  *		sense data so we will call this function whenever we see
3006  *		a lun larger than 2TB.  If for some reason the device
3007  *		supports 64 bit LBAs but doesn't support descriptor sense
3008  *		presumably the mode select will fail.  Everything will
3009  *		continue to work normally except that we will not get
3010  *		complete sense data for commands that fail with an LBA
3011  *		larger than 32 bits.
3012  *
3013  *   Arguments: un - driver soft state (unit) structure
3014  *
3015  *     Context: Kernel thread context only
3016  */
3017 
3018 static void
3019 sd_enable_descr_sense(struct sd_lun *un)
3020 {
3021 	uchar_t			*header;
3022 	struct mode_control_scsi3 *ctrl_bufp;
3023 	size_t			buflen;
3024 	size_t			bd_len;
3025 
3026 	/*
3027 	 * Read MODE SENSE page 0xA, Control Mode Page
3028 	 */
3029 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3030 	    sizeof (struct mode_control_scsi3);
3031 	header = kmem_zalloc(buflen, KM_SLEEP);
3032 	if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
3033 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT) != 0) {
3034 		SD_ERROR(SD_LOG_COMMON, un,
3035 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3036 		goto eds_exit;
3037 	}
3038 
3039 	/*
3040 	 * Determine size of Block Descriptors in order to locate
3041 	 * the mode page data. ATAPI devices return 0, SCSI devices
3042 	 * should return MODE_BLK_DESC_LENGTH.
3043 	 */
3044 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3045 
3046 	/* Clear the mode data length field for MODE SELECT */
3047 	((struct mode_header *)header)->length = 0;
3048 
3049 	ctrl_bufp = (struct mode_control_scsi3 *)
3050 	    (header + MODE_HEADER_LENGTH + bd_len);
3051 
3052 	/*
3053 	 * If the page length is smaller than the expected value,
3054 	 * the target device doesn't support D_SENSE. Bail out here.
3055 	 */
3056 	if (ctrl_bufp->mode_page.length <
3057 	    sizeof (struct mode_control_scsi3) - 2) {
3058 		SD_ERROR(SD_LOG_COMMON, un,
3059 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3060 		goto eds_exit;
3061 	}
3062 
3063 	/*
3064 	 * Clear PS bit for MODE SELECT
3065 	 */
3066 	ctrl_bufp->mode_page.ps = 0;
3067 
3068 	/*
3069 	 * Set D_SENSE to enable descriptor sense format.
3070 	 */
3071 	ctrl_bufp->d_sense = 1;
3072 
3073 	/*
3074 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3075 	 */
3076 	if (sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
3077 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT) != 0) {
3078 		SD_INFO(SD_LOG_COMMON, un,
3079 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3080 		goto eds_exit;
3081 	}
3082 
3083 eds_exit:
3084 	kmem_free(header, buflen);
3085 }
3086 
3087 /*
3088  *    Function: sd_reenable_dsense_task
3089  *
3090  * Description: Re-enable descriptor sense after device or bus reset
3091  *
3092  *     Context: Executes in a taskq() thread context
3093  */
3094 static void
3095 sd_reenable_dsense_task(void *arg)
3096 {
3097 	struct	sd_lun	*un = arg;
3098 
3099 	ASSERT(un != NULL);
3100 	sd_enable_descr_sense(un);
3101 }
3102 #endif /* _LP64 */
3103 
3104 /*
3105  *    Function: sd_set_mmc_caps
3106  *
3107  * Description: This routine determines if the device is MMC compliant and if
3108  *		the device supports CDDA via a mode sense of the CDVD
3109  *		capabilities mode page. Also checks if the device is a
3110  *		dvdram writable device.
3111  *
3112  *   Arguments: un - driver soft state (unit) structure
3113  *
3114  *     Context: Kernel thread context only
3115  */
3116 
3117 static void
3118 sd_set_mmc_caps(struct sd_lun *un)
3119 {
3120 	struct mode_header_grp2		*sense_mhp;
3121 	uchar_t				*sense_page;
3122 	caddr_t				buf;
3123 	int				bd_len;
3124 	int				status;
3125 	struct uscsi_cmd		com;
3126 	int				rtn;
3127 	uchar_t				*out_data_rw, *out_data_hd;
3128 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3129 
3130 	ASSERT(un != NULL);
3131 
3132 	/*
3133 	 * The flags which will be set in this function are - mmc compliant,
3134 	 * dvdram writable device, cdda support. Initialize them to FALSE
3135 	 * and if a capability is detected - it will be set to TRUE.
3136 	 */
3137 	un->un_f_mmc_cap = FALSE;
3138 	un->un_f_dvdram_writable_device = FALSE;
3139 	un->un_f_cfg_cdda = FALSE;
3140 
3141 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3142 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
3143 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3144 
3145 	if (status != 0) {
3146 		/* command failed; just return */
3147 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3148 		return;
3149 	}
3150 	/*
3151 	 * If the mode sense request for the CDROM CAPABILITIES
3152 	 * page (0x2A) succeeds the device is assumed to be MMC.
3153 	 */
3154 	un->un_f_mmc_cap = TRUE;
3155 
3156 	/* Get to the page data */
3157 	sense_mhp = (struct mode_header_grp2 *)buf;
3158 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3159 	    sense_mhp->bdesc_length_lo;
3160 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3161 		/*
3162 		 * We did not get back the expected block descriptor
3163 		 * length so we cannot determine if the device supports
3164 		 * CDDA. However, we still indicate the device is MMC
3165 		 * according to the successful response to the page
3166 		 * 0x2A mode sense request.
3167 		 */
3168 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3169 		    "sd_set_mmc_caps: Mode Sense returned "
3170 		    "invalid block descriptor length\n");
3171 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3172 		return;
3173 	}
3174 
3175 	/* See if read CDDA is supported */
3176 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3177 	    bd_len);
3178 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3179 
3180 	/* See if writing DVD RAM is supported. */
3181 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3182 	if (un->un_f_dvdram_writable_device == TRUE) {
3183 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3184 		return;
3185 	}
3186 
3187 	/*
3188 	 * If the device presents DVD or CD capabilities in the mode
3189 	 * page, we can return here since a RRD will not have
3190 	 * these capabilities.
3191 	 */
3192 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3193 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3194 		return;
3195 	}
3196 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3197 
3198 	/*
3199 	 * If un->un_f_dvdram_writable_device is still FALSE,
3200 	 * check for a Removable Rigid Disk (RRD).  A RRD
3201 	 * device is identified by the features RANDOM_WRITABLE and
3202 	 * HARDWARE_DEFECT_MANAGEMENT.
3203 	 */
3204 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3205 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3206 
3207 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3208 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3209 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3210 	if (rtn != 0) {
3211 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3212 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3213 		return;
3214 	}
3215 
3216 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3217 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3218 
3219 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3220 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3221 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3222 	if (rtn == 0) {
3223 		/*
3224 		 * We have good information, check for random writable
3225 		 * and hardware defect features.
3226 		 */
3227 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3228 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3229 			un->un_f_dvdram_writable_device = TRUE;
3230 		}
3231 	}
3232 
3233 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3234 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3235 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3236 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3237 }
3238 
3239 /*
3240  *    Function: sd_check_for_writable_cd
3241  *
3242  * Description: This routine determines if the media in the device is
3243  *		writable or not. It uses the get configuration command (0x46)
3244  *		to determine if the media is writable
3245  *
3246  *   Arguments: un - driver soft state (unit) structure
3247  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3248  *                           chain and the normal command waitq, or
3249  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3250  *                           "direct" chain and bypass the normal command
3251  *                           waitq.
3252  *
3253  *     Context: Never called at interrupt context.
3254  */
3255 
3256 static void
3257 sd_check_for_writable_cd(struct sd_lun *un, int path_flag)
3258 {
3259 	struct uscsi_cmd		com;
3260 	uchar_t				*out_data;
3261 	uchar_t				*rqbuf;
3262 	int				rtn;
3263 	uchar_t				*out_data_rw, *out_data_hd;
3264 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3265 	struct mode_header_grp2		*sense_mhp;
3266 	uchar_t				*sense_page;
3267 	caddr_t				buf;
3268 	int				bd_len;
3269 	int				status;
3270 
3271 	ASSERT(un != NULL);
3272 	ASSERT(mutex_owned(SD_MUTEX(un)));
3273 
3274 	/*
3275 	 * Initialize the writable media to false, if configuration info.
3276 	 * tells us otherwise then only we will set it.
3277 	 */
3278 	un->un_f_mmc_writable_media = FALSE;
3279 	mutex_exit(SD_MUTEX(un));
3280 
3281 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3282 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3283 
3284 	rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf, SENSE_LENGTH,
3285 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3286 
3287 	mutex_enter(SD_MUTEX(un));
3288 	if (rtn == 0) {
3289 		/*
3290 		 * We have good information, check for writable DVD.
3291 		 */
3292 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3293 			un->un_f_mmc_writable_media = TRUE;
3294 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3295 			kmem_free(rqbuf, SENSE_LENGTH);
3296 			return;
3297 		}
3298 	}
3299 
3300 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3301 	kmem_free(rqbuf, SENSE_LENGTH);
3302 
3303 	/*
3304 	 * Determine if this is a RRD type device.
3305 	 */
3306 	mutex_exit(SD_MUTEX(un));
3307 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3308 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
3309 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3310 	mutex_enter(SD_MUTEX(un));
3311 	if (status != 0) {
3312 		/* command failed; just return */
3313 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3314 		return;
3315 	}
3316 
3317 	/* Get to the page data */
3318 	sense_mhp = (struct mode_header_grp2 *)buf;
3319 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3320 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3321 		/*
3322 		 * We did not get back the expected block descriptor length so
3323 		 * we cannot check the mode page.
3324 		 */
3325 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3326 		    "sd_check_for_writable_cd: Mode Sense returned "
3327 		    "invalid block descriptor length\n");
3328 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3329 		return;
3330 	}
3331 
3332 	/*
3333 	 * If the device presents DVD or CD capabilities in the mode
3334 	 * page, we can return here since a RRD device will not have
3335 	 * these capabilities.
3336 	 */
3337 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3338 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3339 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3340 		return;
3341 	}
3342 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3343 
3344 	/*
3345 	 * If un->un_f_mmc_writable_media is still FALSE,
3346 	 * check for RRD type media.  A RRD device is identified
3347 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3348 	 */
3349 	mutex_exit(SD_MUTEX(un));
3350 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3351 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3352 
3353 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3354 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3355 	    RANDOM_WRITABLE, path_flag);
3356 	if (rtn != 0) {
3357 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3358 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3359 		mutex_enter(SD_MUTEX(un));
3360 		return;
3361 	}
3362 
3363 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3364 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3365 
3366 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3367 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3368 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3369 	mutex_enter(SD_MUTEX(un));
3370 	if (rtn == 0) {
3371 		/*
3372 		 * We have good information, check for random writable
3373 		 * and hardware defect features as current.
3374 		 */
3375 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3376 		    (out_data_rw[10] & 0x1) &&
3377 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3378 		    (out_data_hd[10] & 0x1)) {
3379 			un->un_f_mmc_writable_media = TRUE;
3380 		}
3381 	}
3382 
3383 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3384 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3385 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3386 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3387 }
3388 
3389 /*
3390  *    Function: sd_read_unit_properties
3391  *
3392  * Description: The following implements a property lookup mechanism.
3393  *		Properties for particular disks (keyed on vendor, model
3394  *		and rev numbers) are sought in the sd.conf file via
3395  *		sd_process_sdconf_file(), and if not found there, are
3396  *		looked for in a list hardcoded in this driver via
3397  *		sd_process_sdconf_table() Once located the properties
3398  *		are used to update the driver unit structure.
3399  *
3400  *   Arguments: un - driver soft state (unit) structure
3401  */
3402 
3403 static void
3404 sd_read_unit_properties(struct sd_lun *un)
3405 {
3406 	/*
3407 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3408 	 * the "sd-config-list" property (from the sd.conf file) or if
3409 	 * there was not a match for the inquiry vid/pid. If this event
3410 	 * occurs the static driver configuration table is searched for
3411 	 * a match.
3412 	 */
3413 	ASSERT(un != NULL);
3414 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3415 		sd_process_sdconf_table(un);
3416 	}
3417 
3418 	/* check for LSI device */
3419 	sd_is_lsi(un);
3420 
3421 
3422 }
3423 
3424 
3425 /*
3426  *    Function: sd_process_sdconf_file
3427  *
3428  * Description: Use ddi_getlongprop to obtain the properties from the
3429  *		driver's config file (ie, sd.conf) and update the driver
3430  *		soft state structure accordingly.
3431  *
3432  *   Arguments: un - driver soft state (unit) structure
3433  *
3434  * Return Code: SD_SUCCESS - The properties were successfully set according
3435  *			     to the driver configuration file.
3436  *		SD_FAILURE - The driver config list was not obtained or
3437  *			     there was no vid/pid match. This indicates that
3438  *			     the static config table should be used.
3439  *
3440  * The config file has a property, "sd-config-list", which consists of
3441  * one or more duplets as follows:
3442  *
3443  *  sd-config-list=
3444  *	<duplet>,
3445  *	[<duplet>,]
3446  *	[<duplet>];
3447  *
3448  * The structure of each duplet is as follows:
3449  *
3450  *  <duplet>:= <vid+pid>,<data-property-name_list>
3451  *
3452  * The first entry of the duplet is the device ID string (the concatenated
3453  * vid & pid; not to be confused with a device_id).  This is defined in
3454  * the same way as in the sd_disk_table.
3455  *
3456  * The second part of the duplet is a string that identifies a
3457  * data-property-name-list. The data-property-name-list is defined as
3458  * follows:
3459  *
3460  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3461  *
3462  * The syntax of <data-property-name> depends on the <version> field.
3463  *
3464  * If version = SD_CONF_VERSION_1 we have the following syntax:
3465  *
3466  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3467  *
3468  * where the prop0 value will be used to set prop0 if bit0 set in the
3469  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3470  *
3471  */
3472 
3473 static int
3474 sd_process_sdconf_file(struct sd_lun *un)
3475 {
3476 	char	*config_list = NULL;
3477 	int	config_list_len;
3478 	int	len;
3479 	int	dupletlen = 0;
3480 	char	*vidptr;
3481 	int	vidlen;
3482 	char	*dnlist_ptr;
3483 	char	*dataname_ptr;
3484 	int	dnlist_len;
3485 	int	dataname_len;
3486 	int	*data_list;
3487 	int	data_list_len;
3488 	int	rval = SD_FAILURE;
3489 	int	i;
3490 
3491 	ASSERT(un != NULL);
3492 
3493 	/* Obtain the configuration list associated with the .conf file */
3494 	if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), DDI_PROP_DONTPASS,
3495 	    sd_config_list, (caddr_t)&config_list, &config_list_len)
3496 	    != DDI_PROP_SUCCESS) {
3497 		return (SD_FAILURE);
3498 	}
3499 
3500 	/*
3501 	 * Compare vids in each duplet to the inquiry vid - if a match is
3502 	 * made, get the data value and update the soft state structure
3503 	 * accordingly.
3504 	 *
3505 	 * Note: This algorithm is complex and difficult to maintain. It should
3506 	 * be replaced with a more robust implementation.
3507 	 */
3508 	for (len = config_list_len, vidptr = config_list; len > 0;
3509 	    vidptr += dupletlen, len -= dupletlen) {
3510 		/*
3511 		 * Note: The assumption here is that each vid entry is on
3512 		 * a unique line from its associated duplet.
3513 		 */
3514 		vidlen = dupletlen = (int)strlen(vidptr);
3515 		if ((vidlen == 0) ||
3516 		    (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS)) {
3517 			dupletlen++;
3518 			continue;
3519 		}
3520 
3521 		/*
3522 		 * dnlist contains 1 or more blank separated
3523 		 * data-property-name entries
3524 		 */
3525 		dnlist_ptr = vidptr + vidlen + 1;
3526 		dnlist_len = (int)strlen(dnlist_ptr);
3527 		dupletlen += dnlist_len + 2;
3528 
3529 		/*
3530 		 * Set a pointer for the first data-property-name
3531 		 * entry in the list
3532 		 */
3533 		dataname_ptr = dnlist_ptr;
3534 		dataname_len = 0;
3535 
3536 		/*
3537 		 * Loop through all data-property-name entries in the
3538 		 * data-property-name-list setting the properties for each.
3539 		 */
3540 		while (dataname_len < dnlist_len) {
3541 			int version;
3542 
3543 			/*
3544 			 * Determine the length of the current
3545 			 * data-property-name entry by indexing until a
3546 			 * blank or NULL is encountered. When the space is
3547 			 * encountered reset it to a NULL for compliance
3548 			 * with ddi_getlongprop().
3549 			 */
3550 			for (i = 0; ((dataname_ptr[i] != ' ') &&
3551 			    (dataname_ptr[i] != '\0')); i++) {
3552 				;
3553 			}
3554 
3555 			dataname_len += i;
3556 			/* If not null terminated, Make it so */
3557 			if (dataname_ptr[i] == ' ') {
3558 				dataname_ptr[i] = '\0';
3559 			}
3560 			dataname_len++;
3561 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3562 			    "sd_process_sdconf_file: disk:%s, data:%s\n",
3563 			    vidptr, dataname_ptr);
3564 
3565 			/* Get the data list */
3566 			if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), 0,
3567 			    dataname_ptr, (caddr_t)&data_list, &data_list_len)
3568 			    != DDI_PROP_SUCCESS) {
3569 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3570 				    "sd_process_sdconf_file: data property (%s)"
3571 				    " has no value\n", dataname_ptr);
3572 				dataname_ptr = dnlist_ptr + dataname_len;
3573 				continue;
3574 			}
3575 
3576 			version = data_list[0];
3577 
3578 			if (version == SD_CONF_VERSION_1) {
3579 				sd_tunables values;
3580 
3581 				/* Set the properties */
3582 				if (sd_chk_vers1_data(un, data_list[1],
3583 				    &data_list[2], data_list_len, dataname_ptr)
3584 				    == SD_SUCCESS) {
3585 					sd_get_tunables_from_conf(un,
3586 					    data_list[1], &data_list[2],
3587 					    &values);
3588 					sd_set_vers1_properties(un,
3589 					    data_list[1], &values);
3590 					rval = SD_SUCCESS;
3591 				} else {
3592 					rval = SD_FAILURE;
3593 				}
3594 			} else {
3595 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3596 				    "data property %s version 0x%x is invalid.",
3597 				    dataname_ptr, version);
3598 				rval = SD_FAILURE;
3599 			}
3600 			kmem_free(data_list, data_list_len);
3601 			dataname_ptr = dnlist_ptr + dataname_len;
3602 		}
3603 	}
3604 
3605 	/* free up the memory allocated by ddi_getlongprop */
3606 	if (config_list) {
3607 		kmem_free(config_list, config_list_len);
3608 	}
3609 
3610 	return (rval);
3611 }
3612 
3613 /*
3614  *    Function: sd_get_tunables_from_conf()
3615  *
3616  *
3617  *    This function reads the data list from the sd.conf file and pulls
3618  *    the values that can have numeric values as arguments and places
3619  *    the values in the appropriate sd_tunables member.
3620  *    Since the order of the data list members varies across platforms
3621  *    This function reads them from the data list in a platform specific
3622  *    order and places them into the correct sd_tunable member that is
3623  *    consistent across all platforms.
3624  */
3625 static void
3626 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
3627     sd_tunables *values)
3628 {
3629 	int i;
3630 	int mask;
3631 
3632 	bzero(values, sizeof (sd_tunables));
3633 
3634 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3635 
3636 		mask = 1 << i;
3637 		if (mask > flags) {
3638 			break;
3639 		}
3640 
3641 		switch (mask & flags) {
3642 		case 0:	/* This mask bit not set in flags */
3643 			continue;
3644 		case SD_CONF_BSET_THROTTLE:
3645 			values->sdt_throttle = data_list[i];
3646 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3647 			    "sd_get_tunables_from_conf: throttle = %d\n",
3648 			    values->sdt_throttle);
3649 			break;
3650 		case SD_CONF_BSET_CTYPE:
3651 			values->sdt_ctype = data_list[i];
3652 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3653 			    "sd_get_tunables_from_conf: ctype = %d\n",
3654 			    values->sdt_ctype);
3655 			break;
3656 		case SD_CONF_BSET_NRR_COUNT:
3657 			values->sdt_not_rdy_retries = data_list[i];
3658 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3659 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
3660 			    values->sdt_not_rdy_retries);
3661 			break;
3662 		case SD_CONF_BSET_BSY_RETRY_COUNT:
3663 			values->sdt_busy_retries = data_list[i];
3664 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3665 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
3666 			    values->sdt_busy_retries);
3667 			break;
3668 		case SD_CONF_BSET_RST_RETRIES:
3669 			values->sdt_reset_retries = data_list[i];
3670 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3671 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
3672 			    values->sdt_reset_retries);
3673 			break;
3674 		case SD_CONF_BSET_RSV_REL_TIME:
3675 			values->sdt_reserv_rel_time = data_list[i];
3676 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3677 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
3678 			    values->sdt_reserv_rel_time);
3679 			break;
3680 		case SD_CONF_BSET_MIN_THROTTLE:
3681 			values->sdt_min_throttle = data_list[i];
3682 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3683 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
3684 			    values->sdt_min_throttle);
3685 			break;
3686 		case SD_CONF_BSET_DISKSORT_DISABLED:
3687 			values->sdt_disk_sort_dis = data_list[i];
3688 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3689 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
3690 			    values->sdt_disk_sort_dis);
3691 			break;
3692 		case SD_CONF_BSET_LUN_RESET_ENABLED:
3693 			values->sdt_lun_reset_enable = data_list[i];
3694 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3695 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
3696 			    "\n", values->sdt_lun_reset_enable);
3697 			break;
3698 		case SD_CONF_BSET_CACHE_IS_NV:
3699 			values->sdt_suppress_cache_flush = data_list[i];
3700 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3701 			    "sd_get_tunables_from_conf: \
3702 			    suppress_cache_flush = %d"
3703 			    "\n", values->sdt_suppress_cache_flush);
3704 			break;
3705 		}
3706 	}
3707 }
3708 
3709 /*
3710  *    Function: sd_process_sdconf_table
3711  *
3712  * Description: Search the static configuration table for a match on the
3713  *		inquiry vid/pid and update the driver soft state structure
3714  *		according to the table property values for the device.
3715  *
3716  *		The form of a configuration table entry is:
3717  *		  <vid+pid>,<flags>,<property-data>
3718  *		  "SEAGATE ST42400N",1,0x40000,
3719  *		  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1;
3720  *
3721  *   Arguments: un - driver soft state (unit) structure
3722  */
3723 
3724 static void
3725 sd_process_sdconf_table(struct sd_lun *un)
3726 {
3727 	char	*id = NULL;
3728 	int	table_index;
3729 	int	idlen;
3730 
3731 	ASSERT(un != NULL);
3732 	for (table_index = 0; table_index < sd_disk_table_size;
3733 	    table_index++) {
3734 		id = sd_disk_table[table_index].device_id;
3735 		idlen = strlen(id);
3736 		if (idlen == 0) {
3737 			continue;
3738 		}
3739 
3740 		/*
3741 		 * The static configuration table currently does not
3742 		 * implement version 10 properties. Additionally,
3743 		 * multiple data-property-name entries are not
3744 		 * implemented in the static configuration table.
3745 		 */
3746 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
3747 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3748 			    "sd_process_sdconf_table: disk %s\n", id);
3749 			sd_set_vers1_properties(un,
3750 			    sd_disk_table[table_index].flags,
3751 			    sd_disk_table[table_index].properties);
3752 			break;
3753 		}
3754 	}
3755 }
3756 
3757 
3758 /*
3759  *    Function: sd_sdconf_id_match
3760  *
3761  * Description: This local function implements a case sensitive vid/pid
3762  *		comparison as well as the boundary cases of wild card and
3763  *		multiple blanks.
3764  *
3765  *		Note: An implicit assumption made here is that the scsi
3766  *		inquiry structure will always keep the vid, pid and
3767  *		revision strings in consecutive sequence, so they can be
3768  *		read as a single string. If this assumption is not the
3769  *		case, a separate string, to be used for the check, needs
3770  *		to be built with these strings concatenated.
3771  *
3772  *   Arguments: un - driver soft state (unit) structure
3773  *		id - table or config file vid/pid
3774  *		idlen  - length of the vid/pid (bytes)
3775  *
3776  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3777  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3778  */
3779 
3780 static int
3781 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
3782 {
3783 	struct scsi_inquiry	*sd_inq;
3784 	int 			rval = SD_SUCCESS;
3785 
3786 	ASSERT(un != NULL);
3787 	sd_inq = un->un_sd->sd_inq;
3788 	ASSERT(id != NULL);
3789 
3790 	/*
3791 	 * We use the inq_vid as a pointer to a buffer containing the
3792 	 * vid and pid and use the entire vid/pid length of the table
3793 	 * entry for the comparison. This works because the inq_pid
3794 	 * data member follows inq_vid in the scsi_inquiry structure.
3795 	 */
3796 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
3797 		/*
3798 		 * The user id string is compared to the inquiry vid/pid
3799 		 * using a case insensitive comparison and ignoring
3800 		 * multiple spaces.
3801 		 */
3802 		rval = sd_blank_cmp(un, id, idlen);
3803 		if (rval != SD_SUCCESS) {
3804 			/*
3805 			 * User id strings that start and end with a "*"
3806 			 * are a special case. These do not have a
3807 			 * specific vendor, and the product string can
3808 			 * appear anywhere in the 16 byte PID portion of
3809 			 * the inquiry data. This is a simple strstr()
3810 			 * type search for the user id in the inquiry data.
3811 			 */
3812 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
3813 				char	*pidptr = &id[1];
3814 				int	i;
3815 				int	j;
3816 				int	pidstrlen = idlen - 2;
3817 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
3818 				    pidstrlen;
3819 
3820 				if (j < 0) {
3821 					return (SD_FAILURE);
3822 				}
3823 				for (i = 0; i < j; i++) {
3824 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
3825 					    pidptr, pidstrlen) == 0) {
3826 						rval = SD_SUCCESS;
3827 						break;
3828 					}
3829 				}
3830 			}
3831 		}
3832 	}
3833 	return (rval);
3834 }
3835 
3836 
3837 /*
3838  *    Function: sd_blank_cmp
3839  *
3840  * Description: If the id string starts and ends with a space, treat
3841  *		multiple consecutive spaces as equivalent to a single
3842  *		space. For example, this causes a sd_disk_table entry
3843  *		of " NEC CDROM " to match a device's id string of
3844  *		"NEC       CDROM".
3845  *
3846  *		Note: The success exit condition for this routine is if
3847  *		the pointer to the table entry is '\0' and the cnt of
3848  *		the inquiry length is zero. This will happen if the inquiry
3849  *		string returned by the device is padded with spaces to be
3850  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
3851  *		SCSI spec states that the inquiry string is to be padded with
3852  *		spaces.
3853  *
3854  *   Arguments: un - driver soft state (unit) structure
3855  *		id - table or config file vid/pid
3856  *		idlen  - length of the vid/pid (bytes)
3857  *
3858  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3859  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3860  */
3861 
3862 static int
3863 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
3864 {
3865 	char		*p1;
3866 	char		*p2;
3867 	int		cnt;
3868 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
3869 	    sizeof (SD_INQUIRY(un)->inq_pid);
3870 
3871 	ASSERT(un != NULL);
3872 	p2 = un->un_sd->sd_inq->inq_vid;
3873 	ASSERT(id != NULL);
3874 	p1 = id;
3875 
3876 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
3877 		/*
3878 		 * Note: string p1 is terminated by a NUL but string p2
3879 		 * isn't.  The end of p2 is determined by cnt.
3880 		 */
3881 		for (;;) {
3882 			/* skip over any extra blanks in both strings */
3883 			while ((*p1 != '\0') && (*p1 == ' ')) {
3884 				p1++;
3885 			}
3886 			while ((cnt != 0) && (*p2 == ' ')) {
3887 				p2++;
3888 				cnt--;
3889 			}
3890 
3891 			/* compare the two strings */
3892 			if ((cnt == 0) ||
3893 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
3894 				break;
3895 			}
3896 			while ((cnt > 0) &&
3897 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
3898 				p1++;
3899 				p2++;
3900 				cnt--;
3901 			}
3902 		}
3903 	}
3904 
3905 	/* return SD_SUCCESS if both strings match */
3906 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
3907 }
3908 
3909 
3910 /*
3911  *    Function: sd_chk_vers1_data
3912  *
3913  * Description: Verify the version 1 device properties provided by the
3914  *		user via the configuration file
3915  *
3916  *   Arguments: un	     - driver soft state (unit) structure
3917  *		flags	     - integer mask indicating properties to be set
3918  *		prop_list    - integer list of property values
3919  *		list_len     - length of user provided data
3920  *
3921  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
3922  *		SD_FAILURE - Indicates the user provided data is invalid
3923  */
3924 
3925 static int
3926 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
3927     int list_len, char *dataname_ptr)
3928 {
3929 	int i;
3930 	int mask = 1;
3931 	int index = 0;
3932 
3933 	ASSERT(un != NULL);
3934 
3935 	/* Check for a NULL property name and list */
3936 	if (dataname_ptr == NULL) {
3937 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3938 		    "sd_chk_vers1_data: NULL data property name.");
3939 		return (SD_FAILURE);
3940 	}
3941 	if (prop_list == NULL) {
3942 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3943 		    "sd_chk_vers1_data: %s NULL data property list.",
3944 		    dataname_ptr);
3945 		return (SD_FAILURE);
3946 	}
3947 
3948 	/* Display a warning if undefined bits are set in the flags */
3949 	if (flags & ~SD_CONF_BIT_MASK) {
3950 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3951 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
3952 		    "Properties not set.",
3953 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
3954 		return (SD_FAILURE);
3955 	}
3956 
3957 	/*
3958 	 * Verify the length of the list by identifying the highest bit set
3959 	 * in the flags and validating that the property list has a length
3960 	 * up to the index of this bit.
3961 	 */
3962 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3963 		if (flags & mask) {
3964 			index++;
3965 		}
3966 		mask = 1 << i;
3967 	}
3968 	if ((list_len / sizeof (int)) < (index + 2)) {
3969 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3970 		    "sd_chk_vers1_data: "
3971 		    "Data property list %s size is incorrect. "
3972 		    "Properties not set.", dataname_ptr);
3973 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
3974 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
3975 		return (SD_FAILURE);
3976 	}
3977 	return (SD_SUCCESS);
3978 }
3979 
3980 
3981 /*
3982  *    Function: sd_set_vers1_properties
3983  *
3984  * Description: Set version 1 device properties based on a property list
3985  *		retrieved from the driver configuration file or static
3986  *		configuration table. Version 1 properties have the format:
3987  *
3988  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3989  *
3990  *		where the prop0 value will be used to set prop0 if bit0
3991  *		is set in the flags
3992  *
3993  *   Arguments: un	     - driver soft state (unit) structure
3994  *		flags	     - integer mask indicating properties to be set
3995  *		prop_list    - integer list of property values
3996  */
3997 
3998 static void
3999 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
4000 {
4001 	ASSERT(un != NULL);
4002 
4003 	/*
4004 	 * Set the flag to indicate cache is to be disabled. An attempt
4005 	 * to disable the cache via sd_cache_control() will be made
4006 	 * later during attach once the basic initialization is complete.
4007 	 */
4008 	if (flags & SD_CONF_BSET_NOCACHE) {
4009 		un->un_f_opt_disable_cache = TRUE;
4010 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4011 		    "sd_set_vers1_properties: caching disabled flag set\n");
4012 	}
4013 
4014 	/* CD-specific configuration parameters */
4015 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4016 		un->un_f_cfg_playmsf_bcd = TRUE;
4017 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4018 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4019 	}
4020 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4021 		un->un_f_cfg_readsub_bcd = TRUE;
4022 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4023 		    "sd_set_vers1_properties: readsub_bcd set\n");
4024 	}
4025 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4026 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4027 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4028 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4029 	}
4030 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4031 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4032 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4033 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4034 	}
4035 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4036 		un->un_f_cfg_no_read_header = TRUE;
4037 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4038 		    "sd_set_vers1_properties: no_read_header set\n");
4039 	}
4040 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4041 		un->un_f_cfg_read_cd_xd4 = TRUE;
4042 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4043 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4044 	}
4045 
4046 	/* Support for devices which do not have valid/unique serial numbers */
4047 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4048 		un->un_f_opt_fab_devid = TRUE;
4049 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4050 		    "sd_set_vers1_properties: fab_devid bit set\n");
4051 	}
4052 
4053 	/* Support for user throttle configuration */
4054 	if (flags & SD_CONF_BSET_THROTTLE) {
4055 		ASSERT(prop_list != NULL);
4056 		un->un_saved_throttle = un->un_throttle =
4057 		    prop_list->sdt_throttle;
4058 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4059 		    "sd_set_vers1_properties: throttle set to %d\n",
4060 		    prop_list->sdt_throttle);
4061 	}
4062 
4063 	/* Set the per disk retry count according to the conf file or table. */
4064 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4065 		ASSERT(prop_list != NULL);
4066 		if (prop_list->sdt_not_rdy_retries) {
4067 			un->un_notready_retry_count =
4068 			    prop_list->sdt_not_rdy_retries;
4069 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4070 			    "sd_set_vers1_properties: not ready retry count"
4071 			    " set to %d\n", un->un_notready_retry_count);
4072 		}
4073 	}
4074 
4075 	/* The controller type is reported for generic disk driver ioctls */
4076 	if (flags & SD_CONF_BSET_CTYPE) {
4077 		ASSERT(prop_list != NULL);
4078 		switch (prop_list->sdt_ctype) {
4079 		case CTYPE_CDROM:
4080 			un->un_ctype = prop_list->sdt_ctype;
4081 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4082 			    "sd_set_vers1_properties: ctype set to "
4083 			    "CTYPE_CDROM\n");
4084 			break;
4085 		case CTYPE_CCS:
4086 			un->un_ctype = prop_list->sdt_ctype;
4087 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4088 			    "sd_set_vers1_properties: ctype set to "
4089 			    "CTYPE_CCS\n");
4090 			break;
4091 		case CTYPE_ROD:		/* RW optical */
4092 			un->un_ctype = prop_list->sdt_ctype;
4093 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4094 			    "sd_set_vers1_properties: ctype set to "
4095 			    "CTYPE_ROD\n");
4096 			break;
4097 		default:
4098 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4099 			    "sd_set_vers1_properties: Could not set "
4100 			    "invalid ctype value (%d)",
4101 			    prop_list->sdt_ctype);
4102 		}
4103 	}
4104 
4105 	/* Purple failover timeout */
4106 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4107 		ASSERT(prop_list != NULL);
4108 		un->un_busy_retry_count =
4109 		    prop_list->sdt_busy_retries;
4110 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4111 		    "sd_set_vers1_properties: "
4112 		    "busy retry count set to %d\n",
4113 		    un->un_busy_retry_count);
4114 	}
4115 
4116 	/* Purple reset retry count */
4117 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4118 		ASSERT(prop_list != NULL);
4119 		un->un_reset_retry_count =
4120 		    prop_list->sdt_reset_retries;
4121 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4122 		    "sd_set_vers1_properties: "
4123 		    "reset retry count set to %d\n",
4124 		    un->un_reset_retry_count);
4125 	}
4126 
4127 	/* Purple reservation release timeout */
4128 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4129 		ASSERT(prop_list != NULL);
4130 		un->un_reserve_release_time =
4131 		    prop_list->sdt_reserv_rel_time;
4132 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4133 		    "sd_set_vers1_properties: "
4134 		    "reservation release timeout set to %d\n",
4135 		    un->un_reserve_release_time);
4136 	}
4137 
4138 	/*
4139 	 * Driver flag telling the driver to verify that no commands are pending
4140 	 * for a device before issuing a Test Unit Ready. This is a workaround
4141 	 * for a firmware bug in some Seagate eliteI drives.
4142 	 */
4143 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4144 		un->un_f_cfg_tur_check = TRUE;
4145 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4146 		    "sd_set_vers1_properties: tur queue check set\n");
4147 	}
4148 
4149 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4150 		un->un_min_throttle = prop_list->sdt_min_throttle;
4151 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4152 		    "sd_set_vers1_properties: min throttle set to %d\n",
4153 		    un->un_min_throttle);
4154 	}
4155 
4156 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4157 		un->un_f_disksort_disabled =
4158 		    (prop_list->sdt_disk_sort_dis != 0) ?
4159 		    TRUE : FALSE;
4160 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4161 		    "sd_set_vers1_properties: disksort disabled "
4162 		    "flag set to %d\n",
4163 		    prop_list->sdt_disk_sort_dis);
4164 	}
4165 
4166 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4167 		un->un_f_lun_reset_enabled =
4168 		    (prop_list->sdt_lun_reset_enable != 0) ?
4169 		    TRUE : FALSE;
4170 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4171 		    "sd_set_vers1_properties: lun reset enabled "
4172 		    "flag set to %d\n",
4173 		    prop_list->sdt_lun_reset_enable);
4174 	}
4175 
4176 	if (flags & SD_CONF_BSET_CACHE_IS_NV) {
4177 		un->un_f_suppress_cache_flush =
4178 		    (prop_list->sdt_suppress_cache_flush != 0) ?
4179 		    TRUE : FALSE;
4180 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4181 		    "sd_set_vers1_properties: suppress_cache_flush "
4182 		    "flag set to %d\n",
4183 		    prop_list->sdt_suppress_cache_flush);
4184 	}
4185 
4186 	/*
4187 	 * Validate the throttle values.
4188 	 * If any of the numbers are invalid, set everything to defaults.
4189 	 */
4190 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4191 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4192 	    (un->un_min_throttle > un->un_throttle)) {
4193 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4194 		un->un_min_throttle = sd_min_throttle;
4195 	}
4196 }
4197 
4198 /*
4199  *   Function: sd_is_lsi()
4200  *
4201  *   Description: Check for lsi devices, step through the static device
4202  *	table to match vid/pid.
4203  *
4204  *   Args: un - ptr to sd_lun
4205  *
4206  *   Notes:  When creating new LSI property, need to add the new LSI property
4207  *		to this function.
4208  */
4209 static void
4210 sd_is_lsi(struct sd_lun *un)
4211 {
4212 	char	*id = NULL;
4213 	int	table_index;
4214 	int	idlen;
4215 	void	*prop;
4216 
4217 	ASSERT(un != NULL);
4218 	for (table_index = 0; table_index < sd_disk_table_size;
4219 	    table_index++) {
4220 		id = sd_disk_table[table_index].device_id;
4221 		idlen = strlen(id);
4222 		if (idlen == 0) {
4223 			continue;
4224 		}
4225 
4226 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4227 			prop = sd_disk_table[table_index].properties;
4228 			if (prop == &lsi_properties ||
4229 			    prop == &lsi_oem_properties ||
4230 			    prop == &lsi_properties_scsi ||
4231 			    prop == &symbios_properties) {
4232 				un->un_f_cfg_is_lsi = TRUE;
4233 			}
4234 			break;
4235 		}
4236 	}
4237 }
4238 
4239 /*
4240  *    Function: sd_get_physical_geometry
4241  *
4242  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4243  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4244  *		target, and use this information to initialize the physical
4245  *		geometry cache specified by pgeom_p.
4246  *
4247  *		MODE SENSE is an optional command, so failure in this case
4248  *		does not necessarily denote an error. We want to use the
4249  *		MODE SENSE commands to derive the physical geometry of the
4250  *		device, but if either command fails, the logical geometry is
4251  *		used as the fallback for disk label geometry in cmlb.
4252  *
4253  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4254  *		have already been initialized for the current target and
4255  *		that the current values be passed as args so that we don't
4256  *		end up ever trying to use -1 as a valid value. This could
4257  *		happen if either value is reset while we're not holding
4258  *		the mutex.
4259  *
4260  *   Arguments: un - driver soft state (unit) structure
4261  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4262  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4263  *			to use the USCSI "direct" chain and bypass the normal
4264  *			command waitq.
4265  *
4266  *     Context: Kernel thread only (can sleep).
4267  */
4268 
4269 static int
4270 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4271 	diskaddr_t capacity, int lbasize, int path_flag)
4272 {
4273 	struct	mode_format	*page3p;
4274 	struct	mode_geometry	*page4p;
4275 	struct	mode_header	*headerp;
4276 	int	sector_size;
4277 	int	nsect;
4278 	int	nhead;
4279 	int	ncyl;
4280 	int	intrlv;
4281 	int	spc;
4282 	diskaddr_t	modesense_capacity;
4283 	int	rpm;
4284 	int	bd_len;
4285 	int	mode_header_length;
4286 	uchar_t	*p3bufp;
4287 	uchar_t	*p4bufp;
4288 	int	cdbsize;
4289 	int 	ret = EIO;
4290 
4291 	ASSERT(un != NULL);
4292 
4293 	if (lbasize == 0) {
4294 		if (ISCD(un)) {
4295 			lbasize = 2048;
4296 		} else {
4297 			lbasize = un->un_sys_blocksize;
4298 		}
4299 	}
4300 	pgeom_p->g_secsize = (unsigned short)lbasize;
4301 
4302 	/*
4303 	 * If the unit is a cd/dvd drive MODE SENSE page three
4304 	 * and MODE SENSE page four are reserved (see SBC spec
4305 	 * and MMC spec). To prevent soft errors just return
4306 	 * using the default LBA size.
4307 	 */
4308 	if (ISCD(un))
4309 		return (ret);
4310 
4311 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4312 
4313 	/*
4314 	 * Retrieve MODE SENSE page 3 - Format Device Page
4315 	 */
4316 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4317 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p3bufp,
4318 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag)
4319 	    != 0) {
4320 		SD_ERROR(SD_LOG_COMMON, un,
4321 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4322 		goto page3_exit;
4323 	}
4324 
4325 	/*
4326 	 * Determine size of Block Descriptors in order to locate the mode
4327 	 * page data.  ATAPI devices return 0, SCSI devices should return
4328 	 * MODE_BLK_DESC_LENGTH.
4329 	 */
4330 	headerp = (struct mode_header *)p3bufp;
4331 	if (un->un_f_cfg_is_atapi == TRUE) {
4332 		struct mode_header_grp2 *mhp =
4333 		    (struct mode_header_grp2 *)headerp;
4334 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4335 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4336 	} else {
4337 		mode_header_length = MODE_HEADER_LENGTH;
4338 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4339 	}
4340 
4341 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4342 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4343 		    "received unexpected bd_len of %d, page3\n", bd_len);
4344 		goto page3_exit;
4345 	}
4346 
4347 	page3p = (struct mode_format *)
4348 	    ((caddr_t)headerp + mode_header_length + bd_len);
4349 
4350 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4351 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4352 		    "mode sense pg3 code mismatch %d\n",
4353 		    page3p->mode_page.code);
4354 		goto page3_exit;
4355 	}
4356 
4357 	/*
4358 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4359 	 * complete successfully; otherwise, revert to the logical geometry.
4360 	 * So, we need to save everything in temporary variables.
4361 	 */
4362 	sector_size = BE_16(page3p->data_bytes_sect);
4363 
4364 	/*
4365 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4366 	 */
4367 	if (sector_size == 0) {
4368 		sector_size = un->un_sys_blocksize;
4369 	} else {
4370 		sector_size &= ~(un->un_sys_blocksize - 1);
4371 	}
4372 
4373 	nsect  = BE_16(page3p->sect_track);
4374 	intrlv = BE_16(page3p->interleave);
4375 
4376 	SD_INFO(SD_LOG_COMMON, un,
4377 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
4378 	SD_INFO(SD_LOG_COMMON, un,
4379 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
4380 	    page3p->mode_page.code, nsect, sector_size);
4381 	SD_INFO(SD_LOG_COMMON, un,
4382 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
4383 	    BE_16(page3p->track_skew),
4384 	    BE_16(page3p->cylinder_skew));
4385 
4386 
4387 	/*
4388 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
4389 	 */
4390 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
4391 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p4bufp,
4392 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag)
4393 	    != 0) {
4394 		SD_ERROR(SD_LOG_COMMON, un,
4395 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
4396 		goto page4_exit;
4397 	}
4398 
4399 	/*
4400 	 * Determine size of Block Descriptors in order to locate the mode
4401 	 * page data.  ATAPI devices return 0, SCSI devices should return
4402 	 * MODE_BLK_DESC_LENGTH.
4403 	 */
4404 	headerp = (struct mode_header *)p4bufp;
4405 	if (un->un_f_cfg_is_atapi == TRUE) {
4406 		struct mode_header_grp2 *mhp =
4407 		    (struct mode_header_grp2 *)headerp;
4408 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4409 	} else {
4410 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4411 	}
4412 
4413 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4414 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4415 		    "received unexpected bd_len of %d, page4\n", bd_len);
4416 		goto page4_exit;
4417 	}
4418 
4419 	page4p = (struct mode_geometry *)
4420 	    ((caddr_t)headerp + mode_header_length + bd_len);
4421 
4422 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
4423 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4424 		    "mode sense pg4 code mismatch %d\n",
4425 		    page4p->mode_page.code);
4426 		goto page4_exit;
4427 	}
4428 
4429 	/*
4430 	 * Stash the data now, after we know that both commands completed.
4431 	 */
4432 
4433 
4434 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
4435 	spc   = nhead * nsect;
4436 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
4437 	rpm   = BE_16(page4p->rpm);
4438 
4439 	modesense_capacity = spc * ncyl;
4440 
4441 	SD_INFO(SD_LOG_COMMON, un,
4442 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
4443 	SD_INFO(SD_LOG_COMMON, un,
4444 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
4445 	SD_INFO(SD_LOG_COMMON, un,
4446 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
4447 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
4448 	    (void *)pgeom_p, capacity);
4449 
4450 	/*
4451 	 * Compensate if the drive's geometry is not rectangular, i.e.,
4452 	 * the product of C * H * S returned by MODE SENSE >= that returned
4453 	 * by read capacity. This is an idiosyncrasy of the original x86
4454 	 * disk subsystem.
4455 	 */
4456 	if (modesense_capacity >= capacity) {
4457 		SD_INFO(SD_LOG_COMMON, un,
4458 		    "sd_get_physical_geometry: adjusting acyl; "
4459 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
4460 		    (modesense_capacity - capacity + spc - 1) / spc);
4461 		if (sector_size != 0) {
4462 			/* 1243403: NEC D38x7 drives don't support sec size */
4463 			pgeom_p->g_secsize = (unsigned short)sector_size;
4464 		}
4465 		pgeom_p->g_nsect    = (unsigned short)nsect;
4466 		pgeom_p->g_nhead    = (unsigned short)nhead;
4467 		pgeom_p->g_capacity = capacity;
4468 		pgeom_p->g_acyl	    =
4469 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
4470 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
4471 	}
4472 
4473 	pgeom_p->g_rpm    = (unsigned short)rpm;
4474 	pgeom_p->g_intrlv = (unsigned short)intrlv;
4475 	ret = 0;
4476 
4477 	SD_INFO(SD_LOG_COMMON, un,
4478 	    "sd_get_physical_geometry: mode sense geometry:\n");
4479 	SD_INFO(SD_LOG_COMMON, un,
4480 	    "   nsect: %d; sector size: %d; interlv: %d\n",
4481 	    nsect, sector_size, intrlv);
4482 	SD_INFO(SD_LOG_COMMON, un,
4483 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
4484 	    nhead, ncyl, rpm, modesense_capacity);
4485 	SD_INFO(SD_LOG_COMMON, un,
4486 	    "sd_get_physical_geometry: (cached)\n");
4487 	SD_INFO(SD_LOG_COMMON, un,
4488 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
4489 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
4490 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
4491 	SD_INFO(SD_LOG_COMMON, un,
4492 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
4493 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
4494 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
4495 
4496 page4_exit:
4497 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
4498 page3_exit:
4499 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
4500 
4501 	return (ret);
4502 }
4503 
4504 /*
4505  *    Function: sd_get_virtual_geometry
4506  *
4507  * Description: Ask the controller to tell us about the target device.
4508  *
4509  *   Arguments: un - pointer to softstate
4510  *		capacity - disk capacity in #blocks
4511  *		lbasize - disk block size in bytes
4512  *
4513  *     Context: Kernel thread only
4514  */
4515 
4516 static int
4517 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
4518     diskaddr_t capacity, int lbasize)
4519 {
4520 	uint_t	geombuf;
4521 	int	spc;
4522 
4523 	ASSERT(un != NULL);
4524 
4525 	/* Set sector size, and total number of sectors */
4526 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
4527 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
4528 
4529 	/* Let the HBA tell us its geometry */
4530 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
4531 
4532 	/* A value of -1 indicates an undefined "geometry" property */
4533 	if (geombuf == (-1)) {
4534 		return (EINVAL);
4535 	}
4536 
4537 	/* Initialize the logical geometry cache. */
4538 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
4539 	lgeom_p->g_nsect   = geombuf & 0xffff;
4540 	lgeom_p->g_secsize = un->un_sys_blocksize;
4541 
4542 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
4543 
4544 	/*
4545 	 * Note: The driver originally converted the capacity value from
4546 	 * target blocks to system blocks. However, the capacity value passed
4547 	 * to this routine is already in terms of system blocks (this scaling
4548 	 * is done when the READ CAPACITY command is issued and processed).
4549 	 * This 'error' may have gone undetected because the usage of g_ncyl
4550 	 * (which is based upon g_capacity) is very limited within the driver
4551 	 */
4552 	lgeom_p->g_capacity = capacity;
4553 
4554 	/*
4555 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
4556 	 * hba may return zero values if the device has been removed.
4557 	 */
4558 	if (spc == 0) {
4559 		lgeom_p->g_ncyl = 0;
4560 	} else {
4561 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
4562 	}
4563 	lgeom_p->g_acyl = 0;
4564 
4565 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
4566 	return (0);
4567 
4568 }
4569 /*
4570  *    Function: sd_update_block_info
4571  *
4572  * Description: Calculate a byte count to sector count bitshift value
4573  *		from sector size.
4574  *
4575  *   Arguments: un: unit struct.
4576  *		lbasize: new target sector size
4577  *		capacity: new target capacity, ie. block count
4578  *
4579  *     Context: Kernel thread context
4580  */
4581 
4582 static void
4583 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
4584 {
4585 	uint_t		dblk;
4586 
4587 	if (lbasize != 0) {
4588 		un->un_tgt_blocksize = lbasize;
4589 		un->un_f_tgt_blocksize_is_valid	= TRUE;
4590 	}
4591 
4592 	if (capacity != 0) {
4593 		un->un_blockcount		= capacity;
4594 		un->un_f_blockcount_is_valid	= TRUE;
4595 	}
4596 
4597 	/*
4598 	 * Update device capacity properties.
4599 	 *
4600 	 *   'device-nblocks'	number of blocks in target's units
4601 	 *   'device-blksize'	data bearing size of target's block
4602 	 *
4603 	 * NOTE: math is complicated by the fact that un_tgt_blocksize may
4604 	 * not be a power of two for checksumming disks with 520/528 byte
4605 	 * sectors.
4606 	 */
4607 	if (un->un_f_tgt_blocksize_is_valid &&
4608 	    un->un_f_blockcount_is_valid &&
4609 	    un->un_sys_blocksize) {
4610 		dblk = un->un_tgt_blocksize / un->un_sys_blocksize;
4611 		(void) ddi_prop_update_int64(DDI_DEV_T_NONE, SD_DEVINFO(un),
4612 		    "device-nblocks", un->un_blockcount / dblk);
4613 		/*
4614 		 * To save memory, only define "device-blksize" when its
4615 		 * value is differnet than the default DEV_BSIZE value.
4616 		 */
4617 		if ((un->un_sys_blocksize * dblk) != DEV_BSIZE)
4618 			(void) ddi_prop_update_int(DDI_DEV_T_NONE,
4619 			    SD_DEVINFO(un), "device-blksize",
4620 			    un->un_sys_blocksize * dblk);
4621 	}
4622 }
4623 
4624 
4625 /*
4626  *    Function: sd_register_devid
4627  *
4628  * Description: This routine will obtain the device id information from the
4629  *		target, obtain the serial number, and register the device
4630  *		id with the ddi framework.
4631  *
4632  *   Arguments: devi - the system's dev_info_t for the device.
4633  *		un - driver soft state (unit) structure
4634  *		reservation_flag - indicates if a reservation conflict
4635  *		occurred during attach
4636  *
4637  *     Context: Kernel Thread
4638  */
4639 static void
4640 sd_register_devid(struct sd_lun *un, dev_info_t *devi, int reservation_flag)
4641 {
4642 	int		rval		= 0;
4643 	uchar_t		*inq80		= NULL;
4644 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
4645 	size_t		inq80_resid	= 0;
4646 	uchar_t		*inq83		= NULL;
4647 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
4648 	size_t		inq83_resid	= 0;
4649 	int		dlen, len;
4650 	char		*sn;
4651 
4652 	ASSERT(un != NULL);
4653 	ASSERT(mutex_owned(SD_MUTEX(un)));
4654 	ASSERT((SD_DEVINFO(un)) == devi);
4655 
4656 	/*
4657 	 * If transport has already registered a devid for this target
4658 	 * then that takes precedence over the driver's determination
4659 	 * of the devid.
4660 	 */
4661 	if (ddi_devid_get(SD_DEVINFO(un), &un->un_devid) == DDI_SUCCESS) {
4662 		ASSERT(un->un_devid);
4663 		return; /* use devid registered by the transport */
4664 	}
4665 
4666 	/*
4667 	 * This is the case of antiquated Sun disk drives that have the
4668 	 * FAB_DEVID property set in the disk_table.  These drives
4669 	 * manage the devid's by storing them in last 2 available sectors
4670 	 * on the drive and have them fabricated by the ddi layer by calling
4671 	 * ddi_devid_init and passing the DEVID_FAB flag.
4672 	 */
4673 	if (un->un_f_opt_fab_devid == TRUE) {
4674 		/*
4675 		 * Depending on EINVAL isn't reliable, since a reserved disk
4676 		 * may result in invalid geometry, so check to make sure a
4677 		 * reservation conflict did not occur during attach.
4678 		 */
4679 		if ((sd_get_devid(un) == EINVAL) &&
4680 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
4681 			/*
4682 			 * The devid is invalid AND there is no reservation
4683 			 * conflict.  Fabricate a new devid.
4684 			 */
4685 			(void) sd_create_devid(un);
4686 		}
4687 
4688 		/* Register the devid if it exists */
4689 		if (un->un_devid != NULL) {
4690 			(void) ddi_devid_register(SD_DEVINFO(un),
4691 			    un->un_devid);
4692 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4693 			    "sd_register_devid: Devid Fabricated\n");
4694 		}
4695 		return;
4696 	}
4697 
4698 	/*
4699 	 * We check the availibility of the World Wide Name (0x83) and Unit
4700 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
4701 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
4702 	 * 0x83 is availible, that is the best choice.  Our next choice is
4703 	 * 0x80.  If neither are availible, we munge the devid from the device
4704 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
4705 	 * to fabricate a devid for non-Sun qualified disks.
4706 	 */
4707 	if (sd_check_vpd_page_support(un) == 0) {
4708 		/* collect page 80 data if available */
4709 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
4710 
4711 			mutex_exit(SD_MUTEX(un));
4712 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
4713 			rval = sd_send_scsi_INQUIRY(un, inq80, inq80_len,
4714 			    0x01, 0x80, &inq80_resid);
4715 
4716 			if (rval != 0) {
4717 				kmem_free(inq80, inq80_len);
4718 				inq80 = NULL;
4719 				inq80_len = 0;
4720 			} else if (ddi_prop_exists(
4721 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
4722 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
4723 			    INQUIRY_SERIAL_NO) == 0) {
4724 				/*
4725 				 * If we don't already have a serial number
4726 				 * property, do quick verify of data returned
4727 				 * and define property.
4728 				 */
4729 				dlen = inq80_len - inq80_resid;
4730 				len = (size_t)inq80[3];
4731 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
4732 					/*
4733 					 * Ensure sn termination, skip leading
4734 					 * blanks, and create property
4735 					 * 'inquiry-serial-no'.
4736 					 */
4737 					sn = (char *)&inq80[4];
4738 					sn[len] = 0;
4739 					while (*sn && (*sn == ' '))
4740 						sn++;
4741 					if (*sn) {
4742 						(void) ddi_prop_update_string(
4743 						    DDI_DEV_T_NONE,
4744 						    SD_DEVINFO(un),
4745 						    INQUIRY_SERIAL_NO, sn);
4746 					}
4747 				}
4748 			}
4749 			mutex_enter(SD_MUTEX(un));
4750 		}
4751 
4752 		/* collect page 83 data if available */
4753 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
4754 			mutex_exit(SD_MUTEX(un));
4755 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
4756 			rval = sd_send_scsi_INQUIRY(un, inq83, inq83_len,
4757 			    0x01, 0x83, &inq83_resid);
4758 
4759 			if (rval != 0) {
4760 				kmem_free(inq83, inq83_len);
4761 				inq83 = NULL;
4762 				inq83_len = 0;
4763 			}
4764 			mutex_enter(SD_MUTEX(un));
4765 		}
4766 	}
4767 
4768 	/* encode best devid possible based on data available */
4769 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
4770 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
4771 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
4772 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
4773 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
4774 
4775 		/* devid successfully encoded, register devid */
4776 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
4777 
4778 	} else {
4779 		/*
4780 		 * Unable to encode a devid based on data available.
4781 		 * This is not a Sun qualified disk.  Older Sun disk
4782 		 * drives that have the SD_FAB_DEVID property
4783 		 * set in the disk_table and non Sun qualified
4784 		 * disks are treated in the same manner.  These
4785 		 * drives manage the devid's by storing them in
4786 		 * last 2 available sectors on the drive and
4787 		 * have them fabricated by the ddi layer by
4788 		 * calling ddi_devid_init and passing the
4789 		 * DEVID_FAB flag.
4790 		 * Create a fabricate devid only if there's no
4791 		 * fabricate devid existed.
4792 		 */
4793 		if (sd_get_devid(un) == EINVAL) {
4794 			(void) sd_create_devid(un);
4795 		}
4796 		un->un_f_opt_fab_devid = TRUE;
4797 
4798 		/* Register the devid if it exists */
4799 		if (un->un_devid != NULL) {
4800 			(void) ddi_devid_register(SD_DEVINFO(un),
4801 			    un->un_devid);
4802 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4803 			    "sd_register_devid: devid fabricated using "
4804 			    "ddi framework\n");
4805 		}
4806 	}
4807 
4808 	/* clean up resources */
4809 	if (inq80 != NULL) {
4810 		kmem_free(inq80, inq80_len);
4811 	}
4812 	if (inq83 != NULL) {
4813 		kmem_free(inq83, inq83_len);
4814 	}
4815 }
4816 
4817 
4818 
4819 /*
4820  *    Function: sd_get_devid
4821  *
4822  * Description: This routine will return 0 if a valid device id has been
4823  *		obtained from the target and stored in the soft state. If a
4824  *		valid device id has not been previously read and stored, a
4825  *		read attempt will be made.
4826  *
4827  *   Arguments: un - driver soft state (unit) structure
4828  *
4829  * Return Code: 0 if we successfully get the device id
4830  *
4831  *     Context: Kernel Thread
4832  */
4833 
4834 static int
4835 sd_get_devid(struct sd_lun *un)
4836 {
4837 	struct dk_devid		*dkdevid;
4838 	ddi_devid_t		tmpid;
4839 	uint_t			*ip;
4840 	size_t			sz;
4841 	diskaddr_t		blk;
4842 	int			status;
4843 	int			chksum;
4844 	int			i;
4845 	size_t			buffer_size;
4846 
4847 	ASSERT(un != NULL);
4848 	ASSERT(mutex_owned(SD_MUTEX(un)));
4849 
4850 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
4851 	    un);
4852 
4853 	if (un->un_devid != NULL) {
4854 		return (0);
4855 	}
4856 
4857 	mutex_exit(SD_MUTEX(un));
4858 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
4859 	    (void *)SD_PATH_DIRECT) != 0) {
4860 		mutex_enter(SD_MUTEX(un));
4861 		return (EINVAL);
4862 	}
4863 
4864 	/*
4865 	 * Read and verify device id, stored in the reserved cylinders at the
4866 	 * end of the disk. Backup label is on the odd sectors of the last
4867 	 * track of the last cylinder. Device id will be on track of the next
4868 	 * to last cylinder.
4869 	 */
4870 	mutex_enter(SD_MUTEX(un));
4871 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
4872 	mutex_exit(SD_MUTEX(un));
4873 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
4874 	status = sd_send_scsi_READ(un, dkdevid, buffer_size, blk,
4875 	    SD_PATH_DIRECT);
4876 	if (status != 0) {
4877 		goto error;
4878 	}
4879 
4880 	/* Validate the revision */
4881 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
4882 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
4883 		status = EINVAL;
4884 		goto error;
4885 	}
4886 
4887 	/* Calculate the checksum */
4888 	chksum = 0;
4889 	ip = (uint_t *)dkdevid;
4890 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
4891 	    i++) {
4892 		chksum ^= ip[i];
4893 	}
4894 
4895 	/* Compare the checksums */
4896 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
4897 		status = EINVAL;
4898 		goto error;
4899 	}
4900 
4901 	/* Validate the device id */
4902 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
4903 		status = EINVAL;
4904 		goto error;
4905 	}
4906 
4907 	/*
4908 	 * Store the device id in the driver soft state
4909 	 */
4910 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
4911 	tmpid = kmem_alloc(sz, KM_SLEEP);
4912 
4913 	mutex_enter(SD_MUTEX(un));
4914 
4915 	un->un_devid = tmpid;
4916 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
4917 
4918 	kmem_free(dkdevid, buffer_size);
4919 
4920 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
4921 
4922 	return (status);
4923 error:
4924 	mutex_enter(SD_MUTEX(un));
4925 	kmem_free(dkdevid, buffer_size);
4926 	return (status);
4927 }
4928 
4929 
4930 /*
4931  *    Function: sd_create_devid
4932  *
4933  * Description: This routine will fabricate the device id and write it
4934  *		to the disk.
4935  *
4936  *   Arguments: un - driver soft state (unit) structure
4937  *
4938  * Return Code: value of the fabricated device id
4939  *
4940  *     Context: Kernel Thread
4941  */
4942 
4943 static ddi_devid_t
4944 sd_create_devid(struct sd_lun *un)
4945 {
4946 	ASSERT(un != NULL);
4947 
4948 	/* Fabricate the devid */
4949 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
4950 	    == DDI_FAILURE) {
4951 		return (NULL);
4952 	}
4953 
4954 	/* Write the devid to disk */
4955 	if (sd_write_deviceid(un) != 0) {
4956 		ddi_devid_free(un->un_devid);
4957 		un->un_devid = NULL;
4958 	}
4959 
4960 	return (un->un_devid);
4961 }
4962 
4963 
4964 /*
4965  *    Function: sd_write_deviceid
4966  *
4967  * Description: This routine will write the device id to the disk
4968  *		reserved sector.
4969  *
4970  *   Arguments: un - driver soft state (unit) structure
4971  *
4972  * Return Code: EINVAL
4973  *		value returned by sd_send_scsi_cmd
4974  *
4975  *     Context: Kernel Thread
4976  */
4977 
4978 static int
4979 sd_write_deviceid(struct sd_lun *un)
4980 {
4981 	struct dk_devid		*dkdevid;
4982 	diskaddr_t		blk;
4983 	uint_t			*ip, chksum;
4984 	int			status;
4985 	int			i;
4986 
4987 	ASSERT(mutex_owned(SD_MUTEX(un)));
4988 
4989 	mutex_exit(SD_MUTEX(un));
4990 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
4991 	    (void *)SD_PATH_DIRECT) != 0) {
4992 		mutex_enter(SD_MUTEX(un));
4993 		return (-1);
4994 	}
4995 
4996 
4997 	/* Allocate the buffer */
4998 	dkdevid = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
4999 
5000 	/* Fill in the revision */
5001 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
5002 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
5003 
5004 	/* Copy in the device id */
5005 	mutex_enter(SD_MUTEX(un));
5006 	bcopy(un->un_devid, &dkdevid->dkd_devid,
5007 	    ddi_devid_sizeof(un->un_devid));
5008 	mutex_exit(SD_MUTEX(un));
5009 
5010 	/* Calculate the checksum */
5011 	chksum = 0;
5012 	ip = (uint_t *)dkdevid;
5013 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
5014 	    i++) {
5015 		chksum ^= ip[i];
5016 	}
5017 
5018 	/* Fill-in checksum */
5019 	DKD_FORMCHKSUM(chksum, dkdevid);
5020 
5021 	/* Write the reserved sector */
5022 	status = sd_send_scsi_WRITE(un, dkdevid, un->un_sys_blocksize, blk,
5023 	    SD_PATH_DIRECT);
5024 
5025 	kmem_free(dkdevid, un->un_sys_blocksize);
5026 
5027 	mutex_enter(SD_MUTEX(un));
5028 	return (status);
5029 }
5030 
5031 
5032 /*
5033  *    Function: sd_check_vpd_page_support
5034  *
5035  * Description: This routine sends an inquiry command with the EVPD bit set and
5036  *		a page code of 0x00 to the device. It is used to determine which
5037  *		vital product pages are availible to find the devid. We are
5038  *		looking for pages 0x83 or 0x80.  If we return a negative 1, the
5039  *		device does not support that command.
5040  *
5041  *   Arguments: un  - driver soft state (unit) structure
5042  *
5043  * Return Code: 0 - success
5044  *		1 - check condition
5045  *
5046  *     Context: This routine can sleep.
5047  */
5048 
5049 static int
5050 sd_check_vpd_page_support(struct sd_lun *un)
5051 {
5052 	uchar_t	*page_list	= NULL;
5053 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5054 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5055 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5056 	int    	rval		= 0;
5057 	int	counter;
5058 
5059 	ASSERT(un != NULL);
5060 	ASSERT(mutex_owned(SD_MUTEX(un)));
5061 
5062 	mutex_exit(SD_MUTEX(un));
5063 
5064 	/*
5065 	 * We'll set the page length to the maximum to save figuring it out
5066 	 * with an additional call.
5067 	 */
5068 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5069 
5070 	rval = sd_send_scsi_INQUIRY(un, page_list, page_length, evpd,
5071 	    page_code, NULL);
5072 
5073 	mutex_enter(SD_MUTEX(un));
5074 
5075 	/*
5076 	 * Now we must validate that the device accepted the command, as some
5077 	 * drives do not support it.  If the drive does support it, we will
5078 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5079 	 * not, we return -1.
5080 	 */
5081 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5082 		/* Loop to find one of the 2 pages we need */
5083 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5084 
5085 		/*
5086 		 * Pages are returned in ascending order, and 0x83 is what we
5087 		 * are hoping for.
5088 		 */
5089 		while ((page_list[counter] <= 0x86) &&
5090 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5091 		    VPD_HEAD_OFFSET))) {
5092 			/*
5093 			 * Add 3 because page_list[3] is the number of
5094 			 * pages minus 3
5095 			 */
5096 
5097 			switch (page_list[counter]) {
5098 			case 0x00:
5099 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5100 				break;
5101 			case 0x80:
5102 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5103 				break;
5104 			case 0x81:
5105 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5106 				break;
5107 			case 0x82:
5108 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5109 				break;
5110 			case 0x83:
5111 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5112 				break;
5113 			case 0x86:
5114 				un->un_vpd_page_mask |= SD_VPD_EXTENDED_DATA_PG;
5115 				break;
5116 			}
5117 			counter++;
5118 		}
5119 
5120 	} else {
5121 		rval = -1;
5122 
5123 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5124 		    "sd_check_vpd_page_support: This drive does not implement "
5125 		    "VPD pages.\n");
5126 	}
5127 
5128 	kmem_free(page_list, page_length);
5129 
5130 	return (rval);
5131 }
5132 
5133 
5134 /*
5135  *    Function: sd_setup_pm
5136  *
5137  * Description: Initialize Power Management on the device
5138  *
5139  *     Context: Kernel Thread
5140  */
5141 
5142 static void
5143 sd_setup_pm(struct sd_lun *un, dev_info_t *devi)
5144 {
5145 	uint_t	log_page_size;
5146 	uchar_t	*log_page_data;
5147 	int	rval;
5148 
5149 	/*
5150 	 * Since we are called from attach, holding a mutex for
5151 	 * un is unnecessary. Because some of the routines called
5152 	 * from here require SD_MUTEX to not be held, assert this
5153 	 * right up front.
5154 	 */
5155 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5156 	/*
5157 	 * Since the sd device does not have the 'reg' property,
5158 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5159 	 * The following code is to tell cpr that this device
5160 	 * DOES need to be suspended and resumed.
5161 	 */
5162 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5163 	    "pm-hardware-state", "needs-suspend-resume");
5164 
5165 	/*
5166 	 * This complies with the new power management framework
5167 	 * for certain desktop machines. Create the pm_components
5168 	 * property as a string array property.
5169 	 */
5170 	if (un->un_f_pm_supported) {
5171 		/*
5172 		 * not all devices have a motor, try it first.
5173 		 * some devices may return ILLEGAL REQUEST, some
5174 		 * will hang
5175 		 * The following START_STOP_UNIT is used to check if target
5176 		 * device has a motor.
5177 		 */
5178 		un->un_f_start_stop_supported = TRUE;
5179 		if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
5180 		    SD_PATH_DIRECT) != 0) {
5181 			un->un_f_start_stop_supported = FALSE;
5182 		}
5183 
5184 		/*
5185 		 * create pm properties anyways otherwise the parent can't
5186 		 * go to sleep
5187 		 */
5188 		(void) sd_create_pm_components(devi, un);
5189 		un->un_f_pm_is_enabled = TRUE;
5190 		return;
5191 	}
5192 
5193 	if (!un->un_f_log_sense_supported) {
5194 		un->un_power_level = SD_SPINDLE_ON;
5195 		un->un_f_pm_is_enabled = FALSE;
5196 		return;
5197 	}
5198 
5199 	rval = sd_log_page_supported(un, START_STOP_CYCLE_PAGE);
5200 
5201 #ifdef	SDDEBUG
5202 	if (sd_force_pm_supported) {
5203 		/* Force a successful result */
5204 		rval = 1;
5205 	}
5206 #endif
5207 
5208 	/*
5209 	 * If the start-stop cycle counter log page is not supported
5210 	 * or if the pm-capable property is SD_PM_CAPABLE_FALSE (0)
5211 	 * then we should not create the pm_components property.
5212 	 */
5213 	if (rval == -1) {
5214 		/*
5215 		 * Error.
5216 		 * Reading log sense failed, most likely this is
5217 		 * an older drive that does not support log sense.
5218 		 * If this fails auto-pm is not supported.
5219 		 */
5220 		un->un_power_level = SD_SPINDLE_ON;
5221 		un->un_f_pm_is_enabled = FALSE;
5222 
5223 	} else if (rval == 0) {
5224 		/*
5225 		 * Page not found.
5226 		 * The start stop cycle counter is implemented as page
5227 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
5228 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
5229 		 */
5230 		if (sd_log_page_supported(un, START_STOP_CYCLE_VU_PAGE) == 1) {
5231 			/*
5232 			 * Page found, use this one.
5233 			 */
5234 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
5235 			un->un_f_pm_is_enabled = TRUE;
5236 		} else {
5237 			/*
5238 			 * Error or page not found.
5239 			 * auto-pm is not supported for this device.
5240 			 */
5241 			un->un_power_level = SD_SPINDLE_ON;
5242 			un->un_f_pm_is_enabled = FALSE;
5243 		}
5244 	} else {
5245 		/*
5246 		 * Page found, use it.
5247 		 */
5248 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
5249 		un->un_f_pm_is_enabled = TRUE;
5250 	}
5251 
5252 
5253 	if (un->un_f_pm_is_enabled == TRUE) {
5254 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5255 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5256 
5257 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
5258 		    log_page_size, un->un_start_stop_cycle_page,
5259 		    0x01, 0, SD_PATH_DIRECT);
5260 #ifdef	SDDEBUG
5261 		if (sd_force_pm_supported) {
5262 			/* Force a successful result */
5263 			rval = 0;
5264 		}
5265 #endif
5266 
5267 		/*
5268 		 * If the Log sense for Page( Start/stop cycle counter page)
5269 		 * succeeds, then power managment is supported and we can
5270 		 * enable auto-pm.
5271 		 */
5272 		if (rval == 0)  {
5273 			(void) sd_create_pm_components(devi, un);
5274 		} else {
5275 			un->un_power_level = SD_SPINDLE_ON;
5276 			un->un_f_pm_is_enabled = FALSE;
5277 		}
5278 
5279 		kmem_free(log_page_data, log_page_size);
5280 	}
5281 }
5282 
5283 
5284 /*
5285  *    Function: sd_create_pm_components
5286  *
5287  * Description: Initialize PM property.
5288  *
5289  *     Context: Kernel thread context
5290  */
5291 
5292 static void
5293 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
5294 {
5295 	char *pm_comp[] = { "NAME=spindle-motor", "0=off", "1=on", NULL };
5296 
5297 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5298 
5299 	if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
5300 	    "pm-components", pm_comp, 3) == DDI_PROP_SUCCESS) {
5301 		/*
5302 		 * When components are initially created they are idle,
5303 		 * power up any non-removables.
5304 		 * Note: the return value of pm_raise_power can't be used
5305 		 * for determining if PM should be enabled for this device.
5306 		 * Even if you check the return values and remove this
5307 		 * property created above, the PM framework will not honor the
5308 		 * change after the first call to pm_raise_power. Hence,
5309 		 * removal of that property does not help if pm_raise_power
5310 		 * fails. In the case of removable media, the start/stop
5311 		 * will fail if the media is not present.
5312 		 */
5313 		if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
5314 		    SD_SPINDLE_ON) == DDI_SUCCESS)) {
5315 			mutex_enter(SD_MUTEX(un));
5316 			un->un_power_level = SD_SPINDLE_ON;
5317 			mutex_enter(&un->un_pm_mutex);
5318 			/* Set to on and not busy. */
5319 			un->un_pm_count = 0;
5320 		} else {
5321 			mutex_enter(SD_MUTEX(un));
5322 			un->un_power_level = SD_SPINDLE_OFF;
5323 			mutex_enter(&un->un_pm_mutex);
5324 			/* Set to off. */
5325 			un->un_pm_count = -1;
5326 		}
5327 		mutex_exit(&un->un_pm_mutex);
5328 		mutex_exit(SD_MUTEX(un));
5329 	} else {
5330 		un->un_power_level = SD_SPINDLE_ON;
5331 		un->un_f_pm_is_enabled = FALSE;
5332 	}
5333 }
5334 
5335 
5336 /*
5337  *    Function: sd_ddi_suspend
5338  *
5339  * Description: Performs system power-down operations. This includes
5340  *		setting the drive state to indicate its suspended so
5341  *		that no new commands will be accepted. Also, wait for
5342  *		all commands that are in transport or queued to a timer
5343  *		for retry to complete. All timeout threads are cancelled.
5344  *
5345  * Return Code: DDI_FAILURE or DDI_SUCCESS
5346  *
5347  *     Context: Kernel thread context
5348  */
5349 
5350 static int
5351 sd_ddi_suspend(dev_info_t *devi)
5352 {
5353 	struct	sd_lun	*un;
5354 	clock_t		wait_cmds_complete;
5355 
5356 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
5357 	if (un == NULL) {
5358 		return (DDI_FAILURE);
5359 	}
5360 
5361 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
5362 
5363 	mutex_enter(SD_MUTEX(un));
5364 
5365 	/* Return success if the device is already suspended. */
5366 	if (un->un_state == SD_STATE_SUSPENDED) {
5367 		mutex_exit(SD_MUTEX(un));
5368 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5369 		    "device already suspended, exiting\n");
5370 		return (DDI_SUCCESS);
5371 	}
5372 
5373 	/* Return failure if the device is being used by HA */
5374 	if (un->un_resvd_status &
5375 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
5376 		mutex_exit(SD_MUTEX(un));
5377 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5378 		    "device in use by HA, exiting\n");
5379 		return (DDI_FAILURE);
5380 	}
5381 
5382 	/*
5383 	 * Return failure if the device is in a resource wait
5384 	 * or power changing state.
5385 	 */
5386 	if ((un->un_state == SD_STATE_RWAIT) ||
5387 	    (un->un_state == SD_STATE_PM_CHANGING)) {
5388 		mutex_exit(SD_MUTEX(un));
5389 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5390 		    "device in resource wait state, exiting\n");
5391 		return (DDI_FAILURE);
5392 	}
5393 
5394 
5395 	un->un_save_state = un->un_last_state;
5396 	New_state(un, SD_STATE_SUSPENDED);
5397 
5398 	/*
5399 	 * Wait for all commands that are in transport or queued to a timer
5400 	 * for retry to complete.
5401 	 *
5402 	 * While waiting, no new commands will be accepted or sent because of
5403 	 * the new state we set above.
5404 	 *
5405 	 * Wait till current operation has completed. If we are in the resource
5406 	 * wait state (with an intr outstanding) then we need to wait till the
5407 	 * intr completes and starts the next cmd. We want to wait for
5408 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
5409 	 */
5410 	wait_cmds_complete = ddi_get_lbolt() +
5411 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
5412 
5413 	while (un->un_ncmds_in_transport != 0) {
5414 		/*
5415 		 * Fail if commands do not finish in the specified time.
5416 		 */
5417 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
5418 		    wait_cmds_complete) == -1) {
5419 			/*
5420 			 * Undo the state changes made above. Everything
5421 			 * must go back to it's original value.
5422 			 */
5423 			Restore_state(un);
5424 			un->un_last_state = un->un_save_state;
5425 			/* Wake up any threads that might be waiting. */
5426 			cv_broadcast(&un->un_suspend_cv);
5427 			mutex_exit(SD_MUTEX(un));
5428 			SD_ERROR(SD_LOG_IO_PM, un,
5429 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
5430 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
5431 			return (DDI_FAILURE);
5432 		}
5433 	}
5434 
5435 	/*
5436 	 * Cancel SCSI watch thread and timeouts, if any are active
5437 	 */
5438 
5439 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
5440 		opaque_t temp_token = un->un_swr_token;
5441 		mutex_exit(SD_MUTEX(un));
5442 		scsi_watch_suspend(temp_token);
5443 		mutex_enter(SD_MUTEX(un));
5444 	}
5445 
5446 	if (un->un_reset_throttle_timeid != NULL) {
5447 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
5448 		un->un_reset_throttle_timeid = NULL;
5449 		mutex_exit(SD_MUTEX(un));
5450 		(void) untimeout(temp_id);
5451 		mutex_enter(SD_MUTEX(un));
5452 	}
5453 
5454 	if (un->un_dcvb_timeid != NULL) {
5455 		timeout_id_t temp_id = un->un_dcvb_timeid;
5456 		un->un_dcvb_timeid = NULL;
5457 		mutex_exit(SD_MUTEX(un));
5458 		(void) untimeout(temp_id);
5459 		mutex_enter(SD_MUTEX(un));
5460 	}
5461 
5462 	mutex_enter(&un->un_pm_mutex);
5463 	if (un->un_pm_timeid != NULL) {
5464 		timeout_id_t temp_id = un->un_pm_timeid;
5465 		un->un_pm_timeid = NULL;
5466 		mutex_exit(&un->un_pm_mutex);
5467 		mutex_exit(SD_MUTEX(un));
5468 		(void) untimeout(temp_id);
5469 		mutex_enter(SD_MUTEX(un));
5470 	} else {
5471 		mutex_exit(&un->un_pm_mutex);
5472 	}
5473 
5474 	if (un->un_retry_timeid != NULL) {
5475 		timeout_id_t temp_id = un->un_retry_timeid;
5476 		un->un_retry_timeid = NULL;
5477 		mutex_exit(SD_MUTEX(un));
5478 		(void) untimeout(temp_id);
5479 		mutex_enter(SD_MUTEX(un));
5480 	}
5481 
5482 	if (un->un_direct_priority_timeid != NULL) {
5483 		timeout_id_t temp_id = un->un_direct_priority_timeid;
5484 		un->un_direct_priority_timeid = NULL;
5485 		mutex_exit(SD_MUTEX(un));
5486 		(void) untimeout(temp_id);
5487 		mutex_enter(SD_MUTEX(un));
5488 	}
5489 
5490 	if (un->un_f_is_fibre == TRUE) {
5491 		/*
5492 		 * Remove callbacks for insert and remove events
5493 		 */
5494 		if (un->un_insert_event != NULL) {
5495 			mutex_exit(SD_MUTEX(un));
5496 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
5497 			mutex_enter(SD_MUTEX(un));
5498 			un->un_insert_event = NULL;
5499 		}
5500 
5501 		if (un->un_remove_event != NULL) {
5502 			mutex_exit(SD_MUTEX(un));
5503 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
5504 			mutex_enter(SD_MUTEX(un));
5505 			un->un_remove_event = NULL;
5506 		}
5507 	}
5508 
5509 	mutex_exit(SD_MUTEX(un));
5510 
5511 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
5512 
5513 	return (DDI_SUCCESS);
5514 }
5515 
5516 
5517 /*
5518  *    Function: sd_ddi_pm_suspend
5519  *
5520  * Description: Set the drive state to low power.
5521  *		Someone else is required to actually change the drive
5522  *		power level.
5523  *
5524  *   Arguments: un - driver soft state (unit) structure
5525  *
5526  * Return Code: DDI_FAILURE or DDI_SUCCESS
5527  *
5528  *     Context: Kernel thread context
5529  */
5530 
5531 static int
5532 sd_ddi_pm_suspend(struct sd_lun *un)
5533 {
5534 	ASSERT(un != NULL);
5535 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: entry\n");
5536 
5537 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5538 	mutex_enter(SD_MUTEX(un));
5539 
5540 	/*
5541 	 * Exit if power management is not enabled for this device, or if
5542 	 * the device is being used by HA.
5543 	 */
5544 	if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
5545 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
5546 		mutex_exit(SD_MUTEX(un));
5547 		SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exiting\n");
5548 		return (DDI_SUCCESS);
5549 	}
5550 
5551 	SD_INFO(SD_LOG_POWER, un, "sd_ddi_pm_suspend: un_ncmds_in_driver=%ld\n",
5552 	    un->un_ncmds_in_driver);
5553 
5554 	/*
5555 	 * See if the device is not busy, ie.:
5556 	 *    - we have no commands in the driver for this device
5557 	 *    - not waiting for resources
5558 	 */
5559 	if ((un->un_ncmds_in_driver == 0) &&
5560 	    (un->un_state != SD_STATE_RWAIT)) {
5561 		/*
5562 		 * The device is not busy, so it is OK to go to low power state.
5563 		 * Indicate low power, but rely on someone else to actually
5564 		 * change it.
5565 		 */
5566 		mutex_enter(&un->un_pm_mutex);
5567 		un->un_pm_count = -1;
5568 		mutex_exit(&un->un_pm_mutex);
5569 		un->un_power_level = SD_SPINDLE_OFF;
5570 	}
5571 
5572 	mutex_exit(SD_MUTEX(un));
5573 
5574 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exit\n");
5575 
5576 	return (DDI_SUCCESS);
5577 }
5578 
5579 
5580 /*
5581  *    Function: sd_ddi_resume
5582  *
5583  * Description: Performs system power-up operations..
5584  *
5585  * Return Code: DDI_SUCCESS
5586  *		DDI_FAILURE
5587  *
5588  *     Context: Kernel thread context
5589  */
5590 
5591 static int
5592 sd_ddi_resume(dev_info_t *devi)
5593 {
5594 	struct	sd_lun	*un;
5595 
5596 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
5597 	if (un == NULL) {
5598 		return (DDI_FAILURE);
5599 	}
5600 
5601 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
5602 
5603 	mutex_enter(SD_MUTEX(un));
5604 	Restore_state(un);
5605 
5606 	/*
5607 	 * Restore the state which was saved to give the
5608 	 * the right state in un_last_state
5609 	 */
5610 	un->un_last_state = un->un_save_state;
5611 	/*
5612 	 * Note: throttle comes back at full.
5613 	 * Also note: this MUST be done before calling pm_raise_power
5614 	 * otherwise the system can get hung in biowait. The scenario where
5615 	 * this'll happen is under cpr suspend. Writing of the system
5616 	 * state goes through sddump, which writes 0 to un_throttle. If
5617 	 * writing the system state then fails, example if the partition is
5618 	 * too small, then cpr attempts a resume. If throttle isn't restored
5619 	 * from the saved value until after calling pm_raise_power then
5620 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
5621 	 * in biowait.
5622 	 */
5623 	un->un_throttle = un->un_saved_throttle;
5624 
5625 	/*
5626 	 * The chance of failure is very rare as the only command done in power
5627 	 * entry point is START command when you transition from 0->1 or
5628 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
5629 	 * which suspend was done. Ignore the return value as the resume should
5630 	 * not be failed. In the case of removable media the media need not be
5631 	 * inserted and hence there is a chance that raise power will fail with
5632 	 * media not present.
5633 	 */
5634 	if (un->un_f_attach_spinup) {
5635 		mutex_exit(SD_MUTEX(un));
5636 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
5637 		mutex_enter(SD_MUTEX(un));
5638 	}
5639 
5640 	/*
5641 	 * Don't broadcast to the suspend cv and therefore possibly
5642 	 * start I/O until after power has been restored.
5643 	 */
5644 	cv_broadcast(&un->un_suspend_cv);
5645 	cv_broadcast(&un->un_state_cv);
5646 
5647 	/* restart thread */
5648 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
5649 		scsi_watch_resume(un->un_swr_token);
5650 	}
5651 
5652 #if (defined(__fibre))
5653 	if (un->un_f_is_fibre == TRUE) {
5654 		/*
5655 		 * Add callbacks for insert and remove events
5656 		 */
5657 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
5658 			sd_init_event_callbacks(un);
5659 		}
5660 	}
5661 #endif
5662 
5663 	/*
5664 	 * Transport any pending commands to the target.
5665 	 *
5666 	 * If this is a low-activity device commands in queue will have to wait
5667 	 * until new commands come in, which may take awhile. Also, we
5668 	 * specifically don't check un_ncmds_in_transport because we know that
5669 	 * there really are no commands in progress after the unit was
5670 	 * suspended and we could have reached the throttle level, been
5671 	 * suspended, and have no new commands coming in for awhile. Highly
5672 	 * unlikely, but so is the low-activity disk scenario.
5673 	 */
5674 	ddi_xbuf_dispatch(un->un_xbuf_attr);
5675 
5676 	sd_start_cmds(un, NULL);
5677 	mutex_exit(SD_MUTEX(un));
5678 
5679 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
5680 
5681 	return (DDI_SUCCESS);
5682 }
5683 
5684 
5685 /*
5686  *    Function: sd_ddi_pm_resume
5687  *
5688  * Description: Set the drive state to powered on.
5689  *		Someone else is required to actually change the drive
5690  *		power level.
5691  *
5692  *   Arguments: un - driver soft state (unit) structure
5693  *
5694  * Return Code: DDI_SUCCESS
5695  *
5696  *     Context: Kernel thread context
5697  */
5698 
5699 static int
5700 sd_ddi_pm_resume(struct sd_lun *un)
5701 {
5702 	ASSERT(un != NULL);
5703 
5704 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5705 	mutex_enter(SD_MUTEX(un));
5706 	un->un_power_level = SD_SPINDLE_ON;
5707 
5708 	ASSERT(!mutex_owned(&un->un_pm_mutex));
5709 	mutex_enter(&un->un_pm_mutex);
5710 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
5711 		un->un_pm_count++;
5712 		ASSERT(un->un_pm_count == 0);
5713 		/*
5714 		 * Note: no longer do the cv_broadcast on un_suspend_cv. The
5715 		 * un_suspend_cv is for a system resume, not a power management
5716 		 * device resume. (4297749)
5717 		 *	 cv_broadcast(&un->un_suspend_cv);
5718 		 */
5719 	}
5720 	mutex_exit(&un->un_pm_mutex);
5721 	mutex_exit(SD_MUTEX(un));
5722 
5723 	return (DDI_SUCCESS);
5724 }
5725 
5726 
5727 /*
5728  *    Function: sd_pm_idletimeout_handler
5729  *
5730  * Description: A timer routine that's active only while a device is busy.
5731  *		The purpose is to extend slightly the pm framework's busy
5732  *		view of the device to prevent busy/idle thrashing for
5733  *		back-to-back commands. Do this by comparing the current time
5734  *		to the time at which the last command completed and when the
5735  *		difference is greater than sd_pm_idletime, call
5736  *		pm_idle_component. In addition to indicating idle to the pm
5737  *		framework, update the chain type to again use the internal pm
5738  *		layers of the driver.
5739  *
5740  *   Arguments: arg - driver soft state (unit) structure
5741  *
5742  *     Context: Executes in a timeout(9F) thread context
5743  */
5744 
5745 static void
5746 sd_pm_idletimeout_handler(void *arg)
5747 {
5748 	struct sd_lun *un = arg;
5749 
5750 	time_t	now;
5751 
5752 	mutex_enter(&sd_detach_mutex);
5753 	if (un->un_detach_count != 0) {
5754 		/* Abort if the instance is detaching */
5755 		mutex_exit(&sd_detach_mutex);
5756 		return;
5757 	}
5758 	mutex_exit(&sd_detach_mutex);
5759 
5760 	now = ddi_get_time();
5761 	/*
5762 	 * Grab both mutexes, in the proper order, since we're accessing
5763 	 * both PM and softstate variables.
5764 	 */
5765 	mutex_enter(SD_MUTEX(un));
5766 	mutex_enter(&un->un_pm_mutex);
5767 	if (((now - un->un_pm_idle_time) > sd_pm_idletime) &&
5768 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
5769 		/*
5770 		 * Update the chain types.
5771 		 * This takes affect on the next new command received.
5772 		 */
5773 		if (un->un_f_non_devbsize_supported) {
5774 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
5775 		} else {
5776 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
5777 		}
5778 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
5779 
5780 		SD_TRACE(SD_LOG_IO_PM, un,
5781 		    "sd_pm_idletimeout_handler: idling device\n");
5782 		(void) pm_idle_component(SD_DEVINFO(un), 0);
5783 		un->un_pm_idle_timeid = NULL;
5784 	} else {
5785 		un->un_pm_idle_timeid =
5786 		    timeout(sd_pm_idletimeout_handler, un,
5787 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
5788 	}
5789 	mutex_exit(&un->un_pm_mutex);
5790 	mutex_exit(SD_MUTEX(un));
5791 }
5792 
5793 
5794 /*
5795  *    Function: sd_pm_timeout_handler
5796  *
5797  * Description: Callback to tell framework we are idle.
5798  *
5799  *     Context: timeout(9f) thread context.
5800  */
5801 
5802 static void
5803 sd_pm_timeout_handler(void *arg)
5804 {
5805 	struct sd_lun *un = arg;
5806 
5807 	(void) pm_idle_component(SD_DEVINFO(un), 0);
5808 	mutex_enter(&un->un_pm_mutex);
5809 	un->un_pm_timeid = NULL;
5810 	mutex_exit(&un->un_pm_mutex);
5811 }
5812 
5813 
5814 /*
5815  *    Function: sdpower
5816  *
5817  * Description: PM entry point.
5818  *
5819  * Return Code: DDI_SUCCESS
5820  *		DDI_FAILURE
5821  *
5822  *     Context: Kernel thread context
5823  */
5824 
5825 static int
5826 sdpower(dev_info_t *devi, int component, int level)
5827 {
5828 	struct sd_lun	*un;
5829 	int		instance;
5830 	int		rval = DDI_SUCCESS;
5831 	uint_t		i, log_page_size, maxcycles, ncycles;
5832 	uchar_t		*log_page_data;
5833 	int		log_sense_page;
5834 	int		medium_present;
5835 	time_t		intvlp;
5836 	dev_t		dev;
5837 	struct pm_trans_data	sd_pm_tran_data;
5838 	uchar_t		save_state;
5839 	int		sval;
5840 	uchar_t		state_before_pm;
5841 	int		got_semaphore_here;
5842 
5843 	instance = ddi_get_instance(devi);
5844 
5845 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
5846 	    (SD_SPINDLE_OFF > level) || (level > SD_SPINDLE_ON) ||
5847 	    component != 0) {
5848 		return (DDI_FAILURE);
5849 	}
5850 
5851 	dev = sd_make_device(SD_DEVINFO(un));
5852 
5853 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
5854 
5855 	/*
5856 	 * Must synchronize power down with close.
5857 	 * Attempt to decrement/acquire the open/close semaphore,
5858 	 * but do NOT wait on it. If it's not greater than zero,
5859 	 * ie. it can't be decremented without waiting, then
5860 	 * someone else, either open or close, already has it
5861 	 * and the try returns 0. Use that knowledge here to determine
5862 	 * if it's OK to change the device power level.
5863 	 * Also, only increment it on exit if it was decremented, ie. gotten,
5864 	 * here.
5865 	 */
5866 	got_semaphore_here = sema_tryp(&un->un_semoclose);
5867 
5868 	mutex_enter(SD_MUTEX(un));
5869 
5870 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
5871 	    un->un_ncmds_in_driver);
5872 
5873 	/*
5874 	 * If un_ncmds_in_driver is non-zero it indicates commands are
5875 	 * already being processed in the driver, or if the semaphore was
5876 	 * not gotten here it indicates an open or close is being processed.
5877 	 * At the same time somebody is requesting to go low power which
5878 	 * can't happen, therefore we need to return failure.
5879 	 */
5880 	if ((level == SD_SPINDLE_OFF) &&
5881 	    ((un->un_ncmds_in_driver != 0) || (got_semaphore_here == 0))) {
5882 		mutex_exit(SD_MUTEX(un));
5883 
5884 		if (got_semaphore_here != 0) {
5885 			sema_v(&un->un_semoclose);
5886 		}
5887 		SD_TRACE(SD_LOG_IO_PM, un,
5888 		    "sdpower: exit, device has queued cmds.\n");
5889 		return (DDI_FAILURE);
5890 	}
5891 
5892 	/*
5893 	 * if it is OFFLINE that means the disk is completely dead
5894 	 * in our case we have to put the disk in on or off by sending commands
5895 	 * Of course that will fail anyway so return back here.
5896 	 *
5897 	 * Power changes to a device that's OFFLINE or SUSPENDED
5898 	 * are not allowed.
5899 	 */
5900 	if ((un->un_state == SD_STATE_OFFLINE) ||
5901 	    (un->un_state == SD_STATE_SUSPENDED)) {
5902 		mutex_exit(SD_MUTEX(un));
5903 
5904 		if (got_semaphore_here != 0) {
5905 			sema_v(&un->un_semoclose);
5906 		}
5907 		SD_TRACE(SD_LOG_IO_PM, un,
5908 		    "sdpower: exit, device is off-line.\n");
5909 		return (DDI_FAILURE);
5910 	}
5911 
5912 	/*
5913 	 * Change the device's state to indicate it's power level
5914 	 * is being changed. Do this to prevent a power off in the
5915 	 * middle of commands, which is especially bad on devices
5916 	 * that are really powered off instead of just spun down.
5917 	 */
5918 	state_before_pm = un->un_state;
5919 	un->un_state = SD_STATE_PM_CHANGING;
5920 
5921 	mutex_exit(SD_MUTEX(un));
5922 
5923 	/*
5924 	 * If "pm-capable" property is set to TRUE by HBA drivers,
5925 	 * bypass the following checking, otherwise, check the log
5926 	 * sense information for this device
5927 	 */
5928 	if ((level == SD_SPINDLE_OFF) && un->un_f_log_sense_supported) {
5929 		/*
5930 		 * Get the log sense information to understand whether the
5931 		 * the powercycle counts have gone beyond the threshhold.
5932 		 */
5933 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5934 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5935 
5936 		mutex_enter(SD_MUTEX(un));
5937 		log_sense_page = un->un_start_stop_cycle_page;
5938 		mutex_exit(SD_MUTEX(un));
5939 
5940 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
5941 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
5942 #ifdef	SDDEBUG
5943 		if (sd_force_pm_supported) {
5944 			/* Force a successful result */
5945 			rval = 0;
5946 		}
5947 #endif
5948 		if (rval != 0) {
5949 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5950 			    "Log Sense Failed\n");
5951 			kmem_free(log_page_data, log_page_size);
5952 			/* Cannot support power management on those drives */
5953 
5954 			if (got_semaphore_here != 0) {
5955 				sema_v(&un->un_semoclose);
5956 			}
5957 			/*
5958 			 * On exit put the state back to it's original value
5959 			 * and broadcast to anyone waiting for the power
5960 			 * change completion.
5961 			 */
5962 			mutex_enter(SD_MUTEX(un));
5963 			un->un_state = state_before_pm;
5964 			cv_broadcast(&un->un_suspend_cv);
5965 			mutex_exit(SD_MUTEX(un));
5966 			SD_TRACE(SD_LOG_IO_PM, un,
5967 			    "sdpower: exit, Log Sense Failed.\n");
5968 			return (DDI_FAILURE);
5969 		}
5970 
5971 		/*
5972 		 * From the page data - Convert the essential information to
5973 		 * pm_trans_data
5974 		 */
5975 		maxcycles =
5976 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
5977 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
5978 
5979 		sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
5980 
5981 		ncycles =
5982 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
5983 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
5984 
5985 		sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
5986 
5987 		for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
5988 			sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
5989 			    log_page_data[8+i];
5990 		}
5991 
5992 		kmem_free(log_page_data, log_page_size);
5993 
5994 		/*
5995 		 * Call pm_trans_check routine to get the Ok from
5996 		 * the global policy
5997 		 */
5998 
5999 		sd_pm_tran_data.format = DC_SCSI_FORMAT;
6000 		sd_pm_tran_data.un.scsi_cycles.flag = 0;
6001 
6002 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
6003 #ifdef	SDDEBUG
6004 		if (sd_force_pm_supported) {
6005 			/* Force a successful result */
6006 			rval = 1;
6007 		}
6008 #endif
6009 		switch (rval) {
6010 		case 0:
6011 			/*
6012 			 * Not Ok to Power cycle or error in parameters passed
6013 			 * Would have given the advised time to consider power
6014 			 * cycle. Based on the new intvlp parameter we are
6015 			 * supposed to pretend we are busy so that pm framework
6016 			 * will never call our power entry point. Because of
6017 			 * that install a timeout handler and wait for the
6018 			 * recommended time to elapse so that power management
6019 			 * can be effective again.
6020 			 *
6021 			 * To effect this behavior, call pm_busy_component to
6022 			 * indicate to the framework this device is busy.
6023 			 * By not adjusting un_pm_count the rest of PM in
6024 			 * the driver will function normally, and independant
6025 			 * of this but because the framework is told the device
6026 			 * is busy it won't attempt powering down until it gets
6027 			 * a matching idle. The timeout handler sends this.
6028 			 * Note: sd_pm_entry can't be called here to do this
6029 			 * because sdpower may have been called as a result
6030 			 * of a call to pm_raise_power from within sd_pm_entry.
6031 			 *
6032 			 * If a timeout handler is already active then
6033 			 * don't install another.
6034 			 */
6035 			mutex_enter(&un->un_pm_mutex);
6036 			if (un->un_pm_timeid == NULL) {
6037 				un->un_pm_timeid =
6038 				    timeout(sd_pm_timeout_handler,
6039 				    un, intvlp * drv_usectohz(1000000));
6040 				mutex_exit(&un->un_pm_mutex);
6041 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6042 			} else {
6043 				mutex_exit(&un->un_pm_mutex);
6044 			}
6045 			if (got_semaphore_here != 0) {
6046 				sema_v(&un->un_semoclose);
6047 			}
6048 			/*
6049 			 * On exit put the state back to it's original value
6050 			 * and broadcast to anyone waiting for the power
6051 			 * change completion.
6052 			 */
6053 			mutex_enter(SD_MUTEX(un));
6054 			un->un_state = state_before_pm;
6055 			cv_broadcast(&un->un_suspend_cv);
6056 			mutex_exit(SD_MUTEX(un));
6057 
6058 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6059 			    "trans check Failed, not ok to power cycle.\n");
6060 			return (DDI_FAILURE);
6061 
6062 		case -1:
6063 			if (got_semaphore_here != 0) {
6064 				sema_v(&un->un_semoclose);
6065 			}
6066 			/*
6067 			 * On exit put the state back to it's original value
6068 			 * and broadcast to anyone waiting for the power
6069 			 * change completion.
6070 			 */
6071 			mutex_enter(SD_MUTEX(un));
6072 			un->un_state = state_before_pm;
6073 			cv_broadcast(&un->un_suspend_cv);
6074 			mutex_exit(SD_MUTEX(un));
6075 			SD_TRACE(SD_LOG_IO_PM, un,
6076 			    "sdpower: exit, trans check command Failed.\n");
6077 			return (DDI_FAILURE);
6078 		}
6079 	}
6080 
6081 	if (level == SD_SPINDLE_OFF) {
6082 		/*
6083 		 * Save the last state... if the STOP FAILS we need it
6084 		 * for restoring
6085 		 */
6086 		mutex_enter(SD_MUTEX(un));
6087 		save_state = un->un_last_state;
6088 		/*
6089 		 * There must not be any cmds. getting processed
6090 		 * in the driver when we get here. Power to the
6091 		 * device is potentially going off.
6092 		 */
6093 		ASSERT(un->un_ncmds_in_driver == 0);
6094 		mutex_exit(SD_MUTEX(un));
6095 
6096 		/*
6097 		 * For now suspend the device completely before spindle is
6098 		 * turned off
6099 		 */
6100 		if ((rval = sd_ddi_pm_suspend(un)) == DDI_FAILURE) {
6101 			if (got_semaphore_here != 0) {
6102 				sema_v(&un->un_semoclose);
6103 			}
6104 			/*
6105 			 * On exit put the state back to it's original value
6106 			 * and broadcast to anyone waiting for the power
6107 			 * change completion.
6108 			 */
6109 			mutex_enter(SD_MUTEX(un));
6110 			un->un_state = state_before_pm;
6111 			cv_broadcast(&un->un_suspend_cv);
6112 			mutex_exit(SD_MUTEX(un));
6113 			SD_TRACE(SD_LOG_IO_PM, un,
6114 			    "sdpower: exit, PM suspend Failed.\n");
6115 			return (DDI_FAILURE);
6116 		}
6117 	}
6118 
6119 	/*
6120 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6121 	 * close, or strategy. Dump no long uses this routine, it uses it's
6122 	 * own code so it can be done in polled mode.
6123 	 */
6124 
6125 	medium_present = TRUE;
6126 
6127 	/*
6128 	 * When powering up, issue a TUR in case the device is at unit
6129 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6130 	 * a deadlock on un_pm_busy_cv will occur.
6131 	 */
6132 	if (level == SD_SPINDLE_ON) {
6133 		(void) sd_send_scsi_TEST_UNIT_READY(un,
6134 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6135 	}
6136 
6137 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
6138 	    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
6139 
6140 	sval = sd_send_scsi_START_STOP_UNIT(un,
6141 	    ((level == SD_SPINDLE_ON) ? SD_TARGET_START : SD_TARGET_STOP),
6142 	    SD_PATH_DIRECT);
6143 	/* Command failed, check for media present. */
6144 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
6145 		medium_present = FALSE;
6146 	}
6147 
6148 	/*
6149 	 * The conditions of interest here are:
6150 	 *   if a spindle off with media present fails,
6151 	 *	then restore the state and return an error.
6152 	 *   else if a spindle on fails,
6153 	 *	then return an error (there's no state to restore).
6154 	 * In all other cases we setup for the new state
6155 	 * and return success.
6156 	 */
6157 	switch (level) {
6158 	case SD_SPINDLE_OFF:
6159 		if ((medium_present == TRUE) && (sval != 0)) {
6160 			/* The stop command from above failed */
6161 			rval = DDI_FAILURE;
6162 			/*
6163 			 * The stop command failed, and we have media
6164 			 * present. Put the level back by calling the
6165 			 * sd_pm_resume() and set the state back to
6166 			 * it's previous value.
6167 			 */
6168 			(void) sd_ddi_pm_resume(un);
6169 			mutex_enter(SD_MUTEX(un));
6170 			un->un_last_state = save_state;
6171 			mutex_exit(SD_MUTEX(un));
6172 			break;
6173 		}
6174 		/*
6175 		 * The stop command from above succeeded.
6176 		 */
6177 		if (un->un_f_monitor_media_state) {
6178 			/*
6179 			 * Terminate watch thread in case of removable media
6180 			 * devices going into low power state. This is as per
6181 			 * the requirements of pm framework, otherwise commands
6182 			 * will be generated for the device (through watch
6183 			 * thread), even when the device is in low power state.
6184 			 */
6185 			mutex_enter(SD_MUTEX(un));
6186 			un->un_f_watcht_stopped = FALSE;
6187 			if (un->un_swr_token != NULL) {
6188 				opaque_t temp_token = un->un_swr_token;
6189 				un->un_f_watcht_stopped = TRUE;
6190 				un->un_swr_token = NULL;
6191 				mutex_exit(SD_MUTEX(un));
6192 				(void) scsi_watch_request_terminate(temp_token,
6193 				    SCSI_WATCH_TERMINATE_WAIT);
6194 			} else {
6195 				mutex_exit(SD_MUTEX(un));
6196 			}
6197 		}
6198 		break;
6199 
6200 	default:	/* The level requested is spindle on... */
6201 		/*
6202 		 * Legacy behavior: return success on a failed spinup
6203 		 * if there is no media in the drive.
6204 		 * Do this by looking at medium_present here.
6205 		 */
6206 		if ((sval != 0) && medium_present) {
6207 			/* The start command from above failed */
6208 			rval = DDI_FAILURE;
6209 			break;
6210 		}
6211 		/*
6212 		 * The start command from above succeeded
6213 		 * Resume the devices now that we have
6214 		 * started the disks
6215 		 */
6216 		(void) sd_ddi_pm_resume(un);
6217 
6218 		/*
6219 		 * Resume the watch thread since it was suspended
6220 		 * when the device went into low power mode.
6221 		 */
6222 		if (un->un_f_monitor_media_state) {
6223 			mutex_enter(SD_MUTEX(un));
6224 			if (un->un_f_watcht_stopped == TRUE) {
6225 				opaque_t temp_token;
6226 
6227 				un->un_f_watcht_stopped = FALSE;
6228 				mutex_exit(SD_MUTEX(un));
6229 				temp_token = scsi_watch_request_submit(
6230 				    SD_SCSI_DEVP(un),
6231 				    sd_check_media_time,
6232 				    SENSE_LENGTH, sd_media_watch_cb,
6233 				    (caddr_t)dev);
6234 				mutex_enter(SD_MUTEX(un));
6235 				un->un_swr_token = temp_token;
6236 			}
6237 			mutex_exit(SD_MUTEX(un));
6238 		}
6239 	}
6240 	if (got_semaphore_here != 0) {
6241 		sema_v(&un->un_semoclose);
6242 	}
6243 	/*
6244 	 * On exit put the state back to it's original value
6245 	 * and broadcast to anyone waiting for the power
6246 	 * change completion.
6247 	 */
6248 	mutex_enter(SD_MUTEX(un));
6249 	un->un_state = state_before_pm;
6250 	cv_broadcast(&un->un_suspend_cv);
6251 	mutex_exit(SD_MUTEX(un));
6252 
6253 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
6254 
6255 	return (rval);
6256 }
6257 
6258 
6259 
6260 /*
6261  *    Function: sdattach
6262  *
6263  * Description: Driver's attach(9e) entry point function.
6264  *
6265  *   Arguments: devi - opaque device info handle
6266  *		cmd  - attach  type
6267  *
6268  * Return Code: DDI_SUCCESS
6269  *		DDI_FAILURE
6270  *
6271  *     Context: Kernel thread context
6272  */
6273 
6274 static int
6275 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
6276 {
6277 	switch (cmd) {
6278 	case DDI_ATTACH:
6279 		return (sd_unit_attach(devi));
6280 	case DDI_RESUME:
6281 		return (sd_ddi_resume(devi));
6282 	default:
6283 		break;
6284 	}
6285 	return (DDI_FAILURE);
6286 }
6287 
6288 
6289 /*
6290  *    Function: sddetach
6291  *
6292  * Description: Driver's detach(9E) entry point function.
6293  *
6294  *   Arguments: devi - opaque device info handle
6295  *		cmd  - detach  type
6296  *
6297  * Return Code: DDI_SUCCESS
6298  *		DDI_FAILURE
6299  *
6300  *     Context: Kernel thread context
6301  */
6302 
6303 static int
6304 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
6305 {
6306 	switch (cmd) {
6307 	case DDI_DETACH:
6308 		return (sd_unit_detach(devi));
6309 	case DDI_SUSPEND:
6310 		return (sd_ddi_suspend(devi));
6311 	default:
6312 		break;
6313 	}
6314 	return (DDI_FAILURE);
6315 }
6316 
6317 
6318 /*
6319  *     Function: sd_sync_with_callback
6320  *
6321  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
6322  *		 state while the callback routine is active.
6323  *
6324  *    Arguments: un: softstate structure for the instance
6325  *
6326  *	Context: Kernel thread context
6327  */
6328 
6329 static void
6330 sd_sync_with_callback(struct sd_lun *un)
6331 {
6332 	ASSERT(un != NULL);
6333 
6334 	mutex_enter(SD_MUTEX(un));
6335 
6336 	ASSERT(un->un_in_callback >= 0);
6337 
6338 	while (un->un_in_callback > 0) {
6339 		mutex_exit(SD_MUTEX(un));
6340 		delay(2);
6341 		mutex_enter(SD_MUTEX(un));
6342 	}
6343 
6344 	mutex_exit(SD_MUTEX(un));
6345 }
6346 
6347 /*
6348  *    Function: sd_unit_attach
6349  *
6350  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
6351  *		the soft state structure for the device and performs
6352  *		all necessary structure and device initializations.
6353  *
6354  *   Arguments: devi: the system's dev_info_t for the device.
6355  *
6356  * Return Code: DDI_SUCCESS if attach is successful.
6357  *		DDI_FAILURE if any part of the attach fails.
6358  *
6359  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
6360  *		Kernel thread context only.  Can sleep.
6361  */
6362 
6363 static int
6364 sd_unit_attach(dev_info_t *devi)
6365 {
6366 	struct	scsi_device	*devp;
6367 	struct	sd_lun		*un;
6368 	char			*variantp;
6369 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
6370 	int	instance;
6371 	int	rval;
6372 	int	wc_enabled;
6373 	int	tgt;
6374 	uint64_t	capacity;
6375 	uint_t		lbasize = 0;
6376 	dev_info_t	*pdip = ddi_get_parent(devi);
6377 	int		offbyone = 0;
6378 	int		geom_label_valid = 0;
6379 #if defined(__sparc)
6380 	int		max_xfer_size;
6381 #endif
6382 
6383 	/*
6384 	 * Retrieve the target driver's private data area. This was set
6385 	 * up by the HBA.
6386 	 */
6387 	devp = ddi_get_driver_private(devi);
6388 
6389 	/*
6390 	 * Retrieve the target ID of the device.
6391 	 */
6392 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
6393 	    SCSI_ADDR_PROP_TARGET, -1);
6394 
6395 	/*
6396 	 * Since we have no idea what state things were left in by the last
6397 	 * user of the device, set up some 'default' settings, ie. turn 'em
6398 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
6399 	 * Do this before the scsi_probe, which sends an inquiry.
6400 	 * This is a fix for bug (4430280).
6401 	 * Of special importance is wide-xfer. The drive could have been left
6402 	 * in wide transfer mode by the last driver to communicate with it,
6403 	 * this includes us. If that's the case, and if the following is not
6404 	 * setup properly or we don't re-negotiate with the drive prior to
6405 	 * transferring data to/from the drive, it causes bus parity errors,
6406 	 * data overruns, and unexpected interrupts. This first occurred when
6407 	 * the fix for bug (4378686) was made.
6408 	 */
6409 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
6410 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
6411 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
6412 
6413 	/*
6414 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
6415 	 * on a target. Setting it per lun instance actually sets the
6416 	 * capability of this target, which affects those luns already
6417 	 * attached on the same target. So during attach, we can only disable
6418 	 * this capability only when no other lun has been attached on this
6419 	 * target. By doing this, we assume a target has the same tagged-qing
6420 	 * capability for every lun. The condition can be removed when HBA
6421 	 * is changed to support per lun based tagged-qing capability.
6422 	 */
6423 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
6424 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
6425 	}
6426 
6427 	/*
6428 	 * Use scsi_probe() to issue an INQUIRY command to the device.
6429 	 * This call will allocate and fill in the scsi_inquiry structure
6430 	 * and point the sd_inq member of the scsi_device structure to it.
6431 	 * If the attach succeeds, then this memory will not be de-allocated
6432 	 * (via scsi_unprobe()) until the instance is detached.
6433 	 */
6434 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
6435 		goto probe_failed;
6436 	}
6437 
6438 	/*
6439 	 * Check the device type as specified in the inquiry data and
6440 	 * claim it if it is of a type that we support.
6441 	 */
6442 	switch (devp->sd_inq->inq_dtype) {
6443 	case DTYPE_DIRECT:
6444 		break;
6445 	case DTYPE_RODIRECT:
6446 		break;
6447 	case DTYPE_OPTICAL:
6448 		break;
6449 	case DTYPE_NOTPRESENT:
6450 	default:
6451 		/* Unsupported device type; fail the attach. */
6452 		goto probe_failed;
6453 	}
6454 
6455 	/*
6456 	 * Allocate the soft state structure for this unit.
6457 	 *
6458 	 * We rely upon this memory being set to all zeroes by
6459 	 * ddi_soft_state_zalloc().  We assume that any member of the
6460 	 * soft state structure that is not explicitly initialized by
6461 	 * this routine will have a value of zero.
6462 	 */
6463 	instance = ddi_get_instance(devp->sd_dev);
6464 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
6465 		goto probe_failed;
6466 	}
6467 
6468 	/*
6469 	 * Retrieve a pointer to the newly-allocated soft state.
6470 	 *
6471 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
6472 	 * was successful, unless something has gone horribly wrong and the
6473 	 * ddi's soft state internals are corrupt (in which case it is
6474 	 * probably better to halt here than just fail the attach....)
6475 	 */
6476 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
6477 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
6478 		    instance);
6479 		/*NOTREACHED*/
6480 	}
6481 
6482 	/*
6483 	 * Link the back ptr of the driver soft state to the scsi_device
6484 	 * struct for this lun.
6485 	 * Save a pointer to the softstate in the driver-private area of
6486 	 * the scsi_device struct.
6487 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
6488 	 * we first set un->un_sd below.
6489 	 */
6490 	un->un_sd = devp;
6491 	devp->sd_private = (opaque_t)un;
6492 
6493 	/*
6494 	 * The following must be after devp is stored in the soft state struct.
6495 	 */
6496 #ifdef SDDEBUG
6497 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6498 	    "%s_unit_attach: un:0x%p instance:%d\n",
6499 	    ddi_driver_name(devi), un, instance);
6500 #endif
6501 
6502 	/*
6503 	 * Set up the device type and node type (for the minor nodes).
6504 	 * By default we assume that the device can at least support the
6505 	 * Common Command Set. Call it a CD-ROM if it reports itself
6506 	 * as a RODIRECT device.
6507 	 */
6508 	switch (devp->sd_inq->inq_dtype) {
6509 	case DTYPE_RODIRECT:
6510 		un->un_node_type = DDI_NT_CD_CHAN;
6511 		un->un_ctype	 = CTYPE_CDROM;
6512 		break;
6513 	case DTYPE_OPTICAL:
6514 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6515 		un->un_ctype	 = CTYPE_ROD;
6516 		break;
6517 	default:
6518 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6519 		un->un_ctype	 = CTYPE_CCS;
6520 		break;
6521 	}
6522 
6523 	/*
6524 	 * Try to read the interconnect type from the HBA.
6525 	 *
6526 	 * Note: This driver is currently compiled as two binaries, a parallel
6527 	 * scsi version (sd) and a fibre channel version (ssd). All functional
6528 	 * differences are determined at compile time. In the future a single
6529 	 * binary will be provided and the inteconnect type will be used to
6530 	 * differentiate between fibre and parallel scsi behaviors. At that time
6531 	 * it will be necessary for all fibre channel HBAs to support this
6532 	 * property.
6533 	 *
6534 	 * set un_f_is_fiber to TRUE ( default fiber )
6535 	 */
6536 	un->un_f_is_fibre = TRUE;
6537 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
6538 	case INTERCONNECT_SSA:
6539 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
6540 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6541 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
6542 		break;
6543 	case INTERCONNECT_PARALLEL:
6544 		un->un_f_is_fibre = FALSE;
6545 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
6546 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6547 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
6548 		break;
6549 	case INTERCONNECT_SATA:
6550 		un->un_f_is_fibre = FALSE;
6551 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
6552 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6553 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
6554 		break;
6555 	case INTERCONNECT_FIBRE:
6556 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
6557 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6558 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
6559 		break;
6560 	case INTERCONNECT_FABRIC:
6561 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
6562 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
6563 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6564 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
6565 		break;
6566 	default:
6567 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
6568 		/*
6569 		 * The HBA does not support the "interconnect-type" property
6570 		 * (or did not provide a recognized type).
6571 		 *
6572 		 * Note: This will be obsoleted when a single fibre channel
6573 		 * and parallel scsi driver is delivered. In the meantime the
6574 		 * interconnect type will be set to the platform default.If that
6575 		 * type is not parallel SCSI, it means that we should be
6576 		 * assuming "ssd" semantics. However, here this also means that
6577 		 * the FC HBA is not supporting the "interconnect-type" property
6578 		 * like we expect it to, so log this occurrence.
6579 		 */
6580 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
6581 		if (!SD_IS_PARALLEL_SCSI(un)) {
6582 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6583 			    "sd_unit_attach: un:0x%p Assuming "
6584 			    "INTERCONNECT_FIBRE\n", un);
6585 		} else {
6586 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6587 			    "sd_unit_attach: un:0x%p Assuming "
6588 			    "INTERCONNECT_PARALLEL\n", un);
6589 			un->un_f_is_fibre = FALSE;
6590 		}
6591 #else
6592 		/*
6593 		 * Note: This source will be implemented when a single fibre
6594 		 * channel and parallel scsi driver is delivered. The default
6595 		 * will be to assume that if a device does not support the
6596 		 * "interconnect-type" property it is a parallel SCSI HBA and
6597 		 * we will set the interconnect type for parallel scsi.
6598 		 */
6599 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
6600 		un->un_f_is_fibre = FALSE;
6601 #endif
6602 		break;
6603 	}
6604 
6605 	if (un->un_f_is_fibre == TRUE) {
6606 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
6607 		    SCSI_VERSION_3) {
6608 			switch (un->un_interconnect_type) {
6609 			case SD_INTERCONNECT_FIBRE:
6610 			case SD_INTERCONNECT_SSA:
6611 				un->un_node_type = DDI_NT_BLOCK_WWN;
6612 				break;
6613 			default:
6614 				break;
6615 			}
6616 		}
6617 	}
6618 
6619 	/*
6620 	 * Initialize the Request Sense command for the target
6621 	 */
6622 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
6623 		goto alloc_rqs_failed;
6624 	}
6625 
6626 	/*
6627 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
6628 	 * with separate binary for sd and ssd.
6629 	 *
6630 	 * x86 has 1 binary, un_retry_count is set base on connection type.
6631 	 * The hardcoded values will go away when Sparc uses 1 binary
6632 	 * for sd and ssd.  This hardcoded values need to match
6633 	 * SD_RETRY_COUNT in sddef.h
6634 	 * The value used is base on interconnect type.
6635 	 * fibre = 3, parallel = 5
6636 	 */
6637 #if defined(__i386) || defined(__amd64)
6638 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
6639 #else
6640 	un->un_retry_count = SD_RETRY_COUNT;
6641 #endif
6642 
6643 	/*
6644 	 * Set the per disk retry count to the default number of retries
6645 	 * for disks and CDROMs. This value can be overridden by the
6646 	 * disk property list or an entry in sd.conf.
6647 	 */
6648 	un->un_notready_retry_count =
6649 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
6650 	    : DISK_NOT_READY_RETRY_COUNT(un);
6651 
6652 	/*
6653 	 * Set the busy retry count to the default value of un_retry_count.
6654 	 * This can be overridden by entries in sd.conf or the device
6655 	 * config table.
6656 	 */
6657 	un->un_busy_retry_count = un->un_retry_count;
6658 
6659 	/*
6660 	 * Init the reset threshold for retries.  This number determines
6661 	 * how many retries must be performed before a reset can be issued
6662 	 * (for certain error conditions). This can be overridden by entries
6663 	 * in sd.conf or the device config table.
6664 	 */
6665 	un->un_reset_retry_count = (un->un_retry_count / 2);
6666 
6667 	/*
6668 	 * Set the victim_retry_count to the default un_retry_count
6669 	 */
6670 	un->un_victim_retry_count = (2 * un->un_retry_count);
6671 
6672 	/*
6673 	 * Set the reservation release timeout to the default value of
6674 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
6675 	 * device config table.
6676 	 */
6677 	un->un_reserve_release_time = 5;
6678 
6679 	/*
6680 	 * Set up the default maximum transfer size. Note that this may
6681 	 * get updated later in the attach, when setting up default wide
6682 	 * operations for disks.
6683 	 */
6684 #if defined(__i386) || defined(__amd64)
6685 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
6686 	un->un_partial_dma_supported = 1;
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 	 * Adjust the maximum transfer size. This is to fix
7004 	 * the problem of partial DMA support on SPARC. Some
7005 	 * HBA driver, like aac, has very small dma_attr_maxxfer
7006 	 * size, which requires partial DMA support on SPARC.
7007 	 * In the future the SPARC pci nexus driver may solve
7008 	 * the problem instead of this fix.
7009 	 */
7010 #if defined(__sparc)
7011 	max_xfer_size = scsi_ifgetcap(SD_ADDRESS(un), "dma-max", 1);
7012 	if ((max_xfer_size > 0) && (max_xfer_size < un->un_max_xfer_size)) {
7013 		un->un_max_xfer_size = max_xfer_size;
7014 		un->un_partial_dma_supported = 1;
7015 	}
7016 #endif
7017 
7018 	/*
7019 	 * Set PKT_DMA_PARTIAL flag.
7020 	 */
7021 	if (un->un_partial_dma_supported == 1) {
7022 		un->un_pkt_flags = PKT_DMA_PARTIAL;
7023 	} else {
7024 		un->un_pkt_flags = 0;
7025 	}
7026 
7027 	/*
7028 	 * At this point in the attach, we have enough info in the
7029 	 * soft state to be able to issue commands to the target.
7030 	 *
7031 	 * All command paths used below MUST issue their commands as
7032 	 * SD_PATH_DIRECT. This is important as intermediate layers
7033 	 * are not all initialized yet (such as PM).
7034 	 */
7035 
7036 	/*
7037 	 * Send a TEST UNIT READY command to the device. This should clear
7038 	 * any outstanding UNIT ATTENTION that may be present.
7039 	 *
7040 	 * Note: Don't check for success, just track if there is a reservation,
7041 	 * this is a throw away command to clear any unit attentions.
7042 	 *
7043 	 * Note: This MUST be the first command issued to the target during
7044 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
7045 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
7046 	 * with attempts at spinning up a device with no media.
7047 	 */
7048 	if (sd_send_scsi_TEST_UNIT_READY(un, SD_DONT_RETRY_TUR) == EACCES) {
7049 		reservation_flag = SD_TARGET_IS_RESERVED;
7050 	}
7051 
7052 	/*
7053 	 * If the device is NOT a removable media device, attempt to spin
7054 	 * it up (using the START_STOP_UNIT command) and read its capacity
7055 	 * (using the READ CAPACITY command).  Note, however, that either
7056 	 * of these could fail and in some cases we would continue with
7057 	 * the attach despite the failure (see below).
7058 	 */
7059 	if (un->un_f_descr_format_supported) {
7060 		switch (sd_spin_up_unit(un)) {
7061 		case 0:
7062 			/*
7063 			 * Spin-up was successful; now try to read the
7064 			 * capacity.  If successful then save the results
7065 			 * and mark the capacity & lbasize as valid.
7066 			 */
7067 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7068 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
7069 
7070 			switch (sd_send_scsi_READ_CAPACITY(un, &capacity,
7071 			    &lbasize, SD_PATH_DIRECT)) {
7072 			case 0: {
7073 				if (capacity > DK_MAX_BLOCKS) {
7074 #ifdef _LP64
7075 					if (capacity + 1 >
7076 					    SD_GROUP1_MAX_ADDRESS) {
7077 						/*
7078 						 * Enable descriptor format
7079 						 * sense data so that we can
7080 						 * get 64 bit sense data
7081 						 * fields.
7082 						 */
7083 						sd_enable_descr_sense(un);
7084 					}
7085 #else
7086 					/* 32-bit kernels can't handle this */
7087 					scsi_log(SD_DEVINFO(un),
7088 					    sd_label, CE_WARN,
7089 					    "disk has %llu blocks, which "
7090 					    "is too large for a 32-bit "
7091 					    "kernel", capacity);
7092 
7093 #if defined(__i386) || defined(__amd64)
7094 					/*
7095 					 * 1TB disk was treated as (1T - 512)B
7096 					 * in the past, so that it might have
7097 					 * valid VTOC and solaris partitions,
7098 					 * we have to allow it to continue to
7099 					 * work.
7100 					 */
7101 					if (capacity -1 > DK_MAX_BLOCKS)
7102 #endif
7103 					goto spinup_failed;
7104 #endif
7105 				}
7106 
7107 				/*
7108 				 * Here it's not necessary to check the case:
7109 				 * the capacity of the device is bigger than
7110 				 * what the max hba cdb can support. Because
7111 				 * sd_send_scsi_READ_CAPACITY will retrieve
7112 				 * the capacity by sending USCSI command, which
7113 				 * is constrained by the max hba cdb. Actually,
7114 				 * sd_send_scsi_READ_CAPACITY will return
7115 				 * EINVAL when using bigger cdb than required
7116 				 * cdb length. Will handle this case in
7117 				 * "case EINVAL".
7118 				 */
7119 
7120 				/*
7121 				 * The following relies on
7122 				 * sd_send_scsi_READ_CAPACITY never
7123 				 * returning 0 for capacity and/or lbasize.
7124 				 */
7125 				sd_update_block_info(un, lbasize, capacity);
7126 
7127 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7128 				    "sd_unit_attach: un:0x%p capacity = %ld "
7129 				    "blocks; lbasize= %ld.\n", un,
7130 				    un->un_blockcount, un->un_tgt_blocksize);
7131 
7132 				break;
7133 			}
7134 			case EINVAL:
7135 				/*
7136 				 * In the case where the max-cdb-length property
7137 				 * is smaller than the required CDB length for
7138 				 * a SCSI device, a target driver can fail to
7139 				 * attach to that device.
7140 				 */
7141 				scsi_log(SD_DEVINFO(un),
7142 				    sd_label, CE_WARN,
7143 				    "disk capacity is too large "
7144 				    "for current cdb length");
7145 				goto spinup_failed;
7146 			case EACCES:
7147 				/*
7148 				 * Should never get here if the spin-up
7149 				 * succeeded, but code it in anyway.
7150 				 * From here, just continue with the attach...
7151 				 */
7152 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7153 				    "sd_unit_attach: un:0x%p "
7154 				    "sd_send_scsi_READ_CAPACITY "
7155 				    "returned reservation conflict\n", un);
7156 				reservation_flag = SD_TARGET_IS_RESERVED;
7157 				break;
7158 			default:
7159 				/*
7160 				 * Likewise, should never get here if the
7161 				 * spin-up succeeded. Just continue with
7162 				 * the attach...
7163 				 */
7164 				break;
7165 			}
7166 			break;
7167 		case EACCES:
7168 			/*
7169 			 * Device is reserved by another host.  In this case
7170 			 * we could not spin it up or read the capacity, but
7171 			 * we continue with the attach anyway.
7172 			 */
7173 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7174 			    "sd_unit_attach: un:0x%p spin-up reservation "
7175 			    "conflict.\n", un);
7176 			reservation_flag = SD_TARGET_IS_RESERVED;
7177 			break;
7178 		default:
7179 			/* Fail the attach if the spin-up failed. */
7180 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7181 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
7182 			goto spinup_failed;
7183 		}
7184 	}
7185 
7186 	/*
7187 	 * Check to see if this is a MMC drive
7188 	 */
7189 	if (ISCD(un)) {
7190 		sd_set_mmc_caps(un);
7191 	}
7192 
7193 
7194 	/*
7195 	 * Add a zero-length attribute to tell the world we support
7196 	 * kernel ioctls (for layered drivers)
7197 	 */
7198 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7199 	    DDI_KERNEL_IOCTL, NULL, 0);
7200 
7201 	/*
7202 	 * Add a boolean property to tell the world we support
7203 	 * the B_FAILFAST flag (for layered drivers)
7204 	 */
7205 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7206 	    "ddi-failfast-supported", NULL, 0);
7207 
7208 	/*
7209 	 * Initialize power management
7210 	 */
7211 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
7212 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
7213 	sd_setup_pm(un, devi);
7214 	if (un->un_f_pm_is_enabled == FALSE) {
7215 		/*
7216 		 * For performance, point to a jump table that does
7217 		 * not include pm.
7218 		 * The direct and priority chains don't change with PM.
7219 		 *
7220 		 * Note: this is currently done based on individual device
7221 		 * capabilities. When an interface for determining system
7222 		 * power enabled state becomes available, or when additional
7223 		 * layers are added to the command chain, these values will
7224 		 * have to be re-evaluated for correctness.
7225 		 */
7226 		if (un->un_f_non_devbsize_supported) {
7227 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
7228 		} else {
7229 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
7230 		}
7231 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
7232 	}
7233 
7234 	/*
7235 	 * This property is set to 0 by HA software to avoid retries
7236 	 * on a reserved disk. (The preferred property name is
7237 	 * "retry-on-reservation-conflict") (1189689)
7238 	 *
7239 	 * Note: The use of a global here can have unintended consequences. A
7240 	 * per instance variable is preferrable to match the capabilities of
7241 	 * different underlying hba's (4402600)
7242 	 */
7243 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
7244 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
7245 	    sd_retry_on_reservation_conflict);
7246 	if (sd_retry_on_reservation_conflict != 0) {
7247 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
7248 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
7249 		    sd_retry_on_reservation_conflict);
7250 	}
7251 
7252 	/* Set up options for QFULL handling. */
7253 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7254 	    "qfull-retries", -1)) != -1) {
7255 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
7256 		    rval, 1);
7257 	}
7258 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7259 	    "qfull-retry-interval", -1)) != -1) {
7260 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
7261 		    rval, 1);
7262 	}
7263 
7264 	/*
7265 	 * This just prints a message that announces the existence of the
7266 	 * device. The message is always printed in the system logfile, but
7267 	 * only appears on the console if the system is booted with the
7268 	 * -v (verbose) argument.
7269 	 */
7270 	ddi_report_dev(devi);
7271 
7272 	un->un_mediastate = DKIO_NONE;
7273 
7274 	cmlb_alloc_handle(&un->un_cmlbhandle);
7275 
7276 #if defined(__i386) || defined(__amd64)
7277 	/*
7278 	 * On x86, compensate for off-by-1 legacy error
7279 	 */
7280 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
7281 	    (lbasize == un->un_sys_blocksize))
7282 		offbyone = CMLB_OFF_BY_ONE;
7283 #endif
7284 
7285 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
7286 	    un->un_f_has_removable_media, un->un_f_is_hotpluggable,
7287 	    un->un_node_type, offbyone, un->un_cmlbhandle,
7288 	    (void *)SD_PATH_DIRECT) != 0) {
7289 		goto cmlb_attach_failed;
7290 	}
7291 
7292 
7293 	/*
7294 	 * Read and validate the device's geometry (ie, disk label)
7295 	 * A new unformatted drive will not have a valid geometry, but
7296 	 * the driver needs to successfully attach to this device so
7297 	 * the drive can be formatted via ioctls.
7298 	 */
7299 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
7300 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
7301 
7302 	mutex_enter(SD_MUTEX(un));
7303 
7304 	/*
7305 	 * Read and initialize the devid for the unit.
7306 	 */
7307 	ASSERT(un->un_errstats != NULL);
7308 	if (un->un_f_devid_supported) {
7309 		sd_register_devid(un, devi, reservation_flag);
7310 	}
7311 	mutex_exit(SD_MUTEX(un));
7312 
7313 #if (defined(__fibre))
7314 	/*
7315 	 * Register callbacks for fibre only.  You can't do this soley
7316 	 * on the basis of the devid_type because this is hba specific.
7317 	 * We need to query our hba capabilities to find out whether to
7318 	 * register or not.
7319 	 */
7320 	if (un->un_f_is_fibre) {
7321 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
7322 			sd_init_event_callbacks(un);
7323 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7324 			    "sd_unit_attach: un:0x%p event callbacks inserted",
7325 			    un);
7326 		}
7327 	}
7328 #endif
7329 
7330 	if (un->un_f_opt_disable_cache == TRUE) {
7331 		/*
7332 		 * Disable both read cache and write cache.  This is
7333 		 * the historic behavior of the keywords in the config file.
7334 		 */
7335 		if (sd_cache_control(un, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
7336 		    0) {
7337 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7338 			    "sd_unit_attach: un:0x%p Could not disable "
7339 			    "caching", un);
7340 			goto devid_failed;
7341 		}
7342 	}
7343 
7344 	/*
7345 	 * Check the value of the WCE bit now and
7346 	 * set un_f_write_cache_enabled accordingly.
7347 	 */
7348 	(void) sd_get_write_cache_enabled(un, &wc_enabled);
7349 	mutex_enter(SD_MUTEX(un));
7350 	un->un_f_write_cache_enabled = (wc_enabled != 0);
7351 	mutex_exit(SD_MUTEX(un));
7352 
7353 	/*
7354 	 * Check the value of the NV_SUP bit and set
7355 	 * un_f_suppress_cache_flush accordingly.
7356 	 */
7357 	sd_get_nv_sup(un);
7358 
7359 	/*
7360 	 * Find out what type of reservation this disk supports.
7361 	 */
7362 	switch (sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS, 0, NULL)) {
7363 	case 0:
7364 		/*
7365 		 * SCSI-3 reservations are supported.
7366 		 */
7367 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7368 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7369 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
7370 		break;
7371 	case ENOTSUP:
7372 		/*
7373 		 * The PERSISTENT RESERVE IN command would not be recognized by
7374 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
7375 		 */
7376 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7377 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
7378 		un->un_reservation_type = SD_SCSI2_RESERVATION;
7379 		break;
7380 	default:
7381 		/*
7382 		 * default to SCSI-3 reservations
7383 		 */
7384 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7385 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
7386 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7387 		break;
7388 	}
7389 
7390 	/*
7391 	 * Set the pstat and error stat values here, so data obtained during the
7392 	 * previous attach-time routines is available.
7393 	 *
7394 	 * Note: This is a critical sequence that needs to be maintained:
7395 	 *	1) Instantiate the kstats before any routines using the iopath
7396 	 *	   (i.e. sd_send_scsi_cmd).
7397 	 *	2) Initialize the error stats (sd_set_errstats) and partition
7398 	 *	   stats (sd_set_pstats)here, following
7399 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
7400 	 *	   sd_cache_control().
7401 	 */
7402 
7403 	if (un->un_f_pkstats_enabled && geom_label_valid) {
7404 		sd_set_pstats(un);
7405 		SD_TRACE(SD_LOG_IO_PARTITION, un,
7406 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
7407 	}
7408 
7409 	sd_set_errstats(un);
7410 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7411 	    "sd_unit_attach: un:0x%p errstats set\n", un);
7412 
7413 
7414 	/*
7415 	 * After successfully attaching an instance, we record the information
7416 	 * of how many luns have been attached on the relative target and
7417 	 * controller for parallel SCSI. This information is used when sd tries
7418 	 * to set the tagged queuing capability in HBA.
7419 	 */
7420 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
7421 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
7422 	}
7423 
7424 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7425 	    "sd_unit_attach: un:0x%p exit success\n", un);
7426 
7427 	return (DDI_SUCCESS);
7428 
7429 	/*
7430 	 * An error occurred during the attach; clean up & return failure.
7431 	 */
7432 
7433 devid_failed:
7434 
7435 setup_pm_failed:
7436 	ddi_remove_minor_node(devi, NULL);
7437 
7438 cmlb_attach_failed:
7439 	/*
7440 	 * Cleanup from the scsi_ifsetcap() calls (437868)
7441 	 */
7442 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
7443 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
7444 
7445 	/*
7446 	 * Refer to the comments of setting tagged-qing in the beginning of
7447 	 * sd_unit_attach. We can only disable tagged queuing when there is
7448 	 * no lun attached on the target.
7449 	 */
7450 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7451 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
7452 	}
7453 
7454 	if (un->un_f_is_fibre == FALSE) {
7455 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
7456 	}
7457 
7458 spinup_failed:
7459 
7460 	mutex_enter(SD_MUTEX(un));
7461 
7462 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
7463 	if (un->un_direct_priority_timeid != NULL) {
7464 		timeout_id_t temp_id = un->un_direct_priority_timeid;
7465 		un->un_direct_priority_timeid = NULL;
7466 		mutex_exit(SD_MUTEX(un));
7467 		(void) untimeout(temp_id);
7468 		mutex_enter(SD_MUTEX(un));
7469 	}
7470 
7471 	/* Cancel any pending start/stop timeouts */
7472 	if (un->un_startstop_timeid != NULL) {
7473 		timeout_id_t temp_id = un->un_startstop_timeid;
7474 		un->un_startstop_timeid = NULL;
7475 		mutex_exit(SD_MUTEX(un));
7476 		(void) untimeout(temp_id);
7477 		mutex_enter(SD_MUTEX(un));
7478 	}
7479 
7480 	/* Cancel any pending reset-throttle timeouts */
7481 	if (un->un_reset_throttle_timeid != NULL) {
7482 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
7483 		un->un_reset_throttle_timeid = NULL;
7484 		mutex_exit(SD_MUTEX(un));
7485 		(void) untimeout(temp_id);
7486 		mutex_enter(SD_MUTEX(un));
7487 	}
7488 
7489 	/* Cancel any pending retry timeouts */
7490 	if (un->un_retry_timeid != NULL) {
7491 		timeout_id_t temp_id = un->un_retry_timeid;
7492 		un->un_retry_timeid = NULL;
7493 		mutex_exit(SD_MUTEX(un));
7494 		(void) untimeout(temp_id);
7495 		mutex_enter(SD_MUTEX(un));
7496 	}
7497 
7498 	/* Cancel any pending delayed cv broadcast timeouts */
7499 	if (un->un_dcvb_timeid != NULL) {
7500 		timeout_id_t temp_id = un->un_dcvb_timeid;
7501 		un->un_dcvb_timeid = NULL;
7502 		mutex_exit(SD_MUTEX(un));
7503 		(void) untimeout(temp_id);
7504 		mutex_enter(SD_MUTEX(un));
7505 	}
7506 
7507 	mutex_exit(SD_MUTEX(un));
7508 
7509 	/* There should not be any in-progress I/O so ASSERT this check */
7510 	ASSERT(un->un_ncmds_in_transport == 0);
7511 	ASSERT(un->un_ncmds_in_driver == 0);
7512 
7513 	/* Do not free the softstate if the callback routine is active */
7514 	sd_sync_with_callback(un);
7515 
7516 	/*
7517 	 * Partition stats apparently are not used with removables. These would
7518 	 * not have been created during attach, so no need to clean them up...
7519 	 */
7520 	if (un->un_stats != NULL) {
7521 		kstat_delete(un->un_stats);
7522 		un->un_stats = NULL;
7523 	}
7524 	if (un->un_errstats != NULL) {
7525 		kstat_delete(un->un_errstats);
7526 		un->un_errstats = NULL;
7527 	}
7528 
7529 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
7530 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
7531 
7532 	ddi_prop_remove_all(devi);
7533 	sema_destroy(&un->un_semoclose);
7534 	cv_destroy(&un->un_state_cv);
7535 
7536 getrbuf_failed:
7537 
7538 	sd_free_rqs(un);
7539 
7540 alloc_rqs_failed:
7541 
7542 	devp->sd_private = NULL;
7543 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
7544 
7545 get_softstate_failed:
7546 	/*
7547 	 * Note: the man pages are unclear as to whether or not doing a
7548 	 * ddi_soft_state_free(sd_state, instance) is the right way to
7549 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
7550 	 * ddi_get_soft_state() fails.  The implication seems to be
7551 	 * that the get_soft_state cannot fail if the zalloc succeeds.
7552 	 */
7553 	ddi_soft_state_free(sd_state, instance);
7554 
7555 probe_failed:
7556 	scsi_unprobe(devp);
7557 
7558 	return (DDI_FAILURE);
7559 }
7560 
7561 
7562 /*
7563  *    Function: sd_unit_detach
7564  *
7565  * Description: Performs DDI_DETACH processing for sddetach().
7566  *
7567  * Return Code: DDI_SUCCESS
7568  *		DDI_FAILURE
7569  *
7570  *     Context: Kernel thread context
7571  */
7572 
7573 static int
7574 sd_unit_detach(dev_info_t *devi)
7575 {
7576 	struct scsi_device	*devp;
7577 	struct sd_lun		*un;
7578 	int			i;
7579 	int			tgt;
7580 	dev_t			dev;
7581 	dev_info_t		*pdip = ddi_get_parent(devi);
7582 	int			instance = ddi_get_instance(devi);
7583 
7584 	mutex_enter(&sd_detach_mutex);
7585 
7586 	/*
7587 	 * Fail the detach for any of the following:
7588 	 *  - Unable to get the sd_lun struct for the instance
7589 	 *  - A layered driver has an outstanding open on the instance
7590 	 *  - Another thread is already detaching this instance
7591 	 *  - Another thread is currently performing an open
7592 	 */
7593 	devp = ddi_get_driver_private(devi);
7594 	if ((devp == NULL) ||
7595 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
7596 	    (un->un_ncmds_in_driver != 0) || (un->un_layer_count != 0) ||
7597 	    (un->un_detach_count != 0) || (un->un_opens_in_progress != 0)) {
7598 		mutex_exit(&sd_detach_mutex);
7599 		return (DDI_FAILURE);
7600 	}
7601 
7602 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
7603 
7604 	/*
7605 	 * Mark this instance as currently in a detach, to inhibit any
7606 	 * opens from a layered driver.
7607 	 */
7608 	un->un_detach_count++;
7609 	mutex_exit(&sd_detach_mutex);
7610 
7611 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7612 	    SCSI_ADDR_PROP_TARGET, -1);
7613 
7614 	dev = sd_make_device(SD_DEVINFO(un));
7615 
7616 #ifndef lint
7617 	_NOTE(COMPETING_THREADS_NOW);
7618 #endif
7619 
7620 	mutex_enter(SD_MUTEX(un));
7621 
7622 	/*
7623 	 * Fail the detach if there are any outstanding layered
7624 	 * opens on this device.
7625 	 */
7626 	for (i = 0; i < NDKMAP; i++) {
7627 		if (un->un_ocmap.lyropen[i] != 0) {
7628 			goto err_notclosed;
7629 		}
7630 	}
7631 
7632 	/*
7633 	 * Verify there are NO outstanding commands issued to this device.
7634 	 * ie, un_ncmds_in_transport == 0.
7635 	 * It's possible to have outstanding commands through the physio
7636 	 * code path, even though everything's closed.
7637 	 */
7638 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
7639 	    (un->un_direct_priority_timeid != NULL) ||
7640 	    (un->un_state == SD_STATE_RWAIT)) {
7641 		mutex_exit(SD_MUTEX(un));
7642 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7643 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
7644 		goto err_stillbusy;
7645 	}
7646 
7647 	/*
7648 	 * If we have the device reserved, release the reservation.
7649 	 */
7650 	if ((un->un_resvd_status & SD_RESERVE) &&
7651 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
7652 		mutex_exit(SD_MUTEX(un));
7653 		/*
7654 		 * Note: sd_reserve_release sends a command to the device
7655 		 * via the sd_ioctlcmd() path, and can sleep.
7656 		 */
7657 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
7658 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7659 			    "sd_dr_detach: Cannot release reservation \n");
7660 		}
7661 	} else {
7662 		mutex_exit(SD_MUTEX(un));
7663 	}
7664 
7665 	/*
7666 	 * Untimeout any reserve recover, throttle reset, restart unit
7667 	 * and delayed broadcast timeout threads. Protect the timeout pointer
7668 	 * from getting nulled by their callback functions.
7669 	 */
7670 	mutex_enter(SD_MUTEX(un));
7671 	if (un->un_resvd_timeid != NULL) {
7672 		timeout_id_t temp_id = un->un_resvd_timeid;
7673 		un->un_resvd_timeid = NULL;
7674 		mutex_exit(SD_MUTEX(un));
7675 		(void) untimeout(temp_id);
7676 		mutex_enter(SD_MUTEX(un));
7677 	}
7678 
7679 	if (un->un_reset_throttle_timeid != NULL) {
7680 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
7681 		un->un_reset_throttle_timeid = NULL;
7682 		mutex_exit(SD_MUTEX(un));
7683 		(void) untimeout(temp_id);
7684 		mutex_enter(SD_MUTEX(un));
7685 	}
7686 
7687 	if (un->un_startstop_timeid != NULL) {
7688 		timeout_id_t temp_id = un->un_startstop_timeid;
7689 		un->un_startstop_timeid = NULL;
7690 		mutex_exit(SD_MUTEX(un));
7691 		(void) untimeout(temp_id);
7692 		mutex_enter(SD_MUTEX(un));
7693 	}
7694 
7695 	if (un->un_dcvb_timeid != NULL) {
7696 		timeout_id_t temp_id = un->un_dcvb_timeid;
7697 		un->un_dcvb_timeid = NULL;
7698 		mutex_exit(SD_MUTEX(un));
7699 		(void) untimeout(temp_id);
7700 	} else {
7701 		mutex_exit(SD_MUTEX(un));
7702 	}
7703 
7704 	/* Remove any pending reservation reclaim requests for this device */
7705 	sd_rmv_resv_reclaim_req(dev);
7706 
7707 	mutex_enter(SD_MUTEX(un));
7708 
7709 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
7710 	if (un->un_direct_priority_timeid != NULL) {
7711 		timeout_id_t temp_id = un->un_direct_priority_timeid;
7712 		un->un_direct_priority_timeid = NULL;
7713 		mutex_exit(SD_MUTEX(un));
7714 		(void) untimeout(temp_id);
7715 		mutex_enter(SD_MUTEX(un));
7716 	}
7717 
7718 	/* Cancel any active multi-host disk watch thread requests */
7719 	if (un->un_mhd_token != NULL) {
7720 		mutex_exit(SD_MUTEX(un));
7721 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
7722 		if (scsi_watch_request_terminate(un->un_mhd_token,
7723 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
7724 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7725 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
7726 			/*
7727 			 * Note: We are returning here after having removed
7728 			 * some driver timeouts above. This is consistent with
7729 			 * the legacy implementation but perhaps the watch
7730 			 * terminate call should be made with the wait flag set.
7731 			 */
7732 			goto err_stillbusy;
7733 		}
7734 		mutex_enter(SD_MUTEX(un));
7735 		un->un_mhd_token = NULL;
7736 	}
7737 
7738 	if (un->un_swr_token != NULL) {
7739 		mutex_exit(SD_MUTEX(un));
7740 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
7741 		if (scsi_watch_request_terminate(un->un_swr_token,
7742 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
7743 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7744 			    "sd_dr_detach: Cannot cancel swr watch request\n");
7745 			/*
7746 			 * Note: We are returning here after having removed
7747 			 * some driver timeouts above. This is consistent with
7748 			 * the legacy implementation but perhaps the watch
7749 			 * terminate call should be made with the wait flag set.
7750 			 */
7751 			goto err_stillbusy;
7752 		}
7753 		mutex_enter(SD_MUTEX(un));
7754 		un->un_swr_token = NULL;
7755 	}
7756 
7757 	mutex_exit(SD_MUTEX(un));
7758 
7759 	/*
7760 	 * Clear any scsi_reset_notifies. We clear the reset notifies
7761 	 * if we have not registered one.
7762 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
7763 	 */
7764 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
7765 	    sd_mhd_reset_notify_cb, (caddr_t)un);
7766 
7767 	/*
7768 	 * protect the timeout pointers from getting nulled by
7769 	 * their callback functions during the cancellation process.
7770 	 * In such a scenario untimeout can be invoked with a null value.
7771 	 */
7772 	_NOTE(NO_COMPETING_THREADS_NOW);
7773 
7774 	mutex_enter(&un->un_pm_mutex);
7775 	if (un->un_pm_idle_timeid != NULL) {
7776 		timeout_id_t temp_id = un->un_pm_idle_timeid;
7777 		un->un_pm_idle_timeid = NULL;
7778 		mutex_exit(&un->un_pm_mutex);
7779 
7780 		/*
7781 		 * Timeout is active; cancel it.
7782 		 * Note that it'll never be active on a device
7783 		 * that does not support PM therefore we don't
7784 		 * have to check before calling pm_idle_component.
7785 		 */
7786 		(void) untimeout(temp_id);
7787 		(void) pm_idle_component(SD_DEVINFO(un), 0);
7788 		mutex_enter(&un->un_pm_mutex);
7789 	}
7790 
7791 	/*
7792 	 * Check whether there is already a timeout scheduled for power
7793 	 * management. If yes then don't lower the power here, that's.
7794 	 * the timeout handler's job.
7795 	 */
7796 	if (un->un_pm_timeid != NULL) {
7797 		timeout_id_t temp_id = un->un_pm_timeid;
7798 		un->un_pm_timeid = NULL;
7799 		mutex_exit(&un->un_pm_mutex);
7800 		/*
7801 		 * Timeout is active; cancel it.
7802 		 * Note that it'll never be active on a device
7803 		 * that does not support PM therefore we don't
7804 		 * have to check before calling pm_idle_component.
7805 		 */
7806 		(void) untimeout(temp_id);
7807 		(void) pm_idle_component(SD_DEVINFO(un), 0);
7808 
7809 	} else {
7810 		mutex_exit(&un->un_pm_mutex);
7811 		if ((un->un_f_pm_is_enabled == TRUE) &&
7812 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_SPINDLE_OFF) !=
7813 		    DDI_SUCCESS)) {
7814 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7815 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
7816 			/*
7817 			 * Fix for bug: 4297749, item # 13
7818 			 * The above test now includes a check to see if PM is
7819 			 * supported by this device before call
7820 			 * pm_lower_power().
7821 			 * Note, the following is not dead code. The call to
7822 			 * pm_lower_power above will generate a call back into
7823 			 * our sdpower routine which might result in a timeout
7824 			 * handler getting activated. Therefore the following
7825 			 * code is valid and necessary.
7826 			 */
7827 			mutex_enter(&un->un_pm_mutex);
7828 			if (un->un_pm_timeid != NULL) {
7829 				timeout_id_t temp_id = un->un_pm_timeid;
7830 				un->un_pm_timeid = NULL;
7831 				mutex_exit(&un->un_pm_mutex);
7832 				(void) untimeout(temp_id);
7833 				(void) pm_idle_component(SD_DEVINFO(un), 0);
7834 			} else {
7835 				mutex_exit(&un->un_pm_mutex);
7836 			}
7837 		}
7838 	}
7839 
7840 	/*
7841 	 * Cleanup from the scsi_ifsetcap() calls (437868)
7842 	 * Relocated here from above to be after the call to
7843 	 * pm_lower_power, which was getting errors.
7844 	 */
7845 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
7846 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
7847 
7848 	/*
7849 	 * Currently, tagged queuing is supported per target based by HBA.
7850 	 * Setting this per lun instance actually sets the capability of this
7851 	 * target in HBA, which affects those luns already attached on the
7852 	 * same target. So during detach, we can only disable this capability
7853 	 * only when this is the only lun left on this target. By doing
7854 	 * this, we assume a target has the same tagged queuing capability
7855 	 * for every lun. The condition can be removed when HBA is changed to
7856 	 * support per lun based tagged queuing capability.
7857 	 */
7858 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
7859 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
7860 	}
7861 
7862 	if (un->un_f_is_fibre == FALSE) {
7863 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
7864 	}
7865 
7866 	/*
7867 	 * Remove any event callbacks, fibre only
7868 	 */
7869 	if (un->un_f_is_fibre == TRUE) {
7870 		if ((un->un_insert_event != NULL) &&
7871 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
7872 		    DDI_SUCCESS)) {
7873 			/*
7874 			 * Note: We are returning here after having done
7875 			 * substantial cleanup above. This is consistent
7876 			 * with the legacy implementation but this may not
7877 			 * be the right thing to do.
7878 			 */
7879 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7880 			    "sd_dr_detach: Cannot cancel insert event\n");
7881 			goto err_remove_event;
7882 		}
7883 		un->un_insert_event = NULL;
7884 
7885 		if ((un->un_remove_event != NULL) &&
7886 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
7887 		    DDI_SUCCESS)) {
7888 			/*
7889 			 * Note: We are returning here after having done
7890 			 * substantial cleanup above. This is consistent
7891 			 * with the legacy implementation but this may not
7892 			 * be the right thing to do.
7893 			 */
7894 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7895 			    "sd_dr_detach: Cannot cancel remove event\n");
7896 			goto err_remove_event;
7897 		}
7898 		un->un_remove_event = NULL;
7899 	}
7900 
7901 	/* Do not free the softstate if the callback routine is active */
7902 	sd_sync_with_callback(un);
7903 
7904 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
7905 	cmlb_free_handle(&un->un_cmlbhandle);
7906 
7907 	/*
7908 	 * Hold the detach mutex here, to make sure that no other threads ever
7909 	 * can access a (partially) freed soft state structure.
7910 	 */
7911 	mutex_enter(&sd_detach_mutex);
7912 
7913 	/*
7914 	 * Clean up the soft state struct.
7915 	 * Cleanup is done in reverse order of allocs/inits.
7916 	 * At this point there should be no competing threads anymore.
7917 	 */
7918 
7919 	/* Unregister and free device id. */
7920 	ddi_devid_unregister(devi);
7921 	if (un->un_devid) {
7922 		ddi_devid_free(un->un_devid);
7923 		un->un_devid = NULL;
7924 	}
7925 
7926 	/*
7927 	 * Destroy wmap cache if it exists.
7928 	 */
7929 	if (un->un_wm_cache != NULL) {
7930 		kmem_cache_destroy(un->un_wm_cache);
7931 		un->un_wm_cache = NULL;
7932 	}
7933 
7934 	/*
7935 	 * kstat cleanup is done in detach for all device types (4363169).
7936 	 * We do not want to fail detach if the device kstats are not deleted
7937 	 * since there is a confusion about the devo_refcnt for the device.
7938 	 * We just delete the kstats and let detach complete successfully.
7939 	 */
7940 	if (un->un_stats != NULL) {
7941 		kstat_delete(un->un_stats);
7942 		un->un_stats = NULL;
7943 	}
7944 	if (un->un_errstats != NULL) {
7945 		kstat_delete(un->un_errstats);
7946 		un->un_errstats = NULL;
7947 	}
7948 
7949 	/* Remove partition stats */
7950 	if (un->un_f_pkstats_enabled) {
7951 		for (i = 0; i < NSDMAP; i++) {
7952 			if (un->un_pstats[i] != NULL) {
7953 				kstat_delete(un->un_pstats[i]);
7954 				un->un_pstats[i] = NULL;
7955 			}
7956 		}
7957 	}
7958 
7959 	/* Remove xbuf registration */
7960 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
7961 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
7962 
7963 	/* Remove driver properties */
7964 	ddi_prop_remove_all(devi);
7965 
7966 	mutex_destroy(&un->un_pm_mutex);
7967 	cv_destroy(&un->un_pm_busy_cv);
7968 
7969 	cv_destroy(&un->un_wcc_cv);
7970 
7971 	/* Open/close semaphore */
7972 	sema_destroy(&un->un_semoclose);
7973 
7974 	/* Removable media condvar. */
7975 	cv_destroy(&un->un_state_cv);
7976 
7977 	/* Suspend/resume condvar. */
7978 	cv_destroy(&un->un_suspend_cv);
7979 	cv_destroy(&un->un_disk_busy_cv);
7980 
7981 	sd_free_rqs(un);
7982 
7983 	/* Free up soft state */
7984 	devp->sd_private = NULL;
7985 
7986 	bzero(un, sizeof (struct sd_lun));
7987 	ddi_soft_state_free(sd_state, instance);
7988 
7989 	mutex_exit(&sd_detach_mutex);
7990 
7991 	/* This frees up the INQUIRY data associated with the device. */
7992 	scsi_unprobe(devp);
7993 
7994 	/*
7995 	 * After successfully detaching an instance, we update the information
7996 	 * of how many luns have been attached in the relative target and
7997 	 * controller for parallel SCSI. This information is used when sd tries
7998 	 * to set the tagged queuing capability in HBA.
7999 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
8000 	 * check if the device is parallel SCSI. However, we don't need to
8001 	 * check here because we've already checked during attach. No device
8002 	 * that is not parallel SCSI is in the chain.
8003 	 */
8004 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8005 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
8006 	}
8007 
8008 	return (DDI_SUCCESS);
8009 
8010 err_notclosed:
8011 	mutex_exit(SD_MUTEX(un));
8012 
8013 err_stillbusy:
8014 	_NOTE(NO_COMPETING_THREADS_NOW);
8015 
8016 err_remove_event:
8017 	mutex_enter(&sd_detach_mutex);
8018 	un->un_detach_count--;
8019 	mutex_exit(&sd_detach_mutex);
8020 
8021 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
8022 	return (DDI_FAILURE);
8023 }
8024 
8025 
8026 /*
8027  *    Function: sd_create_errstats
8028  *
8029  * Description: This routine instantiates the device error stats.
8030  *
8031  *		Note: During attach the stats are instantiated first so they are
8032  *		available for attach-time routines that utilize the driver
8033  *		iopath to send commands to the device. The stats are initialized
8034  *		separately so data obtained during some attach-time routines is
8035  *		available. (4362483)
8036  *
8037  *   Arguments: un - driver soft state (unit) structure
8038  *		instance - driver instance
8039  *
8040  *     Context: Kernel thread context
8041  */
8042 
8043 static void
8044 sd_create_errstats(struct sd_lun *un, int instance)
8045 {
8046 	struct	sd_errstats	*stp;
8047 	char	kstatmodule_err[KSTAT_STRLEN];
8048 	char	kstatname[KSTAT_STRLEN];
8049 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
8050 
8051 	ASSERT(un != NULL);
8052 
8053 	if (un->un_errstats != NULL) {
8054 		return;
8055 	}
8056 
8057 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
8058 	    "%serr", sd_label);
8059 	(void) snprintf(kstatname, sizeof (kstatname),
8060 	    "%s%d,err", sd_label, instance);
8061 
8062 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
8063 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
8064 
8065 	if (un->un_errstats == NULL) {
8066 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8067 		    "sd_create_errstats: Failed kstat_create\n");
8068 		return;
8069 	}
8070 
8071 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8072 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
8073 	    KSTAT_DATA_UINT32);
8074 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
8075 	    KSTAT_DATA_UINT32);
8076 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
8077 	    KSTAT_DATA_UINT32);
8078 	kstat_named_init(&stp->sd_vid,		"Vendor",
8079 	    KSTAT_DATA_CHAR);
8080 	kstat_named_init(&stp->sd_pid,		"Product",
8081 	    KSTAT_DATA_CHAR);
8082 	kstat_named_init(&stp->sd_revision,	"Revision",
8083 	    KSTAT_DATA_CHAR);
8084 	kstat_named_init(&stp->sd_serial,	"Serial No",
8085 	    KSTAT_DATA_CHAR);
8086 	kstat_named_init(&stp->sd_capacity,	"Size",
8087 	    KSTAT_DATA_ULONGLONG);
8088 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
8089 	    KSTAT_DATA_UINT32);
8090 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
8091 	    KSTAT_DATA_UINT32);
8092 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
8093 	    KSTAT_DATA_UINT32);
8094 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
8095 	    KSTAT_DATA_UINT32);
8096 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
8097 	    KSTAT_DATA_UINT32);
8098 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
8099 	    KSTAT_DATA_UINT32);
8100 
8101 	un->un_errstats->ks_private = un;
8102 	un->un_errstats->ks_update  = nulldev;
8103 
8104 	kstat_install(un->un_errstats);
8105 }
8106 
8107 
8108 /*
8109  *    Function: sd_set_errstats
8110  *
8111  * Description: This routine sets the value of the vendor id, product id,
8112  *		revision, serial number, and capacity device error stats.
8113  *
8114  *		Note: During attach the stats are instantiated first so they are
8115  *		available for attach-time routines that utilize the driver
8116  *		iopath to send commands to the device. The stats are initialized
8117  *		separately so data obtained during some attach-time routines is
8118  *		available. (4362483)
8119  *
8120  *   Arguments: un - driver soft state (unit) structure
8121  *
8122  *     Context: Kernel thread context
8123  */
8124 
8125 static void
8126 sd_set_errstats(struct sd_lun *un)
8127 {
8128 	struct	sd_errstats	*stp;
8129 
8130 	ASSERT(un != NULL);
8131 	ASSERT(un->un_errstats != NULL);
8132 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8133 	ASSERT(stp != NULL);
8134 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
8135 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
8136 	(void) strncpy(stp->sd_revision.value.c,
8137 	    un->un_sd->sd_inq->inq_revision, 4);
8138 
8139 	/*
8140 	 * All the errstats are persistent across detach/attach,
8141 	 * so reset all the errstats here in case of the hot
8142 	 * replacement of disk drives, except for not changed
8143 	 * Sun qualified drives.
8144 	 */
8145 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
8146 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8147 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
8148 		stp->sd_softerrs.value.ui32 = 0;
8149 		stp->sd_harderrs.value.ui32 = 0;
8150 		stp->sd_transerrs.value.ui32 = 0;
8151 		stp->sd_rq_media_err.value.ui32 = 0;
8152 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
8153 		stp->sd_rq_nodev_err.value.ui32 = 0;
8154 		stp->sd_rq_recov_err.value.ui32 = 0;
8155 		stp->sd_rq_illrq_err.value.ui32 = 0;
8156 		stp->sd_rq_pfa_err.value.ui32 = 0;
8157 	}
8158 
8159 	/*
8160 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
8161 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
8162 	 * (4376302))
8163 	 */
8164 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
8165 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8166 		    sizeof (SD_INQUIRY(un)->inq_serial));
8167 	}
8168 
8169 	if (un->un_f_blockcount_is_valid != TRUE) {
8170 		/*
8171 		 * Set capacity error stat to 0 for no media. This ensures
8172 		 * a valid capacity is displayed in response to 'iostat -E'
8173 		 * when no media is present in the device.
8174 		 */
8175 		stp->sd_capacity.value.ui64 = 0;
8176 	} else {
8177 		/*
8178 		 * Multiply un_blockcount by un->un_sys_blocksize to get
8179 		 * capacity.
8180 		 *
8181 		 * Note: for non-512 blocksize devices "un_blockcount" has been
8182 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
8183 		 * (un_tgt_blocksize / un->un_sys_blocksize).
8184 		 */
8185 		stp->sd_capacity.value.ui64 = (uint64_t)
8186 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
8187 	}
8188 }
8189 
8190 
8191 /*
8192  *    Function: sd_set_pstats
8193  *
8194  * Description: This routine instantiates and initializes the partition
8195  *              stats for each partition with more than zero blocks.
8196  *		(4363169)
8197  *
8198  *   Arguments: un - driver soft state (unit) structure
8199  *
8200  *     Context: Kernel thread context
8201  */
8202 
8203 static void
8204 sd_set_pstats(struct sd_lun *un)
8205 {
8206 	char	kstatname[KSTAT_STRLEN];
8207 	int	instance;
8208 	int	i;
8209 	diskaddr_t	nblks = 0;
8210 	char	*partname = NULL;
8211 
8212 	ASSERT(un != NULL);
8213 
8214 	instance = ddi_get_instance(SD_DEVINFO(un));
8215 
8216 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
8217 	for (i = 0; i < NSDMAP; i++) {
8218 
8219 		if (cmlb_partinfo(un->un_cmlbhandle, i,
8220 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
8221 			continue;
8222 		mutex_enter(SD_MUTEX(un));
8223 
8224 		if ((un->un_pstats[i] == NULL) &&
8225 		    (nblks != 0)) {
8226 
8227 			(void) snprintf(kstatname, sizeof (kstatname),
8228 			    "%s%d,%s", sd_label, instance,
8229 			    partname);
8230 
8231 			un->un_pstats[i] = kstat_create(sd_label,
8232 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
8233 			    1, KSTAT_FLAG_PERSISTENT);
8234 			if (un->un_pstats[i] != NULL) {
8235 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
8236 				kstat_install(un->un_pstats[i]);
8237 			}
8238 		}
8239 		mutex_exit(SD_MUTEX(un));
8240 	}
8241 }
8242 
8243 
8244 #if (defined(__fibre))
8245 /*
8246  *    Function: sd_init_event_callbacks
8247  *
8248  * Description: This routine initializes the insertion and removal event
8249  *		callbacks. (fibre only)
8250  *
8251  *   Arguments: un - driver soft state (unit) structure
8252  *
8253  *     Context: Kernel thread context
8254  */
8255 
8256 static void
8257 sd_init_event_callbacks(struct sd_lun *un)
8258 {
8259 	ASSERT(un != NULL);
8260 
8261 	if ((un->un_insert_event == NULL) &&
8262 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
8263 	    &un->un_insert_event) == DDI_SUCCESS)) {
8264 		/*
8265 		 * Add the callback for an insertion event
8266 		 */
8267 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8268 		    un->un_insert_event, sd_event_callback, (void *)un,
8269 		    &(un->un_insert_cb_id));
8270 	}
8271 
8272 	if ((un->un_remove_event == NULL) &&
8273 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
8274 	    &un->un_remove_event) == DDI_SUCCESS)) {
8275 		/*
8276 		 * Add the callback for a removal event
8277 		 */
8278 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8279 		    un->un_remove_event, sd_event_callback, (void *)un,
8280 		    &(un->un_remove_cb_id));
8281 	}
8282 }
8283 
8284 
8285 /*
8286  *    Function: sd_event_callback
8287  *
8288  * Description: This routine handles insert/remove events (photon). The
8289  *		state is changed to OFFLINE which can be used to supress
8290  *		error msgs. (fibre only)
8291  *
8292  *   Arguments: un - driver soft state (unit) structure
8293  *
8294  *     Context: Callout thread context
8295  */
8296 /* ARGSUSED */
8297 static void
8298 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
8299     void *bus_impldata)
8300 {
8301 	struct sd_lun *un = (struct sd_lun *)arg;
8302 
8303 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
8304 	if (event == un->un_insert_event) {
8305 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
8306 		mutex_enter(SD_MUTEX(un));
8307 		if (un->un_state == SD_STATE_OFFLINE) {
8308 			if (un->un_last_state != SD_STATE_SUSPENDED) {
8309 				un->un_state = un->un_last_state;
8310 			} else {
8311 				/*
8312 				 * We have gone through SUSPEND/RESUME while
8313 				 * we were offline. Restore the last state
8314 				 */
8315 				un->un_state = un->un_save_state;
8316 			}
8317 		}
8318 		mutex_exit(SD_MUTEX(un));
8319 
8320 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
8321 	} else if (event == un->un_remove_event) {
8322 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
8323 		mutex_enter(SD_MUTEX(un));
8324 		/*
8325 		 * We need to handle an event callback that occurs during
8326 		 * the suspend operation, since we don't prevent it.
8327 		 */
8328 		if (un->un_state != SD_STATE_OFFLINE) {
8329 			if (un->un_state != SD_STATE_SUSPENDED) {
8330 				New_state(un, SD_STATE_OFFLINE);
8331 			} else {
8332 				un->un_last_state = SD_STATE_OFFLINE;
8333 			}
8334 		}
8335 		mutex_exit(SD_MUTEX(un));
8336 	} else {
8337 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
8338 		    "!Unknown event\n");
8339 	}
8340 
8341 }
8342 #endif
8343 
8344 /*
8345  *    Function: sd_cache_control()
8346  *
8347  * Description: This routine is the driver entry point for setting
8348  *		read and write caching by modifying the WCE (write cache
8349  *		enable) and RCD (read cache disable) bits of mode
8350  *		page 8 (MODEPAGE_CACHING).
8351  *
8352  *   Arguments: un - driver soft state (unit) structure
8353  *		rcd_flag - flag for controlling the read cache
8354  *		wce_flag - flag for controlling the write cache
8355  *
8356  * Return Code: EIO
8357  *		code returned by sd_send_scsi_MODE_SENSE and
8358  *		sd_send_scsi_MODE_SELECT
8359  *
8360  *     Context: Kernel Thread
8361  */
8362 
8363 static int
8364 sd_cache_control(struct sd_lun *un, int rcd_flag, int wce_flag)
8365 {
8366 	struct mode_caching	*mode_caching_page;
8367 	uchar_t			*header;
8368 	size_t			buflen;
8369 	int			hdrlen;
8370 	int			bd_len;
8371 	int			rval = 0;
8372 	struct mode_header_grp2	*mhp;
8373 
8374 	ASSERT(un != NULL);
8375 
8376 	/*
8377 	 * Do a test unit ready, otherwise a mode sense may not work if this
8378 	 * is the first command sent to the device after boot.
8379 	 */
8380 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
8381 
8382 	if (un->un_f_cfg_is_atapi == TRUE) {
8383 		hdrlen = MODE_HEADER_LENGTH_GRP2;
8384 	} else {
8385 		hdrlen = MODE_HEADER_LENGTH;
8386 	}
8387 
8388 	/*
8389 	 * Allocate memory for the retrieved mode page and its headers.  Set
8390 	 * a pointer to the page itself.  Use mode_cache_scsi3 to insure
8391 	 * we get all of the mode sense data otherwise, the mode select
8392 	 * will fail.  mode_cache_scsi3 is a superset of mode_caching.
8393 	 */
8394 	buflen = hdrlen + MODE_BLK_DESC_LENGTH +
8395 	    sizeof (struct mode_cache_scsi3);
8396 
8397 	header = kmem_zalloc(buflen, KM_SLEEP);
8398 
8399 	/* Get the information from the device. */
8400 	if (un->un_f_cfg_is_atapi == TRUE) {
8401 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
8402 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8403 	} else {
8404 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
8405 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8406 	}
8407 	if (rval != 0) {
8408 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
8409 		    "sd_cache_control: Mode Sense Failed\n");
8410 		kmem_free(header, buflen);
8411 		return (rval);
8412 	}
8413 
8414 	/*
8415 	 * Determine size of Block Descriptors in order to locate
8416 	 * the mode page data. ATAPI devices return 0, SCSI devices
8417 	 * should return MODE_BLK_DESC_LENGTH.
8418 	 */
8419 	if (un->un_f_cfg_is_atapi == TRUE) {
8420 		mhp	= (struct mode_header_grp2 *)header;
8421 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
8422 	} else {
8423 		bd_len  = ((struct mode_header *)header)->bdesc_length;
8424 	}
8425 
8426 	if (bd_len > MODE_BLK_DESC_LENGTH) {
8427 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
8428 		    "sd_cache_control: Mode Sense returned invalid "
8429 		    "block descriptor length\n");
8430 		kmem_free(header, buflen);
8431 		return (EIO);
8432 	}
8433 
8434 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
8435 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
8436 		SD_ERROR(SD_LOG_COMMON, un, "sd_cache_control: Mode Sense"
8437 		    " caching page code mismatch %d\n",
8438 		    mode_caching_page->mode_page.code);
8439 		kmem_free(header, buflen);
8440 		return (EIO);
8441 	}
8442 
8443 	/* Check the relevant bits on successful mode sense. */
8444 	if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
8445 	    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
8446 	    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
8447 	    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
8448 
8449 		size_t sbuflen;
8450 		uchar_t save_pg;
8451 
8452 		/*
8453 		 * Construct select buffer length based on the
8454 		 * length of the sense data returned.
8455 		 */
8456 		sbuflen =  hdrlen + MODE_BLK_DESC_LENGTH +
8457 		    sizeof (struct mode_page) +
8458 		    (int)mode_caching_page->mode_page.length;
8459 
8460 		/*
8461 		 * Set the caching bits as requested.
8462 		 */
8463 		if (rcd_flag == SD_CACHE_ENABLE)
8464 			mode_caching_page->rcd = 0;
8465 		else if (rcd_flag == SD_CACHE_DISABLE)
8466 			mode_caching_page->rcd = 1;
8467 
8468 		if (wce_flag == SD_CACHE_ENABLE)
8469 			mode_caching_page->wce = 1;
8470 		else if (wce_flag == SD_CACHE_DISABLE)
8471 			mode_caching_page->wce = 0;
8472 
8473 		/*
8474 		 * Save the page if the mode sense says the
8475 		 * drive supports it.
8476 		 */
8477 		save_pg = mode_caching_page->mode_page.ps ?
8478 		    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
8479 
8480 		/* Clear reserved bits before mode select. */
8481 		mode_caching_page->mode_page.ps = 0;
8482 
8483 		/*
8484 		 * Clear out mode header for mode select.
8485 		 * The rest of the retrieved page will be reused.
8486 		 */
8487 		bzero(header, hdrlen);
8488 
8489 		if (un->un_f_cfg_is_atapi == TRUE) {
8490 			mhp = (struct mode_header_grp2 *)header;
8491 			mhp->bdesc_length_hi = bd_len >> 8;
8492 			mhp->bdesc_length_lo = (uchar_t)bd_len & 0xff;
8493 		} else {
8494 			((struct mode_header *)header)->bdesc_length = bd_len;
8495 		}
8496 
8497 		/* Issue mode select to change the cache settings */
8498 		if (un->un_f_cfg_is_atapi == TRUE) {
8499 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, header,
8500 			    sbuflen, save_pg, SD_PATH_DIRECT);
8501 		} else {
8502 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
8503 			    sbuflen, save_pg, SD_PATH_DIRECT);
8504 		}
8505 	}
8506 
8507 	kmem_free(header, buflen);
8508 	return (rval);
8509 }
8510 
8511 
8512 /*
8513  *    Function: sd_get_write_cache_enabled()
8514  *
8515  * Description: This routine is the driver entry point for determining if
8516  *		write caching is enabled.  It examines the WCE (write cache
8517  *		enable) bits of mode page 8 (MODEPAGE_CACHING).
8518  *
8519  *   Arguments: un - driver soft state (unit) structure
8520  *		is_enabled - pointer to int where write cache enabled state
8521  *		is returned (non-zero -> write cache enabled)
8522  *
8523  *
8524  * Return Code: EIO
8525  *		code returned by sd_send_scsi_MODE_SENSE
8526  *
8527  *     Context: Kernel Thread
8528  *
8529  * NOTE: If ioctl is added to disable write cache, this sequence should
8530  * be followed so that no locking is required for accesses to
8531  * un->un_f_write_cache_enabled:
8532  * 	do mode select to clear wce
8533  * 	do synchronize cache to flush cache
8534  * 	set un->un_f_write_cache_enabled = FALSE
8535  *
8536  * Conversely, an ioctl to enable the write cache should be done
8537  * in this order:
8538  * 	set un->un_f_write_cache_enabled = TRUE
8539  * 	do mode select to set wce
8540  */
8541 
8542 static int
8543 sd_get_write_cache_enabled(struct sd_lun *un, int *is_enabled)
8544 {
8545 	struct mode_caching	*mode_caching_page;
8546 	uchar_t			*header;
8547 	size_t			buflen;
8548 	int			hdrlen;
8549 	int			bd_len;
8550 	int			rval = 0;
8551 
8552 	ASSERT(un != NULL);
8553 	ASSERT(is_enabled != NULL);
8554 
8555 	/* in case of error, flag as enabled */
8556 	*is_enabled = TRUE;
8557 
8558 	/*
8559 	 * Do a test unit ready, otherwise a mode sense may not work if this
8560 	 * is the first command sent to the device after boot.
8561 	 */
8562 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
8563 
8564 	if (un->un_f_cfg_is_atapi == TRUE) {
8565 		hdrlen = MODE_HEADER_LENGTH_GRP2;
8566 	} else {
8567 		hdrlen = MODE_HEADER_LENGTH;
8568 	}
8569 
8570 	/*
8571 	 * Allocate memory for the retrieved mode page and its headers.  Set
8572 	 * a pointer to the page itself.
8573 	 */
8574 	buflen = hdrlen + MODE_BLK_DESC_LENGTH + sizeof (struct mode_caching);
8575 	header = kmem_zalloc(buflen, KM_SLEEP);
8576 
8577 	/* Get the information from the device. */
8578 	if (un->un_f_cfg_is_atapi == TRUE) {
8579 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
8580 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8581 	} else {
8582 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
8583 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8584 	}
8585 	if (rval != 0) {
8586 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
8587 		    "sd_get_write_cache_enabled: Mode Sense Failed\n");
8588 		kmem_free(header, buflen);
8589 		return (rval);
8590 	}
8591 
8592 	/*
8593 	 * Determine size of Block Descriptors in order to locate
8594 	 * the mode page data. ATAPI devices return 0, SCSI devices
8595 	 * should return MODE_BLK_DESC_LENGTH.
8596 	 */
8597 	if (un->un_f_cfg_is_atapi == TRUE) {
8598 		struct mode_header_grp2	*mhp;
8599 		mhp	= (struct mode_header_grp2 *)header;
8600 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
8601 	} else {
8602 		bd_len  = ((struct mode_header *)header)->bdesc_length;
8603 	}
8604 
8605 	if (bd_len > MODE_BLK_DESC_LENGTH) {
8606 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
8607 		    "sd_get_write_cache_enabled: Mode Sense returned invalid "
8608 		    "block descriptor length\n");
8609 		kmem_free(header, buflen);
8610 		return (EIO);
8611 	}
8612 
8613 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
8614 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
8615 		SD_ERROR(SD_LOG_COMMON, un, "sd_cache_control: Mode Sense"
8616 		    " caching page code mismatch %d\n",
8617 		    mode_caching_page->mode_page.code);
8618 		kmem_free(header, buflen);
8619 		return (EIO);
8620 	}
8621 	*is_enabled = mode_caching_page->wce;
8622 
8623 	kmem_free(header, buflen);
8624 	return (0);
8625 }
8626 
8627 /*
8628  *    Function: sd_get_nv_sup()
8629  *
8630  * Description: This routine is the driver entry point for
8631  * determining whether non-volatile cache is supported. This
8632  * determination process works as follows:
8633  *
8634  * 1. sd first queries sd.conf on whether
8635  * suppress_cache_flush bit is set for this device.
8636  *
8637  * 2. if not there, then queries the internal disk table.
8638  *
8639  * 3. if either sd.conf or internal disk table specifies
8640  * cache flush be suppressed, we don't bother checking
8641  * NV_SUP bit.
8642  *
8643  * If SUPPRESS_CACHE_FLUSH bit is not set to 1, sd queries
8644  * the optional INQUIRY VPD page 0x86. If the device
8645  * supports VPD page 0x86, sd examines the NV_SUP
8646  * (non-volatile cache support) bit in the INQUIRY VPD page
8647  * 0x86:
8648  *   o If NV_SUP bit is set, sd assumes the device has a
8649  *   non-volatile cache and set the
8650  *   un_f_sync_nv_supported to TRUE.
8651  *   o Otherwise cache is not non-volatile,
8652  *   un_f_sync_nv_supported is set to FALSE.
8653  *
8654  * Arguments: un - driver soft state (unit) structure
8655  *
8656  * Return Code:
8657  *
8658  *     Context: Kernel Thread
8659  */
8660 
8661 static void
8662 sd_get_nv_sup(struct sd_lun *un)
8663 {
8664 	int		rval		= 0;
8665 	uchar_t		*inq86		= NULL;
8666 	size_t		inq86_len	= MAX_INQUIRY_SIZE;
8667 	size_t		inq86_resid	= 0;
8668 	struct		dk_callback *dkc;
8669 
8670 	ASSERT(un != NULL);
8671 
8672 	mutex_enter(SD_MUTEX(un));
8673 
8674 	/*
8675 	 * Be conservative on the device's support of
8676 	 * SYNC_NV bit: un_f_sync_nv_supported is
8677 	 * initialized to be false.
8678 	 */
8679 	un->un_f_sync_nv_supported = FALSE;
8680 
8681 	/*
8682 	 * If either sd.conf or internal disk table
8683 	 * specifies cache flush be suppressed, then
8684 	 * we don't bother checking NV_SUP bit.
8685 	 */
8686 	if (un->un_f_suppress_cache_flush == TRUE) {
8687 		mutex_exit(SD_MUTEX(un));
8688 		return;
8689 	}
8690 
8691 	if (sd_check_vpd_page_support(un) == 0 &&
8692 	    un->un_vpd_page_mask & SD_VPD_EXTENDED_DATA_PG) {
8693 		mutex_exit(SD_MUTEX(un));
8694 		/* collect page 86 data if available */
8695 		inq86 = kmem_zalloc(inq86_len, KM_SLEEP);
8696 		rval = sd_send_scsi_INQUIRY(un, inq86, inq86_len,
8697 		    0x01, 0x86, &inq86_resid);
8698 
8699 		if (rval == 0 && (inq86_len - inq86_resid > 6)) {
8700 			SD_TRACE(SD_LOG_COMMON, un,
8701 			    "sd_get_nv_sup: \
8702 			    successfully get VPD page: %x \
8703 			    PAGE LENGTH: %x BYTE 6: %x\n",
8704 			    inq86[1], inq86[3], inq86[6]);
8705 
8706 			mutex_enter(SD_MUTEX(un));
8707 			/*
8708 			 * check the value of NV_SUP bit: only if the device
8709 			 * reports NV_SUP bit to be 1, the
8710 			 * un_f_sync_nv_supported bit will be set to true.
8711 			 */
8712 			if (inq86[6] & SD_VPD_NV_SUP) {
8713 				un->un_f_sync_nv_supported = TRUE;
8714 			}
8715 			mutex_exit(SD_MUTEX(un));
8716 		}
8717 		kmem_free(inq86, inq86_len);
8718 	} else {
8719 		mutex_exit(SD_MUTEX(un));
8720 	}
8721 
8722 	/*
8723 	 * Send a SYNC CACHE command to check whether
8724 	 * SYNC_NV bit is supported. This command should have
8725 	 * un_f_sync_nv_supported set to correct value.
8726 	 */
8727 	mutex_enter(SD_MUTEX(un));
8728 	if (un->un_f_sync_nv_supported) {
8729 		mutex_exit(SD_MUTEX(un));
8730 		dkc = kmem_zalloc(sizeof (struct dk_callback), KM_SLEEP);
8731 		dkc->dkc_flag = FLUSH_VOLATILE;
8732 		(void) sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
8733 
8734 		/*
8735 		 * Send a TEST UNIT READY command to the device. This should
8736 		 * clear any outstanding UNIT ATTENTION that may be present.
8737 		 */
8738 		(void) sd_send_scsi_TEST_UNIT_READY(un, SD_DONT_RETRY_TUR);
8739 
8740 		kmem_free(dkc, sizeof (struct dk_callback));
8741 	} else {
8742 		mutex_exit(SD_MUTEX(un));
8743 	}
8744 
8745 	SD_TRACE(SD_LOG_COMMON, un, "sd_get_nv_sup: \
8746 	    un_f_suppress_cache_flush is set to %d\n",
8747 	    un->un_f_suppress_cache_flush);
8748 }
8749 
8750 /*
8751  *    Function: sd_make_device
8752  *
8753  * Description: Utility routine to return the Solaris device number from
8754  *		the data in the device's dev_info structure.
8755  *
8756  * Return Code: The Solaris device number
8757  *
8758  *     Context: Any
8759  */
8760 
8761 static dev_t
8762 sd_make_device(dev_info_t *devi)
8763 {
8764 	return (makedevice(ddi_name_to_major(ddi_get_name(devi)),
8765 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
8766 }
8767 
8768 
8769 /*
8770  *    Function: sd_pm_entry
8771  *
8772  * Description: Called at the start of a new command to manage power
8773  *		and busy status of a device. This includes determining whether
8774  *		the current power state of the device is sufficient for
8775  *		performing the command or whether it must be changed.
8776  *		The PM framework is notified appropriately.
8777  *		Only with a return status of DDI_SUCCESS will the
8778  *		component be busy to the framework.
8779  *
8780  *		All callers of sd_pm_entry must check the return status
8781  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
8782  *		of DDI_FAILURE indicates the device failed to power up.
8783  *		In this case un_pm_count has been adjusted so the result
8784  *		on exit is still powered down, ie. count is less than 0.
8785  *		Calling sd_pm_exit with this count value hits an ASSERT.
8786  *
8787  * Return Code: DDI_SUCCESS or DDI_FAILURE
8788  *
8789  *     Context: Kernel thread context.
8790  */
8791 
8792 static int
8793 sd_pm_entry(struct sd_lun *un)
8794 {
8795 	int return_status = DDI_SUCCESS;
8796 
8797 	ASSERT(!mutex_owned(SD_MUTEX(un)));
8798 	ASSERT(!mutex_owned(&un->un_pm_mutex));
8799 
8800 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
8801 
8802 	if (un->un_f_pm_is_enabled == FALSE) {
8803 		SD_TRACE(SD_LOG_IO_PM, un,
8804 		    "sd_pm_entry: exiting, PM not enabled\n");
8805 		return (return_status);
8806 	}
8807 
8808 	/*
8809 	 * Just increment a counter if PM is enabled. On the transition from
8810 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
8811 	 * the count with each IO and mark the device as idle when the count
8812 	 * hits 0.
8813 	 *
8814 	 * If the count is less than 0 the device is powered down. If a powered
8815 	 * down device is successfully powered up then the count must be
8816 	 * incremented to reflect the power up. Note that it'll get incremented
8817 	 * a second time to become busy.
8818 	 *
8819 	 * Because the following has the potential to change the device state
8820 	 * and must release the un_pm_mutex to do so, only one thread can be
8821 	 * allowed through at a time.
8822 	 */
8823 
8824 	mutex_enter(&un->un_pm_mutex);
8825 	while (un->un_pm_busy == TRUE) {
8826 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
8827 	}
8828 	un->un_pm_busy = TRUE;
8829 
8830 	if (un->un_pm_count < 1) {
8831 
8832 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
8833 
8834 		/*
8835 		 * Indicate we are now busy so the framework won't attempt to
8836 		 * power down the device. This call will only fail if either
8837 		 * we passed a bad component number or the device has no
8838 		 * components. Neither of these should ever happen.
8839 		 */
8840 		mutex_exit(&un->un_pm_mutex);
8841 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
8842 		ASSERT(return_status == DDI_SUCCESS);
8843 
8844 		mutex_enter(&un->un_pm_mutex);
8845 
8846 		if (un->un_pm_count < 0) {
8847 			mutex_exit(&un->un_pm_mutex);
8848 
8849 			SD_TRACE(SD_LOG_IO_PM, un,
8850 			    "sd_pm_entry: power up component\n");
8851 
8852 			/*
8853 			 * pm_raise_power will cause sdpower to be called
8854 			 * which brings the device power level to the
8855 			 * desired state, ON in this case. If successful,
8856 			 * un_pm_count and un_power_level will be updated
8857 			 * appropriately.
8858 			 */
8859 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
8860 			    SD_SPINDLE_ON);
8861 
8862 			mutex_enter(&un->un_pm_mutex);
8863 
8864 			if (return_status != DDI_SUCCESS) {
8865 				/*
8866 				 * Power up failed.
8867 				 * Idle the device and adjust the count
8868 				 * so the result on exit is that we're
8869 				 * still powered down, ie. count is less than 0.
8870 				 */
8871 				SD_TRACE(SD_LOG_IO_PM, un,
8872 				    "sd_pm_entry: power up failed,"
8873 				    " idle the component\n");
8874 
8875 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8876 				un->un_pm_count--;
8877 			} else {
8878 				/*
8879 				 * Device is powered up, verify the
8880 				 * count is non-negative.
8881 				 * This is debug only.
8882 				 */
8883 				ASSERT(un->un_pm_count == 0);
8884 			}
8885 		}
8886 
8887 		if (return_status == DDI_SUCCESS) {
8888 			/*
8889 			 * For performance, now that the device has been tagged
8890 			 * as busy, and it's known to be powered up, update the
8891 			 * chain types to use jump tables that do not include
8892 			 * pm. This significantly lowers the overhead and
8893 			 * therefore improves performance.
8894 			 */
8895 
8896 			mutex_exit(&un->un_pm_mutex);
8897 			mutex_enter(SD_MUTEX(un));
8898 			SD_TRACE(SD_LOG_IO_PM, un,
8899 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
8900 			    un->un_uscsi_chain_type);
8901 
8902 			if (un->un_f_non_devbsize_supported) {
8903 				un->un_buf_chain_type =
8904 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
8905 			} else {
8906 				un->un_buf_chain_type =
8907 				    SD_CHAIN_INFO_DISK_NO_PM;
8908 			}
8909 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8910 
8911 			SD_TRACE(SD_LOG_IO_PM, un,
8912 			    "             changed  uscsi_chain_type to   %d\n",
8913 			    un->un_uscsi_chain_type);
8914 			mutex_exit(SD_MUTEX(un));
8915 			mutex_enter(&un->un_pm_mutex);
8916 
8917 			if (un->un_pm_idle_timeid == NULL) {
8918 				/* 300 ms. */
8919 				un->un_pm_idle_timeid =
8920 				    timeout(sd_pm_idletimeout_handler, un,
8921 				    (drv_usectohz((clock_t)300000)));
8922 				/*
8923 				 * Include an extra call to busy which keeps the
8924 				 * device busy with-respect-to the PM layer
8925 				 * until the timer fires, at which time it'll
8926 				 * get the extra idle call.
8927 				 */
8928 				(void) pm_busy_component(SD_DEVINFO(un), 0);
8929 			}
8930 		}
8931 	}
8932 	un->un_pm_busy = FALSE;
8933 	/* Next... */
8934 	cv_signal(&un->un_pm_busy_cv);
8935 
8936 	un->un_pm_count++;
8937 
8938 	SD_TRACE(SD_LOG_IO_PM, un,
8939 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
8940 
8941 	mutex_exit(&un->un_pm_mutex);
8942 
8943 	return (return_status);
8944 }
8945 
8946 
8947 /*
8948  *    Function: sd_pm_exit
8949  *
8950  * Description: Called at the completion of a command to manage busy
8951  *		status for the device. If the device becomes idle the
8952  *		PM framework is notified.
8953  *
8954  *     Context: Kernel thread context
8955  */
8956 
8957 static void
8958 sd_pm_exit(struct sd_lun *un)
8959 {
8960 	ASSERT(!mutex_owned(SD_MUTEX(un)));
8961 	ASSERT(!mutex_owned(&un->un_pm_mutex));
8962 
8963 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
8964 
8965 	/*
8966 	 * After attach the following flag is only read, so don't
8967 	 * take the penalty of acquiring a mutex for it.
8968 	 */
8969 	if (un->un_f_pm_is_enabled == TRUE) {
8970 
8971 		mutex_enter(&un->un_pm_mutex);
8972 		un->un_pm_count--;
8973 
8974 		SD_TRACE(SD_LOG_IO_PM, un,
8975 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
8976 
8977 		ASSERT(un->un_pm_count >= 0);
8978 		if (un->un_pm_count == 0) {
8979 			mutex_exit(&un->un_pm_mutex);
8980 
8981 			SD_TRACE(SD_LOG_IO_PM, un,
8982 			    "sd_pm_exit: idle component\n");
8983 
8984 			(void) pm_idle_component(SD_DEVINFO(un), 0);
8985 
8986 		} else {
8987 			mutex_exit(&un->un_pm_mutex);
8988 		}
8989 	}
8990 
8991 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
8992 }
8993 
8994 
8995 /*
8996  *    Function: sdopen
8997  *
8998  * Description: Driver's open(9e) entry point function.
8999  *
9000  *   Arguments: dev_i   - pointer to device number
9001  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
9002  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9003  *		cred_p  - user credential pointer
9004  *
9005  * Return Code: EINVAL
9006  *		ENXIO
9007  *		EIO
9008  *		EROFS
9009  *		EBUSY
9010  *
9011  *     Context: Kernel thread context
9012  */
9013 /* ARGSUSED */
9014 static int
9015 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
9016 {
9017 	struct sd_lun	*un;
9018 	int		nodelay;
9019 	int		part;
9020 	uint64_t	partmask;
9021 	int		instance;
9022 	dev_t		dev;
9023 	int		rval = EIO;
9024 	diskaddr_t	nblks = 0;
9025 
9026 	/* Validate the open type */
9027 	if (otyp >= OTYPCNT) {
9028 		return (EINVAL);
9029 	}
9030 
9031 	dev = *dev_p;
9032 	instance = SDUNIT(dev);
9033 	mutex_enter(&sd_detach_mutex);
9034 
9035 	/*
9036 	 * Fail the open if there is no softstate for the instance, or
9037 	 * if another thread somewhere is trying to detach the instance.
9038 	 */
9039 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
9040 	    (un->un_detach_count != 0)) {
9041 		mutex_exit(&sd_detach_mutex);
9042 		/*
9043 		 * The probe cache only needs to be cleared when open (9e) fails
9044 		 * with ENXIO (4238046).
9045 		 */
9046 		/*
9047 		 * un-conditionally clearing probe cache is ok with
9048 		 * separate sd/ssd binaries
9049 		 * x86 platform can be an issue with both parallel
9050 		 * and fibre in 1 binary
9051 		 */
9052 		sd_scsi_clear_probe_cache();
9053 		return (ENXIO);
9054 	}
9055 
9056 	/*
9057 	 * The un_layer_count is to prevent another thread in specfs from
9058 	 * trying to detach the instance, which can happen when we are
9059 	 * called from a higher-layer driver instead of thru specfs.
9060 	 * This will not be needed when DDI provides a layered driver
9061 	 * interface that allows specfs to know that an instance is in
9062 	 * use by a layered driver & should not be detached.
9063 	 *
9064 	 * Note: the semantics for layered driver opens are exactly one
9065 	 * close for every open.
9066 	 */
9067 	if (otyp == OTYP_LYR) {
9068 		un->un_layer_count++;
9069 	}
9070 
9071 	/*
9072 	 * Keep a count of the current # of opens in progress. This is because
9073 	 * some layered drivers try to call us as a regular open. This can
9074 	 * cause problems that we cannot prevent, however by keeping this count
9075 	 * we can at least keep our open and detach routines from racing against
9076 	 * each other under such conditions.
9077 	 */
9078 	un->un_opens_in_progress++;
9079 	mutex_exit(&sd_detach_mutex);
9080 
9081 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
9082 	part	 = SDPART(dev);
9083 	partmask = 1 << part;
9084 
9085 	/*
9086 	 * We use a semaphore here in order to serialize
9087 	 * open and close requests on the device.
9088 	 */
9089 	sema_p(&un->un_semoclose);
9090 
9091 	mutex_enter(SD_MUTEX(un));
9092 
9093 	/*
9094 	 * All device accesses go thru sdstrategy() where we check
9095 	 * on suspend status but there could be a scsi_poll command,
9096 	 * which bypasses sdstrategy(), so we need to check pm
9097 	 * status.
9098 	 */
9099 
9100 	if (!nodelay) {
9101 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9102 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9103 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9104 		}
9105 
9106 		mutex_exit(SD_MUTEX(un));
9107 		if (sd_pm_entry(un) != DDI_SUCCESS) {
9108 			rval = EIO;
9109 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
9110 			    "sdopen: sd_pm_entry failed\n");
9111 			goto open_failed_with_pm;
9112 		}
9113 		mutex_enter(SD_MUTEX(un));
9114 	}
9115 
9116 	/* check for previous exclusive open */
9117 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
9118 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
9119 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
9120 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
9121 
9122 	if (un->un_exclopen & (partmask)) {
9123 		goto excl_open_fail;
9124 	}
9125 
9126 	if (flag & FEXCL) {
9127 		int i;
9128 		if (un->un_ocmap.lyropen[part]) {
9129 			goto excl_open_fail;
9130 		}
9131 		for (i = 0; i < (OTYPCNT - 1); i++) {
9132 			if (un->un_ocmap.regopen[i] & (partmask)) {
9133 				goto excl_open_fail;
9134 			}
9135 		}
9136 	}
9137 
9138 	/*
9139 	 * Check the write permission if this is a removable media device,
9140 	 * NDELAY has not been set, and writable permission is requested.
9141 	 *
9142 	 * Note: If NDELAY was set and this is write-protected media the WRITE
9143 	 * attempt will fail with EIO as part of the I/O processing. This is a
9144 	 * more permissive implementation that allows the open to succeed and
9145 	 * WRITE attempts to fail when appropriate.
9146 	 */
9147 	if (un->un_f_chk_wp_open) {
9148 		if ((flag & FWRITE) && (!nodelay)) {
9149 			mutex_exit(SD_MUTEX(un));
9150 			/*
9151 			 * Defer the check for write permission on writable
9152 			 * DVD drive till sdstrategy and will not fail open even
9153 			 * if FWRITE is set as the device can be writable
9154 			 * depending upon the media and the media can change
9155 			 * after the call to open().
9156 			 */
9157 			if (un->un_f_dvdram_writable_device == FALSE) {
9158 				if (ISCD(un) || sr_check_wp(dev)) {
9159 				rval = EROFS;
9160 				mutex_enter(SD_MUTEX(un));
9161 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9162 				    "write to cd or write protected media\n");
9163 				goto open_fail;
9164 				}
9165 			}
9166 			mutex_enter(SD_MUTEX(un));
9167 		}
9168 	}
9169 
9170 	/*
9171 	 * If opening in NDELAY/NONBLOCK mode, just return.
9172 	 * Check if disk is ready and has a valid geometry later.
9173 	 */
9174 	if (!nodelay) {
9175 		mutex_exit(SD_MUTEX(un));
9176 		rval = sd_ready_and_valid(un);
9177 		mutex_enter(SD_MUTEX(un));
9178 		/*
9179 		 * Fail if device is not ready or if the number of disk
9180 		 * blocks is zero or negative for non CD devices.
9181 		 */
9182 
9183 		nblks = 0;
9184 
9185 		if (rval == SD_READY_VALID && (!ISCD(un))) {
9186 			/* if cmlb_partinfo fails, nblks remains 0 */
9187 			mutex_exit(SD_MUTEX(un));
9188 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
9189 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
9190 			mutex_enter(SD_MUTEX(un));
9191 		}
9192 
9193 		if ((rval != SD_READY_VALID) ||
9194 		    (!ISCD(un) && nblks <= 0)) {
9195 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
9196 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9197 			    "device not ready or invalid disk block value\n");
9198 			goto open_fail;
9199 		}
9200 #if defined(__i386) || defined(__amd64)
9201 	} else {
9202 		uchar_t *cp;
9203 		/*
9204 		 * x86 requires special nodelay handling, so that p0 is
9205 		 * always defined and accessible.
9206 		 * Invalidate geometry only if device is not already open.
9207 		 */
9208 		cp = &un->un_ocmap.chkd[0];
9209 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9210 			if (*cp != (uchar_t)0) {
9211 				break;
9212 			}
9213 			cp++;
9214 		}
9215 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9216 			mutex_exit(SD_MUTEX(un));
9217 			cmlb_invalidate(un->un_cmlbhandle,
9218 			    (void *)SD_PATH_DIRECT);
9219 			mutex_enter(SD_MUTEX(un));
9220 		}
9221 
9222 #endif
9223 	}
9224 
9225 	if (otyp == OTYP_LYR) {
9226 		un->un_ocmap.lyropen[part]++;
9227 	} else {
9228 		un->un_ocmap.regopen[otyp] |= partmask;
9229 	}
9230 
9231 	/* Set up open and exclusive open flags */
9232 	if (flag & FEXCL) {
9233 		un->un_exclopen |= (partmask);
9234 	}
9235 
9236 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9237 	    "open of part %d type %d\n", part, otyp);
9238 
9239 	mutex_exit(SD_MUTEX(un));
9240 	if (!nodelay) {
9241 		sd_pm_exit(un);
9242 	}
9243 
9244 	sema_v(&un->un_semoclose);
9245 
9246 	mutex_enter(&sd_detach_mutex);
9247 	un->un_opens_in_progress--;
9248 	mutex_exit(&sd_detach_mutex);
9249 
9250 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
9251 	return (DDI_SUCCESS);
9252 
9253 excl_open_fail:
9254 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
9255 	rval = EBUSY;
9256 
9257 open_fail:
9258 	mutex_exit(SD_MUTEX(un));
9259 
9260 	/*
9261 	 * On a failed open we must exit the pm management.
9262 	 */
9263 	if (!nodelay) {
9264 		sd_pm_exit(un);
9265 	}
9266 open_failed_with_pm:
9267 	sema_v(&un->un_semoclose);
9268 
9269 	mutex_enter(&sd_detach_mutex);
9270 	un->un_opens_in_progress--;
9271 	if (otyp == OTYP_LYR) {
9272 		un->un_layer_count--;
9273 	}
9274 	mutex_exit(&sd_detach_mutex);
9275 
9276 	return (rval);
9277 }
9278 
9279 
9280 /*
9281  *    Function: sdclose
9282  *
9283  * Description: Driver's close(9e) entry point function.
9284  *
9285  *   Arguments: dev    - device number
9286  *		flag   - file status flag, informational only
9287  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9288  *		cred_p - user credential pointer
9289  *
9290  * Return Code: ENXIO
9291  *
9292  *     Context: Kernel thread context
9293  */
9294 /* ARGSUSED */
9295 static int
9296 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
9297 {
9298 	struct sd_lun	*un;
9299 	uchar_t		*cp;
9300 	int		part;
9301 	int		nodelay;
9302 	int		rval = 0;
9303 
9304 	/* Validate the open type */
9305 	if (otyp >= OTYPCNT) {
9306 		return (ENXIO);
9307 	}
9308 
9309 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9310 		return (ENXIO);
9311 	}
9312 
9313 	part = SDPART(dev);
9314 	nodelay = flag & (FNDELAY | FNONBLOCK);
9315 
9316 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
9317 	    "sdclose: close of part %d type %d\n", part, otyp);
9318 
9319 	/*
9320 	 * We use a semaphore here in order to serialize
9321 	 * open and close requests on the device.
9322 	 */
9323 	sema_p(&un->un_semoclose);
9324 
9325 	mutex_enter(SD_MUTEX(un));
9326 
9327 	/* Don't proceed if power is being changed. */
9328 	while (un->un_state == SD_STATE_PM_CHANGING) {
9329 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9330 	}
9331 
9332 	if (un->un_exclopen & (1 << part)) {
9333 		un->un_exclopen &= ~(1 << part);
9334 	}
9335 
9336 	/* Update the open partition map */
9337 	if (otyp == OTYP_LYR) {
9338 		un->un_ocmap.lyropen[part] -= 1;
9339 	} else {
9340 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
9341 	}
9342 
9343 	cp = &un->un_ocmap.chkd[0];
9344 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9345 		if (*cp != NULL) {
9346 			break;
9347 		}
9348 		cp++;
9349 	}
9350 
9351 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9352 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
9353 
9354 		/*
9355 		 * We avoid persistance upon the last close, and set
9356 		 * the throttle back to the maximum.
9357 		 */
9358 		un->un_throttle = un->un_saved_throttle;
9359 
9360 		if (un->un_state == SD_STATE_OFFLINE) {
9361 			if (un->un_f_is_fibre == FALSE) {
9362 				scsi_log(SD_DEVINFO(un), sd_label,
9363 				    CE_WARN, "offline\n");
9364 			}
9365 			mutex_exit(SD_MUTEX(un));
9366 			cmlb_invalidate(un->un_cmlbhandle,
9367 			    (void *)SD_PATH_DIRECT);
9368 			mutex_enter(SD_MUTEX(un));
9369 
9370 		} else {
9371 			/*
9372 			 * Flush any outstanding writes in NVRAM cache.
9373 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
9374 			 * cmd, it may not work for non-Pluto devices.
9375 			 * SYNCHRONIZE CACHE is not required for removables,
9376 			 * except DVD-RAM drives.
9377 			 *
9378 			 * Also note: because SYNCHRONIZE CACHE is currently
9379 			 * the only command issued here that requires the
9380 			 * drive be powered up, only do the power up before
9381 			 * sending the Sync Cache command. If additional
9382 			 * commands are added which require a powered up
9383 			 * drive, the following sequence may have to change.
9384 			 *
9385 			 * And finally, note that parallel SCSI on SPARC
9386 			 * only issues a Sync Cache to DVD-RAM, a newly
9387 			 * supported device.
9388 			 */
9389 #if defined(__i386) || defined(__amd64)
9390 			if (un->un_f_sync_cache_supported ||
9391 			    un->un_f_dvdram_writable_device == TRUE) {
9392 #else
9393 			if (un->un_f_dvdram_writable_device == TRUE) {
9394 #endif
9395 				mutex_exit(SD_MUTEX(un));
9396 				if (sd_pm_entry(un) == DDI_SUCCESS) {
9397 					rval =
9398 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
9399 					    NULL);
9400 					/* ignore error if not supported */
9401 					if (rval == ENOTSUP) {
9402 						rval = 0;
9403 					} else if (rval != 0) {
9404 						rval = EIO;
9405 					}
9406 					sd_pm_exit(un);
9407 				} else {
9408 					rval = EIO;
9409 				}
9410 				mutex_enter(SD_MUTEX(un));
9411 			}
9412 
9413 			/*
9414 			 * For devices which supports DOOR_LOCK, send an ALLOW
9415 			 * MEDIA REMOVAL command, but don't get upset if it
9416 			 * fails. We need to raise the power of the drive before
9417 			 * we can call sd_send_scsi_DOORLOCK()
9418 			 */
9419 			if (un->un_f_doorlock_supported) {
9420 				mutex_exit(SD_MUTEX(un));
9421 				if (sd_pm_entry(un) == DDI_SUCCESS) {
9422 					rval = sd_send_scsi_DOORLOCK(un,
9423 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
9424 
9425 					sd_pm_exit(un);
9426 					if (ISCD(un) && (rval != 0) &&
9427 					    (nodelay != 0)) {
9428 						rval = ENXIO;
9429 					}
9430 				} else {
9431 					rval = EIO;
9432 				}
9433 				mutex_enter(SD_MUTEX(un));
9434 			}
9435 
9436 			/*
9437 			 * If a device has removable media, invalidate all
9438 			 * parameters related to media, such as geometry,
9439 			 * blocksize, and blockcount.
9440 			 */
9441 			if (un->un_f_has_removable_media) {
9442 				sr_ejected(un);
9443 			}
9444 
9445 			/*
9446 			 * Destroy the cache (if it exists) which was
9447 			 * allocated for the write maps since this is
9448 			 * the last close for this media.
9449 			 */
9450 			if (un->un_wm_cache) {
9451 				/*
9452 				 * Check if there are pending commands.
9453 				 * and if there are give a warning and
9454 				 * do not destroy the cache.
9455 				 */
9456 				if (un->un_ncmds_in_driver > 0) {
9457 					scsi_log(SD_DEVINFO(un),
9458 					    sd_label, CE_WARN,
9459 					    "Unable to clean up memory "
9460 					    "because of pending I/O\n");
9461 				} else {
9462 					kmem_cache_destroy(
9463 					    un->un_wm_cache);
9464 					un->un_wm_cache = NULL;
9465 				}
9466 			}
9467 		}
9468 	}
9469 
9470 	mutex_exit(SD_MUTEX(un));
9471 	sema_v(&un->un_semoclose);
9472 
9473 	if (otyp == OTYP_LYR) {
9474 		mutex_enter(&sd_detach_mutex);
9475 		/*
9476 		 * The detach routine may run when the layer count
9477 		 * drops to zero.
9478 		 */
9479 		un->un_layer_count--;
9480 		mutex_exit(&sd_detach_mutex);
9481 	}
9482 
9483 	return (rval);
9484 }
9485 
9486 
9487 /*
9488  *    Function: sd_ready_and_valid
9489  *
9490  * Description: Test if device is ready and has a valid geometry.
9491  *
9492  *   Arguments: dev - device number
9493  *		un  - driver soft state (unit) structure
9494  *
9495  * Return Code: SD_READY_VALID		ready and valid label
9496  *		SD_NOT_READY_VALID	not ready, no label
9497  *		SD_RESERVED_BY_OTHERS	reservation conflict
9498  *
9499  *     Context: Never called at interrupt context.
9500  */
9501 
9502 static int
9503 sd_ready_and_valid(struct sd_lun *un)
9504 {
9505 	struct sd_errstats	*stp;
9506 	uint64_t		capacity;
9507 	uint_t			lbasize;
9508 	int			rval = SD_READY_VALID;
9509 	char			name_str[48];
9510 	int			is_valid;
9511 
9512 	ASSERT(un != NULL);
9513 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9514 
9515 	mutex_enter(SD_MUTEX(un));
9516 	/*
9517 	 * If a device has removable media, we must check if media is
9518 	 * ready when checking if this device is ready and valid.
9519 	 */
9520 	if (un->un_f_has_removable_media) {
9521 		mutex_exit(SD_MUTEX(un));
9522 		if (sd_send_scsi_TEST_UNIT_READY(un, 0) != 0) {
9523 			rval = SD_NOT_READY_VALID;
9524 			mutex_enter(SD_MUTEX(un));
9525 			goto done;
9526 		}
9527 
9528 		is_valid = SD_IS_VALID_LABEL(un);
9529 		mutex_enter(SD_MUTEX(un));
9530 		if (!is_valid ||
9531 		    (un->un_f_blockcount_is_valid == FALSE) ||
9532 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
9533 
9534 			/* capacity has to be read every open. */
9535 			mutex_exit(SD_MUTEX(un));
9536 			if (sd_send_scsi_READ_CAPACITY(un, &capacity,
9537 			    &lbasize, SD_PATH_DIRECT) != 0) {
9538 				cmlb_invalidate(un->un_cmlbhandle,
9539 				    (void *)SD_PATH_DIRECT);
9540 				mutex_enter(SD_MUTEX(un));
9541 				rval = SD_NOT_READY_VALID;
9542 				goto done;
9543 			} else {
9544 				mutex_enter(SD_MUTEX(un));
9545 				sd_update_block_info(un, lbasize, capacity);
9546 			}
9547 		}
9548 
9549 		/*
9550 		 * Check if the media in the device is writable or not.
9551 		 */
9552 		if (!is_valid && ISCD(un)) {
9553 			sd_check_for_writable_cd(un, SD_PATH_DIRECT);
9554 		}
9555 
9556 	} else {
9557 		/*
9558 		 * Do a test unit ready to clear any unit attention from non-cd
9559 		 * devices.
9560 		 */
9561 		mutex_exit(SD_MUTEX(un));
9562 		(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
9563 		mutex_enter(SD_MUTEX(un));
9564 	}
9565 
9566 
9567 	/*
9568 	 * If this is a non 512 block device, allocate space for
9569 	 * the wmap cache. This is being done here since every time
9570 	 * a media is changed this routine will be called and the
9571 	 * block size is a function of media rather than device.
9572 	 */
9573 	if (un->un_f_non_devbsize_supported && NOT_DEVBSIZE(un)) {
9574 		if (!(un->un_wm_cache)) {
9575 			(void) snprintf(name_str, sizeof (name_str),
9576 			    "%s%d_cache",
9577 			    ddi_driver_name(SD_DEVINFO(un)),
9578 			    ddi_get_instance(SD_DEVINFO(un)));
9579 			un->un_wm_cache = kmem_cache_create(
9580 			    name_str, sizeof (struct sd_w_map),
9581 			    8, sd_wm_cache_constructor,
9582 			    sd_wm_cache_destructor, NULL,
9583 			    (void *)un, NULL, 0);
9584 			if (!(un->un_wm_cache)) {
9585 					rval = ENOMEM;
9586 					goto done;
9587 			}
9588 		}
9589 	}
9590 
9591 	if (un->un_state == SD_STATE_NORMAL) {
9592 		/*
9593 		 * If the target is not yet ready here (defined by a TUR
9594 		 * failure), invalidate the geometry and print an 'offline'
9595 		 * message. This is a legacy message, as the state of the
9596 		 * target is not actually changed to SD_STATE_OFFLINE.
9597 		 *
9598 		 * If the TUR fails for EACCES (Reservation Conflict),
9599 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
9600 		 * reservation conflict. If the TUR fails for other
9601 		 * reasons, SD_NOT_READY_VALID will be returned.
9602 		 */
9603 		int err;
9604 
9605 		mutex_exit(SD_MUTEX(un));
9606 		err = sd_send_scsi_TEST_UNIT_READY(un, 0);
9607 		mutex_enter(SD_MUTEX(un));
9608 
9609 		if (err != 0) {
9610 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
9611 			    "offline or reservation conflict\n");
9612 			mutex_exit(SD_MUTEX(un));
9613 			cmlb_invalidate(un->un_cmlbhandle,
9614 			    (void *)SD_PATH_DIRECT);
9615 			mutex_enter(SD_MUTEX(un));
9616 			if (err == EACCES) {
9617 				rval = SD_RESERVED_BY_OTHERS;
9618 			} else {
9619 				rval = SD_NOT_READY_VALID;
9620 			}
9621 			goto done;
9622 		}
9623 	}
9624 
9625 	if (un->un_f_format_in_progress == FALSE) {
9626 		mutex_exit(SD_MUTEX(un));
9627 		if (cmlb_validate(un->un_cmlbhandle, 0,
9628 		    (void *)SD_PATH_DIRECT) != 0) {
9629 			rval = SD_NOT_READY_VALID;
9630 			mutex_enter(SD_MUTEX(un));
9631 			goto done;
9632 		}
9633 		if (un->un_f_pkstats_enabled) {
9634 			sd_set_pstats(un);
9635 			SD_TRACE(SD_LOG_IO_PARTITION, un,
9636 			    "sd_ready_and_valid: un:0x%p pstats created and "
9637 			    "set\n", un);
9638 		}
9639 		mutex_enter(SD_MUTEX(un));
9640 	}
9641 
9642 	/*
9643 	 * If this device supports DOOR_LOCK command, try and send
9644 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
9645 	 * if it fails. For a CD, however, it is an error
9646 	 */
9647 	if (un->un_f_doorlock_supported) {
9648 		mutex_exit(SD_MUTEX(un));
9649 		if ((sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
9650 		    SD_PATH_DIRECT) != 0) && ISCD(un)) {
9651 			rval = SD_NOT_READY_VALID;
9652 			mutex_enter(SD_MUTEX(un));
9653 			goto done;
9654 		}
9655 		mutex_enter(SD_MUTEX(un));
9656 	}
9657 
9658 	/* The state has changed, inform the media watch routines */
9659 	un->un_mediastate = DKIO_INSERTED;
9660 	cv_broadcast(&un->un_state_cv);
9661 	rval = SD_READY_VALID;
9662 
9663 done:
9664 
9665 	/*
9666 	 * Initialize the capacity kstat value, if no media previously
9667 	 * (capacity kstat is 0) and a media has been inserted
9668 	 * (un_blockcount > 0).
9669 	 */
9670 	if (un->un_errstats != NULL) {
9671 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
9672 		if ((stp->sd_capacity.value.ui64 == 0) &&
9673 		    (un->un_f_blockcount_is_valid == TRUE)) {
9674 			stp->sd_capacity.value.ui64 =
9675 			    (uint64_t)((uint64_t)un->un_blockcount *
9676 			    un->un_sys_blocksize);
9677 		}
9678 	}
9679 
9680 	mutex_exit(SD_MUTEX(un));
9681 	return (rval);
9682 }
9683 
9684 
9685 /*
9686  *    Function: sdmin
9687  *
9688  * Description: Routine to limit the size of a data transfer. Used in
9689  *		conjunction with physio(9F).
9690  *
9691  *   Arguments: bp - pointer to the indicated buf(9S) struct.
9692  *
9693  *     Context: Kernel thread context.
9694  */
9695 
9696 static void
9697 sdmin(struct buf *bp)
9698 {
9699 	struct sd_lun	*un;
9700 	int		instance;
9701 
9702 	instance = SDUNIT(bp->b_edev);
9703 
9704 	un = ddi_get_soft_state(sd_state, instance);
9705 	ASSERT(un != NULL);
9706 
9707 	if (bp->b_bcount > un->un_max_xfer_size) {
9708 		bp->b_bcount = un->un_max_xfer_size;
9709 	}
9710 }
9711 
9712 
9713 /*
9714  *    Function: sdread
9715  *
9716  * Description: Driver's read(9e) entry point function.
9717  *
9718  *   Arguments: dev   - device number
9719  *		uio   - structure pointer describing where data is to be stored
9720  *			in user's space
9721  *		cred_p  - user credential pointer
9722  *
9723  * Return Code: ENXIO
9724  *		EIO
9725  *		EINVAL
9726  *		value returned by physio
9727  *
9728  *     Context: Kernel thread context.
9729  */
9730 /* ARGSUSED */
9731 static int
9732 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
9733 {
9734 	struct sd_lun	*un = NULL;
9735 	int		secmask;
9736 	int		err;
9737 
9738 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9739 		return (ENXIO);
9740 	}
9741 
9742 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9743 
9744 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9745 		mutex_enter(SD_MUTEX(un));
9746 		/*
9747 		 * Because the call to sd_ready_and_valid will issue I/O we
9748 		 * must wait here if either the device is suspended or
9749 		 * if it's power level is changing.
9750 		 */
9751 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9752 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9753 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9754 		}
9755 		un->un_ncmds_in_driver++;
9756 		mutex_exit(SD_MUTEX(un));
9757 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9758 			mutex_enter(SD_MUTEX(un));
9759 			un->un_ncmds_in_driver--;
9760 			ASSERT(un->un_ncmds_in_driver >= 0);
9761 			mutex_exit(SD_MUTEX(un));
9762 			return (EIO);
9763 		}
9764 		mutex_enter(SD_MUTEX(un));
9765 		un->un_ncmds_in_driver--;
9766 		ASSERT(un->un_ncmds_in_driver >= 0);
9767 		mutex_exit(SD_MUTEX(un));
9768 	}
9769 
9770 	/*
9771 	 * Read requests are restricted to multiples of the system block size.
9772 	 */
9773 	secmask = un->un_sys_blocksize - 1;
9774 
9775 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9776 		SD_ERROR(SD_LOG_READ_WRITE, un,
9777 		    "sdread: file offset not modulo %d\n",
9778 		    un->un_sys_blocksize);
9779 		err = EINVAL;
9780 	} else if (uio->uio_iov->iov_len & (secmask)) {
9781 		SD_ERROR(SD_LOG_READ_WRITE, un,
9782 		    "sdread: transfer length not modulo %d\n",
9783 		    un->un_sys_blocksize);
9784 		err = EINVAL;
9785 	} else {
9786 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
9787 	}
9788 	return (err);
9789 }
9790 
9791 
9792 /*
9793  *    Function: sdwrite
9794  *
9795  * Description: Driver's write(9e) entry point function.
9796  *
9797  *   Arguments: dev   - device number
9798  *		uio   - structure pointer describing where data is stored in
9799  *			user's space
9800  *		cred_p  - user credential pointer
9801  *
9802  * Return Code: ENXIO
9803  *		EIO
9804  *		EINVAL
9805  *		value returned by physio
9806  *
9807  *     Context: Kernel thread context.
9808  */
9809 /* ARGSUSED */
9810 static int
9811 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
9812 {
9813 	struct sd_lun	*un = NULL;
9814 	int		secmask;
9815 	int		err;
9816 
9817 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9818 		return (ENXIO);
9819 	}
9820 
9821 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9822 
9823 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9824 		mutex_enter(SD_MUTEX(un));
9825 		/*
9826 		 * Because the call to sd_ready_and_valid will issue I/O we
9827 		 * must wait here if either the device is suspended or
9828 		 * if it's power level is changing.
9829 		 */
9830 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9831 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9832 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9833 		}
9834 		un->un_ncmds_in_driver++;
9835 		mutex_exit(SD_MUTEX(un));
9836 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9837 			mutex_enter(SD_MUTEX(un));
9838 			un->un_ncmds_in_driver--;
9839 			ASSERT(un->un_ncmds_in_driver >= 0);
9840 			mutex_exit(SD_MUTEX(un));
9841 			return (EIO);
9842 		}
9843 		mutex_enter(SD_MUTEX(un));
9844 		un->un_ncmds_in_driver--;
9845 		ASSERT(un->un_ncmds_in_driver >= 0);
9846 		mutex_exit(SD_MUTEX(un));
9847 	}
9848 
9849 	/*
9850 	 * Write requests are restricted to multiples of the system block size.
9851 	 */
9852 	secmask = un->un_sys_blocksize - 1;
9853 
9854 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9855 		SD_ERROR(SD_LOG_READ_WRITE, un,
9856 		    "sdwrite: file offset not modulo %d\n",
9857 		    un->un_sys_blocksize);
9858 		err = EINVAL;
9859 	} else if (uio->uio_iov->iov_len & (secmask)) {
9860 		SD_ERROR(SD_LOG_READ_WRITE, un,
9861 		    "sdwrite: transfer length not modulo %d\n",
9862 		    un->un_sys_blocksize);
9863 		err = EINVAL;
9864 	} else {
9865 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
9866 	}
9867 	return (err);
9868 }
9869 
9870 
9871 /*
9872  *    Function: sdaread
9873  *
9874  * Description: Driver's aread(9e) entry point function.
9875  *
9876  *   Arguments: dev   - device number
9877  *		aio   - structure pointer describing where data is to be stored
9878  *		cred_p  - user credential pointer
9879  *
9880  * Return Code: ENXIO
9881  *		EIO
9882  *		EINVAL
9883  *		value returned by aphysio
9884  *
9885  *     Context: Kernel thread context.
9886  */
9887 /* ARGSUSED */
9888 static int
9889 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
9890 {
9891 	struct sd_lun	*un = NULL;
9892 	struct uio	*uio = aio->aio_uio;
9893 	int		secmask;
9894 	int		err;
9895 
9896 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9897 		return (ENXIO);
9898 	}
9899 
9900 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9901 
9902 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9903 		mutex_enter(SD_MUTEX(un));
9904 		/*
9905 		 * Because the call to sd_ready_and_valid will issue I/O we
9906 		 * must wait here if either the device is suspended or
9907 		 * if it's power level is changing.
9908 		 */
9909 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9910 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9911 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9912 		}
9913 		un->un_ncmds_in_driver++;
9914 		mutex_exit(SD_MUTEX(un));
9915 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9916 			mutex_enter(SD_MUTEX(un));
9917 			un->un_ncmds_in_driver--;
9918 			ASSERT(un->un_ncmds_in_driver >= 0);
9919 			mutex_exit(SD_MUTEX(un));
9920 			return (EIO);
9921 		}
9922 		mutex_enter(SD_MUTEX(un));
9923 		un->un_ncmds_in_driver--;
9924 		ASSERT(un->un_ncmds_in_driver >= 0);
9925 		mutex_exit(SD_MUTEX(un));
9926 	}
9927 
9928 	/*
9929 	 * Read requests are restricted to multiples of the system block size.
9930 	 */
9931 	secmask = un->un_sys_blocksize - 1;
9932 
9933 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9934 		SD_ERROR(SD_LOG_READ_WRITE, un,
9935 		    "sdaread: file offset not modulo %d\n",
9936 		    un->un_sys_blocksize);
9937 		err = EINVAL;
9938 	} else if (uio->uio_iov->iov_len & (secmask)) {
9939 		SD_ERROR(SD_LOG_READ_WRITE, un,
9940 		    "sdaread: transfer length not modulo %d\n",
9941 		    un->un_sys_blocksize);
9942 		err = EINVAL;
9943 	} else {
9944 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
9945 	}
9946 	return (err);
9947 }
9948 
9949 
9950 /*
9951  *    Function: sdawrite
9952  *
9953  * Description: Driver's awrite(9e) entry point function.
9954  *
9955  *   Arguments: dev   - device number
9956  *		aio   - structure pointer describing where data is stored
9957  *		cred_p  - user credential pointer
9958  *
9959  * Return Code: ENXIO
9960  *		EIO
9961  *		EINVAL
9962  *		value returned by aphysio
9963  *
9964  *     Context: Kernel thread context.
9965  */
9966 /* ARGSUSED */
9967 static int
9968 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
9969 {
9970 	struct sd_lun	*un = NULL;
9971 	struct uio	*uio = aio->aio_uio;
9972 	int		secmask;
9973 	int		err;
9974 
9975 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9976 		return (ENXIO);
9977 	}
9978 
9979 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9980 
9981 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9982 		mutex_enter(SD_MUTEX(un));
9983 		/*
9984 		 * Because the call to sd_ready_and_valid will issue I/O we
9985 		 * must wait here if either the device is suspended or
9986 		 * if it's power level is changing.
9987 		 */
9988 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9989 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9990 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9991 		}
9992 		un->un_ncmds_in_driver++;
9993 		mutex_exit(SD_MUTEX(un));
9994 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9995 			mutex_enter(SD_MUTEX(un));
9996 			un->un_ncmds_in_driver--;
9997 			ASSERT(un->un_ncmds_in_driver >= 0);
9998 			mutex_exit(SD_MUTEX(un));
9999 			return (EIO);
10000 		}
10001 		mutex_enter(SD_MUTEX(un));
10002 		un->un_ncmds_in_driver--;
10003 		ASSERT(un->un_ncmds_in_driver >= 0);
10004 		mutex_exit(SD_MUTEX(un));
10005 	}
10006 
10007 	/*
10008 	 * Write requests are restricted to multiples of the system block size.
10009 	 */
10010 	secmask = un->un_sys_blocksize - 1;
10011 
10012 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10013 		SD_ERROR(SD_LOG_READ_WRITE, un,
10014 		    "sdawrite: file offset not modulo %d\n",
10015 		    un->un_sys_blocksize);
10016 		err = EINVAL;
10017 	} else if (uio->uio_iov->iov_len & (secmask)) {
10018 		SD_ERROR(SD_LOG_READ_WRITE, un,
10019 		    "sdawrite: transfer length not modulo %d\n",
10020 		    un->un_sys_blocksize);
10021 		err = EINVAL;
10022 	} else {
10023 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
10024 	}
10025 	return (err);
10026 }
10027 
10028 
10029 
10030 
10031 
10032 /*
10033  * Driver IO processing follows the following sequence:
10034  *
10035  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
10036  *         |                |                     ^
10037  *         v                v                     |
10038  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
10039  *         |                |                     |                   |
10040  *         v                |                     |                   |
10041  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
10042  *         |                |                     ^                   ^
10043  *         v                v                     |                   |
10044  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
10045  *         |                |                     |                   |
10046  *     +---+                |                     +------------+      +-------+
10047  *     |                    |                                  |              |
10048  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10049  *     |                    v                                  |              |
10050  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
10051  *     |                    |                                  ^              |
10052  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10053  *     |                    v                                  |              |
10054  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
10055  *     |                    |                                  ^              |
10056  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10057  *     |                    v                                  |              |
10058  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
10059  *     |                    |                                  ^              |
10060  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
10061  *     |                    v                                  |              |
10062  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
10063  *     |                    |                                  ^              |
10064  *     |                    |                                  |              |
10065  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
10066  *                          |                           ^
10067  *                          v                           |
10068  *                   sd_core_iostart()                  |
10069  *                          |                           |
10070  *                          |                           +------>(*destroypkt)()
10071  *                          +-> sd_start_cmds() <-+     |           |
10072  *                          |                     |     |           v
10073  *                          |                     |     |  scsi_destroy_pkt(9F)
10074  *                          |                     |     |
10075  *                          +->(*initpkt)()       +- sdintr()
10076  *                          |  |                        |  |
10077  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
10078  *                          |  +-> scsi_setup_cdb(9F)   |
10079  *                          |                           |
10080  *                          +--> scsi_transport(9F)     |
10081  *                                     |                |
10082  *                                     +----> SCSA ---->+
10083  *
10084  *
10085  * This code is based upon the following presumptions:
10086  *
10087  *   - iostart and iodone functions operate on buf(9S) structures. These
10088  *     functions perform the necessary operations on the buf(9S) and pass
10089  *     them along to the next function in the chain by using the macros
10090  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
10091  *     (for iodone side functions).
10092  *
10093  *   - The iostart side functions may sleep. The iodone side functions
10094  *     are called under interrupt context and may NOT sleep. Therefore
10095  *     iodone side functions also may not call iostart side functions.
10096  *     (NOTE: iostart side functions should NOT sleep for memory, as
10097  *     this could result in deadlock.)
10098  *
10099  *   - An iostart side function may call its corresponding iodone side
10100  *     function directly (if necessary).
10101  *
10102  *   - In the event of an error, an iostart side function can return a buf(9S)
10103  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
10104  *     b_error in the usual way of course).
10105  *
10106  *   - The taskq mechanism may be used by the iodone side functions to dispatch
10107  *     requests to the iostart side functions.  The iostart side functions in
10108  *     this case would be called under the context of a taskq thread, so it's
10109  *     OK for them to block/sleep/spin in this case.
10110  *
10111  *   - iostart side functions may allocate "shadow" buf(9S) structs and
10112  *     pass them along to the next function in the chain.  The corresponding
10113  *     iodone side functions must coalesce the "shadow" bufs and return
10114  *     the "original" buf to the next higher layer.
10115  *
10116  *   - The b_private field of the buf(9S) struct holds a pointer to
10117  *     an sd_xbuf struct, which contains information needed to
10118  *     construct the scsi_pkt for the command.
10119  *
10120  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
10121  *     layer must acquire & release the SD_MUTEX(un) as needed.
10122  */
10123 
10124 
10125 /*
10126  * Create taskq for all targets in the system. This is created at
10127  * _init(9E) and destroyed at _fini(9E).
10128  *
10129  * Note: here we set the minalloc to a reasonably high number to ensure that
10130  * we will have an adequate supply of task entries available at interrupt time.
10131  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
10132  * sd_create_taskq().  Since we do not want to sleep for allocations at
10133  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
10134  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
10135  * requests any one instant in time.
10136  */
10137 #define	SD_TASKQ_NUMTHREADS	8
10138 #define	SD_TASKQ_MINALLOC	256
10139 #define	SD_TASKQ_MAXALLOC	256
10140 
10141 static taskq_t	*sd_tq = NULL;
10142 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
10143 
10144 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
10145 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
10146 
10147 /*
10148  * The following task queue is being created for the write part of
10149  * read-modify-write of non-512 block size devices.
10150  * Limit the number of threads to 1 for now. This number has been chosen
10151  * considering the fact that it applies only to dvd ram drives/MO drives
10152  * currently. Performance for which is not main criteria at this stage.
10153  * Note: It needs to be explored if we can use a single taskq in future
10154  */
10155 #define	SD_WMR_TASKQ_NUMTHREADS	1
10156 static taskq_t	*sd_wmr_tq = NULL;
10157 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
10158 
10159 /*
10160  *    Function: sd_taskq_create
10161  *
10162  * Description: Create taskq thread(s) and preallocate task entries
10163  *
10164  * Return Code: Returns a pointer to the allocated taskq_t.
10165  *
10166  *     Context: Can sleep. Requires blockable context.
10167  *
10168  *       Notes: - The taskq() facility currently is NOT part of the DDI.
10169  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
10170  *		- taskq_create() will block for memory, also it will panic
10171  *		  if it cannot create the requested number of threads.
10172  *		- Currently taskq_create() creates threads that cannot be
10173  *		  swapped.
10174  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
10175  *		  supply of taskq entries at interrupt time (ie, so that we
10176  *		  do not have to sleep for memory)
10177  */
10178 
10179 static void
10180 sd_taskq_create(void)
10181 {
10182 	char	taskq_name[TASKQ_NAMELEN];
10183 
10184 	ASSERT(sd_tq == NULL);
10185 	ASSERT(sd_wmr_tq == NULL);
10186 
10187 	(void) snprintf(taskq_name, sizeof (taskq_name),
10188 	    "%s_drv_taskq", sd_label);
10189 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
10190 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10191 	    TASKQ_PREPOPULATE));
10192 
10193 	(void) snprintf(taskq_name, sizeof (taskq_name),
10194 	    "%s_rmw_taskq", sd_label);
10195 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
10196 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10197 	    TASKQ_PREPOPULATE));
10198 }
10199 
10200 
10201 /*
10202  *    Function: sd_taskq_delete
10203  *
10204  * Description: Complementary cleanup routine for sd_taskq_create().
10205  *
10206  *     Context: Kernel thread context.
10207  */
10208 
10209 static void
10210 sd_taskq_delete(void)
10211 {
10212 	ASSERT(sd_tq != NULL);
10213 	ASSERT(sd_wmr_tq != NULL);
10214 	taskq_destroy(sd_tq);
10215 	taskq_destroy(sd_wmr_tq);
10216 	sd_tq = NULL;
10217 	sd_wmr_tq = NULL;
10218 }
10219 
10220 
10221 /*
10222  *    Function: sdstrategy
10223  *
10224  * Description: Driver's strategy (9E) entry point function.
10225  *
10226  *   Arguments: bp - pointer to buf(9S)
10227  *
10228  * Return Code: Always returns zero
10229  *
10230  *     Context: Kernel thread context.
10231  */
10232 
10233 static int
10234 sdstrategy(struct buf *bp)
10235 {
10236 	struct sd_lun *un;
10237 
10238 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
10239 	if (un == NULL) {
10240 		bioerror(bp, EIO);
10241 		bp->b_resid = bp->b_bcount;
10242 		biodone(bp);
10243 		return (0);
10244 	}
10245 	/* As was done in the past, fail new cmds. if state is dumping. */
10246 	if (un->un_state == SD_STATE_DUMPING) {
10247 		bioerror(bp, ENXIO);
10248 		bp->b_resid = bp->b_bcount;
10249 		biodone(bp);
10250 		return (0);
10251 	}
10252 
10253 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10254 
10255 	/*
10256 	 * Commands may sneak in while we released the mutex in
10257 	 * DDI_SUSPEND, we should block new commands. However, old
10258 	 * commands that are still in the driver at this point should
10259 	 * still be allowed to drain.
10260 	 */
10261 	mutex_enter(SD_MUTEX(un));
10262 	/*
10263 	 * Must wait here if either the device is suspended or
10264 	 * if it's power level is changing.
10265 	 */
10266 	while ((un->un_state == SD_STATE_SUSPENDED) ||
10267 	    (un->un_state == SD_STATE_PM_CHANGING)) {
10268 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10269 	}
10270 
10271 	un->un_ncmds_in_driver++;
10272 
10273 	/*
10274 	 * atapi: Since we are running the CD for now in PIO mode we need to
10275 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
10276 	 * the HBA's init_pkt routine.
10277 	 */
10278 	if (un->un_f_cfg_is_atapi == TRUE) {
10279 		mutex_exit(SD_MUTEX(un));
10280 		bp_mapin(bp);
10281 		mutex_enter(SD_MUTEX(un));
10282 	}
10283 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
10284 	    un->un_ncmds_in_driver);
10285 
10286 	mutex_exit(SD_MUTEX(un));
10287 
10288 	/*
10289 	 * This will (eventually) allocate the sd_xbuf area and
10290 	 * call sd_xbuf_strategy().  We just want to return the
10291 	 * result of ddi_xbuf_qstrategy so that we have an opt-
10292 	 * imized tail call which saves us a stack frame.
10293 	 */
10294 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
10295 }
10296 
10297 
10298 /*
10299  *    Function: sd_xbuf_strategy
10300  *
10301  * Description: Function for initiating IO operations via the
10302  *		ddi_xbuf_qstrategy() mechanism.
10303  *
10304  *     Context: Kernel thread context.
10305  */
10306 
10307 static void
10308 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
10309 {
10310 	struct sd_lun *un = arg;
10311 
10312 	ASSERT(bp != NULL);
10313 	ASSERT(xp != NULL);
10314 	ASSERT(un != NULL);
10315 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10316 
10317 	/*
10318 	 * Initialize the fields in the xbuf and save a pointer to the
10319 	 * xbuf in bp->b_private.
10320 	 */
10321 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
10322 
10323 	/* Send the buf down the iostart chain */
10324 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
10325 }
10326 
10327 
10328 /*
10329  *    Function: sd_xbuf_init
10330  *
10331  * Description: Prepare the given sd_xbuf struct for use.
10332  *
10333  *   Arguments: un - ptr to softstate
10334  *		bp - ptr to associated buf(9S)
10335  *		xp - ptr to associated sd_xbuf
10336  *		chain_type - IO chain type to use:
10337  *			SD_CHAIN_NULL
10338  *			SD_CHAIN_BUFIO
10339  *			SD_CHAIN_USCSI
10340  *			SD_CHAIN_DIRECT
10341  *			SD_CHAIN_DIRECT_PRIORITY
10342  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
10343  *			initialization; may be NULL if none.
10344  *
10345  *     Context: Kernel thread context
10346  */
10347 
10348 static void
10349 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
10350 	uchar_t chain_type, void *pktinfop)
10351 {
10352 	int index;
10353 
10354 	ASSERT(un != NULL);
10355 	ASSERT(bp != NULL);
10356 	ASSERT(xp != NULL);
10357 
10358 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
10359 	    bp, chain_type);
10360 
10361 	xp->xb_un	= un;
10362 	xp->xb_pktp	= NULL;
10363 	xp->xb_pktinfo	= pktinfop;
10364 	xp->xb_private	= bp->b_private;
10365 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
10366 
10367 	/*
10368 	 * Set up the iostart and iodone chain indexes in the xbuf, based
10369 	 * upon the specified chain type to use.
10370 	 */
10371 	switch (chain_type) {
10372 	case SD_CHAIN_NULL:
10373 		/*
10374 		 * Fall thru to just use the values for the buf type, even
10375 		 * tho for the NULL chain these values will never be used.
10376 		 */
10377 		/* FALLTHRU */
10378 	case SD_CHAIN_BUFIO:
10379 		index = un->un_buf_chain_type;
10380 		break;
10381 	case SD_CHAIN_USCSI:
10382 		index = un->un_uscsi_chain_type;
10383 		break;
10384 	case SD_CHAIN_DIRECT:
10385 		index = un->un_direct_chain_type;
10386 		break;
10387 	case SD_CHAIN_DIRECT_PRIORITY:
10388 		index = un->un_priority_chain_type;
10389 		break;
10390 	default:
10391 		/* We're really broken if we ever get here... */
10392 		panic("sd_xbuf_init: illegal chain type!");
10393 		/*NOTREACHED*/
10394 	}
10395 
10396 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
10397 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
10398 
10399 	/*
10400 	 * It might be a bit easier to simply bzero the entire xbuf above,
10401 	 * but it turns out that since we init a fair number of members anyway,
10402 	 * we save a fair number cycles by doing explicit assignment of zero.
10403 	 */
10404 	xp->xb_pkt_flags	= 0;
10405 	xp->xb_dma_resid	= 0;
10406 	xp->xb_retry_count	= 0;
10407 	xp->xb_victim_retry_count = 0;
10408 	xp->xb_ua_retry_count	= 0;
10409 	xp->xb_nr_retry_count	= 0;
10410 	xp->xb_sense_bp		= NULL;
10411 	xp->xb_sense_status	= 0;
10412 	xp->xb_sense_state	= 0;
10413 	xp->xb_sense_resid	= 0;
10414 
10415 	bp->b_private	= xp;
10416 	bp->b_flags	&= ~(B_DONE | B_ERROR);
10417 	bp->b_resid	= 0;
10418 	bp->av_forw	= NULL;
10419 	bp->av_back	= NULL;
10420 	bioerror(bp, 0);
10421 
10422 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
10423 }
10424 
10425 
10426 /*
10427  *    Function: sd_uscsi_strategy
10428  *
10429  * Description: Wrapper for calling into the USCSI chain via physio(9F)
10430  *
10431  *   Arguments: bp - buf struct ptr
10432  *
10433  * Return Code: Always returns 0
10434  *
10435  *     Context: Kernel thread context
10436  */
10437 
10438 static int
10439 sd_uscsi_strategy(struct buf *bp)
10440 {
10441 	struct sd_lun		*un;
10442 	struct sd_uscsi_info	*uip;
10443 	struct sd_xbuf		*xp;
10444 	uchar_t			chain_type;
10445 
10446 	ASSERT(bp != NULL);
10447 
10448 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
10449 	if (un == NULL) {
10450 		bioerror(bp, EIO);
10451 		bp->b_resid = bp->b_bcount;
10452 		biodone(bp);
10453 		return (0);
10454 	}
10455 
10456 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10457 
10458 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
10459 
10460 	mutex_enter(SD_MUTEX(un));
10461 	/*
10462 	 * atapi: Since we are running the CD for now in PIO mode we need to
10463 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
10464 	 * the HBA's init_pkt routine.
10465 	 */
10466 	if (un->un_f_cfg_is_atapi == TRUE) {
10467 		mutex_exit(SD_MUTEX(un));
10468 		bp_mapin(bp);
10469 		mutex_enter(SD_MUTEX(un));
10470 	}
10471 	un->un_ncmds_in_driver++;
10472 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
10473 	    un->un_ncmds_in_driver);
10474 	mutex_exit(SD_MUTEX(un));
10475 
10476 	/*
10477 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
10478 	 */
10479 	ASSERT(bp->b_private != NULL);
10480 	uip = (struct sd_uscsi_info *)bp->b_private;
10481 
10482 	switch (uip->ui_flags) {
10483 	case SD_PATH_DIRECT:
10484 		chain_type = SD_CHAIN_DIRECT;
10485 		break;
10486 	case SD_PATH_DIRECT_PRIORITY:
10487 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
10488 		break;
10489 	default:
10490 		chain_type = SD_CHAIN_USCSI;
10491 		break;
10492 	}
10493 
10494 	/*
10495 	 * We may allocate extra buf for external USCSI commands. If the
10496 	 * application asks for bigger than 20-byte sense data via USCSI,
10497 	 * SCSA layer will allocate 252 bytes sense buf for that command.
10498 	 */
10499 	if (((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_rqlen >
10500 	    SENSE_LENGTH) {
10501 		xp = kmem_zalloc(sizeof (struct sd_xbuf) - SENSE_LENGTH +
10502 		    MAX_SENSE_LENGTH, KM_SLEEP);
10503 	} else {
10504 		xp = kmem_zalloc(sizeof (struct sd_xbuf), KM_SLEEP);
10505 	}
10506 
10507 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
10508 
10509 	/* Use the index obtained within xbuf_init */
10510 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
10511 
10512 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
10513 
10514 	return (0);
10515 }
10516 
10517 /*
10518  *    Function: sd_send_scsi_cmd
10519  *
10520  * Description: Runs a USCSI command for user (when called thru sdioctl),
10521  *		or for the driver
10522  *
10523  *   Arguments: dev - the dev_t for the device
10524  *		incmd - ptr to a valid uscsi_cmd struct
10525  *		flag - bit flag, indicating open settings, 32/64 bit type
10526  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
10527  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
10528  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
10529  *			to use the USCSI "direct" chain and bypass the normal
10530  *			command waitq.
10531  *
10532  * Return Code: 0 -  successful completion of the given command
10533  *		EIO - scsi_uscsi_handle_command() failed
10534  *		ENXIO  - soft state not found for specified dev
10535  *		EINVAL
10536  *		EFAULT - copyin/copyout error
10537  *		return code of scsi_uscsi_handle_command():
10538  *			EIO
10539  *			ENXIO
10540  *			EACCES
10541  *
10542  *     Context: Waits for command to complete. Can sleep.
10543  */
10544 
10545 static int
10546 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
10547 	enum uio_seg dataspace, int path_flag)
10548 {
10549 	struct sd_uscsi_info	*uip;
10550 	struct uscsi_cmd	*uscmd;
10551 	struct sd_lun	*un;
10552 	int	format = 0;
10553 	int	rval;
10554 
10555 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
10556 	if (un == NULL) {
10557 		return (ENXIO);
10558 	}
10559 
10560 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10561 
10562 #ifdef SDDEBUG
10563 	switch (dataspace) {
10564 	case UIO_USERSPACE:
10565 		SD_TRACE(SD_LOG_IO, un,
10566 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_USERSPACE\n", un);
10567 		break;
10568 	case UIO_SYSSPACE:
10569 		SD_TRACE(SD_LOG_IO, un,
10570 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_SYSSPACE\n", un);
10571 		break;
10572 	default:
10573 		SD_TRACE(SD_LOG_IO, un,
10574 		    "sd_send_scsi_cmd: entry: un:0x%p UNEXPECTED SPACE\n", un);
10575 		break;
10576 	}
10577 #endif
10578 
10579 	rval = scsi_uscsi_alloc_and_copyin((intptr_t)incmd, flag,
10580 	    SD_ADDRESS(un), &uscmd);
10581 	if (rval != 0) {
10582 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
10583 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
10584 		return (rval);
10585 	}
10586 
10587 	if ((uscmd->uscsi_cdb != NULL) &&
10588 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
10589 		mutex_enter(SD_MUTEX(un));
10590 		un->un_f_format_in_progress = TRUE;
10591 		mutex_exit(SD_MUTEX(un));
10592 		format = 1;
10593 	}
10594 
10595 	/*
10596 	 * Allocate an sd_uscsi_info struct and fill it with the info
10597 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
10598 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
10599 	 * since we allocate the buf here in this function, we do not
10600 	 * need to preserve the prior contents of b_private.
10601 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
10602 	 */
10603 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
10604 	uip->ui_flags = path_flag;
10605 	uip->ui_cmdp = uscmd;
10606 
10607 	/*
10608 	 * Commands sent with priority are intended for error recovery
10609 	 * situations, and do not have retries performed.
10610 	 */
10611 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
10612 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
10613 	}
10614 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
10615 
10616 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
10617 	    sd_uscsi_strategy, NULL, uip);
10618 
10619 #ifdef SDDEBUG
10620 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10621 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
10622 	    uscmd->uscsi_status, uscmd->uscsi_resid);
10623 	if (uscmd->uscsi_bufaddr != NULL) {
10624 		SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10625 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
10626 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
10627 		if (dataspace == UIO_SYSSPACE) {
10628 			SD_DUMP_MEMORY(un, SD_LOG_IO,
10629 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
10630 			    uscmd->uscsi_buflen, SD_LOG_HEX);
10631 		}
10632 	}
10633 #endif
10634 
10635 	if (format == 1) {
10636 		mutex_enter(SD_MUTEX(un));
10637 		un->un_f_format_in_progress = FALSE;
10638 		mutex_exit(SD_MUTEX(un));
10639 	}
10640 
10641 	(void) scsi_uscsi_copyout_and_free((intptr_t)incmd, uscmd);
10642 	kmem_free(uip, sizeof (struct sd_uscsi_info));
10643 
10644 	return (rval);
10645 }
10646 
10647 
10648 /*
10649  *    Function: sd_buf_iodone
10650  *
10651  * Description: Frees the sd_xbuf & returns the buf to its originator.
10652  *
10653  *     Context: May be called from interrupt context.
10654  */
10655 /* ARGSUSED */
10656 static void
10657 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
10658 {
10659 	struct sd_xbuf *xp;
10660 
10661 	ASSERT(un != NULL);
10662 	ASSERT(bp != NULL);
10663 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10664 
10665 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
10666 
10667 	xp = SD_GET_XBUF(bp);
10668 	ASSERT(xp != NULL);
10669 
10670 	mutex_enter(SD_MUTEX(un));
10671 
10672 	/*
10673 	 * Grab time when the cmd completed.
10674 	 * This is used for determining if the system has been
10675 	 * idle long enough to make it idle to the PM framework.
10676 	 * This is for lowering the overhead, and therefore improving
10677 	 * performance per I/O operation.
10678 	 */
10679 	un->un_pm_idle_time = ddi_get_time();
10680 
10681 	un->un_ncmds_in_driver--;
10682 	ASSERT(un->un_ncmds_in_driver >= 0);
10683 	SD_INFO(SD_LOG_IO, un, "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
10684 	    un->un_ncmds_in_driver);
10685 
10686 	mutex_exit(SD_MUTEX(un));
10687 
10688 	ddi_xbuf_done(bp, un->un_xbuf_attr);	/* xbuf is gone after this */
10689 	biodone(bp);				/* bp is gone after this */
10690 
10691 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
10692 }
10693 
10694 
10695 /*
10696  *    Function: sd_uscsi_iodone
10697  *
10698  * Description: Frees the sd_xbuf & returns the buf to its originator.
10699  *
10700  *     Context: May be called from interrupt context.
10701  */
10702 /* ARGSUSED */
10703 static void
10704 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
10705 {
10706 	struct sd_xbuf *xp;
10707 
10708 	ASSERT(un != NULL);
10709 	ASSERT(bp != NULL);
10710 
10711 	xp = SD_GET_XBUF(bp);
10712 	ASSERT(xp != NULL);
10713 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10714 
10715 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
10716 
10717 	bp->b_private = xp->xb_private;
10718 
10719 	mutex_enter(SD_MUTEX(un));
10720 
10721 	/*
10722 	 * Grab time when the cmd completed.
10723 	 * This is used for determining if the system has been
10724 	 * idle long enough to make it idle to the PM framework.
10725 	 * This is for lowering the overhead, and therefore improving
10726 	 * performance per I/O operation.
10727 	 */
10728 	un->un_pm_idle_time = ddi_get_time();
10729 
10730 	un->un_ncmds_in_driver--;
10731 	ASSERT(un->un_ncmds_in_driver >= 0);
10732 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
10733 	    un->un_ncmds_in_driver);
10734 
10735 	mutex_exit(SD_MUTEX(un));
10736 
10737 	if (((struct uscsi_cmd *)(xp->xb_pktinfo))->uscsi_rqlen >
10738 	    SENSE_LENGTH) {
10739 		kmem_free(xp, sizeof (struct sd_xbuf) - SENSE_LENGTH +
10740 		    MAX_SENSE_LENGTH);
10741 	} else {
10742 		kmem_free(xp, sizeof (struct sd_xbuf));
10743 	}
10744 
10745 	biodone(bp);
10746 
10747 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
10748 }
10749 
10750 
10751 /*
10752  *    Function: sd_mapblockaddr_iostart
10753  *
10754  * Description: Verify request lies within the partition limits for
10755  *		the indicated minor device.  Issue "overrun" buf if
10756  *		request would exceed partition range.  Converts
10757  *		partition-relative block address to absolute.
10758  *
10759  *     Context: Can sleep
10760  *
10761  *      Issues: This follows what the old code did, in terms of accessing
10762  *		some of the partition info in the unit struct without holding
10763  *		the mutext.  This is a general issue, if the partition info
10764  *		can be altered while IO is in progress... as soon as we send
10765  *		a buf, its partitioning can be invalid before it gets to the
10766  *		device.  Probably the right fix is to move partitioning out
10767  *		of the driver entirely.
10768  */
10769 
10770 static void
10771 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
10772 {
10773 	diskaddr_t	nblocks;	/* #blocks in the given partition */
10774 	daddr_t	blocknum;	/* Block number specified by the buf */
10775 	size_t	requested_nblocks;
10776 	size_t	available_nblocks;
10777 	int	partition;
10778 	diskaddr_t	partition_offset;
10779 	struct sd_xbuf *xp;
10780 
10781 
10782 	ASSERT(un != NULL);
10783 	ASSERT(bp != NULL);
10784 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10785 
10786 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10787 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
10788 
10789 	xp = SD_GET_XBUF(bp);
10790 	ASSERT(xp != NULL);
10791 
10792 	/*
10793 	 * If the geometry is not indicated as valid, attempt to access
10794 	 * the unit & verify the geometry/label. This can be the case for
10795 	 * removable-media devices, of if the device was opened in
10796 	 * NDELAY/NONBLOCK mode.
10797 	 */
10798 	if (!SD_IS_VALID_LABEL(un) &&
10799 	    (sd_ready_and_valid(un) != SD_READY_VALID)) {
10800 		/*
10801 		 * For removable devices it is possible to start an I/O
10802 		 * without a media by opening the device in nodelay mode.
10803 		 * Also for writable CDs there can be many scenarios where
10804 		 * there is no geometry yet but volume manager is trying to
10805 		 * issue a read() just because it can see TOC on the CD. So
10806 		 * do not print a message for removables.
10807 		 */
10808 		if (!un->un_f_has_removable_media) {
10809 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10810 			    "i/o to invalid geometry\n");
10811 		}
10812 		bioerror(bp, EIO);
10813 		bp->b_resid = bp->b_bcount;
10814 		SD_BEGIN_IODONE(index, un, bp);
10815 		return;
10816 	}
10817 
10818 	partition = SDPART(bp->b_edev);
10819 
10820 	nblocks = 0;
10821 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
10822 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
10823 
10824 	/*
10825 	 * blocknum is the starting block number of the request. At this
10826 	 * point it is still relative to the start of the minor device.
10827 	 */
10828 	blocknum = xp->xb_blkno;
10829 
10830 	/*
10831 	 * Legacy: If the starting block number is one past the last block
10832 	 * in the partition, do not set B_ERROR in the buf.
10833 	 */
10834 	if (blocknum == nblocks)  {
10835 		goto error_exit;
10836 	}
10837 
10838 	/*
10839 	 * Confirm that the first block of the request lies within the
10840 	 * partition limits. Also the requested number of bytes must be
10841 	 * a multiple of the system block size.
10842 	 */
10843 	if ((blocknum < 0) || (blocknum >= nblocks) ||
10844 	    ((bp->b_bcount & (un->un_sys_blocksize - 1)) != 0)) {
10845 		bp->b_flags |= B_ERROR;
10846 		goto error_exit;
10847 	}
10848 
10849 	/*
10850 	 * If the requsted # blocks exceeds the available # blocks, that
10851 	 * is an overrun of the partition.
10852 	 */
10853 	requested_nblocks = SD_BYTES2SYSBLOCKS(un, bp->b_bcount);
10854 	available_nblocks = (size_t)(nblocks - blocknum);
10855 	ASSERT(nblocks >= blocknum);
10856 
10857 	if (requested_nblocks > available_nblocks) {
10858 		/*
10859 		 * Allocate an "overrun" buf to allow the request to proceed
10860 		 * for the amount of space available in the partition. The
10861 		 * amount not transferred will be added into the b_resid
10862 		 * when the operation is complete. The overrun buf
10863 		 * replaces the original buf here, and the original buf
10864 		 * is saved inside the overrun buf, for later use.
10865 		 */
10866 		size_t resid = SD_SYSBLOCKS2BYTES(un,
10867 		    (offset_t)(requested_nblocks - available_nblocks));
10868 		size_t count = bp->b_bcount - resid;
10869 		/*
10870 		 * Note: count is an unsigned entity thus it'll NEVER
10871 		 * be less than 0 so ASSERT the original values are
10872 		 * correct.
10873 		 */
10874 		ASSERT(bp->b_bcount >= resid);
10875 
10876 		bp = sd_bioclone_alloc(bp, count, blocknum,
10877 		    (int (*)(struct buf *)) sd_mapblockaddr_iodone);
10878 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
10879 		ASSERT(xp != NULL);
10880 	}
10881 
10882 	/* At this point there should be no residual for this buf. */
10883 	ASSERT(bp->b_resid == 0);
10884 
10885 	/* Convert the block number to an absolute address. */
10886 	xp->xb_blkno += partition_offset;
10887 
10888 	SD_NEXT_IOSTART(index, un, bp);
10889 
10890 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10891 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
10892 
10893 	return;
10894 
10895 error_exit:
10896 	bp->b_resid = bp->b_bcount;
10897 	SD_BEGIN_IODONE(index, un, bp);
10898 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10899 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
10900 }
10901 
10902 
10903 /*
10904  *    Function: sd_mapblockaddr_iodone
10905  *
10906  * Description: Completion-side processing for partition management.
10907  *
10908  *     Context: May be called under interrupt context
10909  */
10910 
10911 static void
10912 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
10913 {
10914 	/* int	partition; */	/* Not used, see below. */
10915 	ASSERT(un != NULL);
10916 	ASSERT(bp != NULL);
10917 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10918 
10919 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10920 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
10921 
10922 	if (bp->b_iodone == (int (*)(struct buf *)) sd_mapblockaddr_iodone) {
10923 		/*
10924 		 * We have an "overrun" buf to deal with...
10925 		 */
10926 		struct sd_xbuf	*xp;
10927 		struct buf	*obp;	/* ptr to the original buf */
10928 
10929 		xp = SD_GET_XBUF(bp);
10930 		ASSERT(xp != NULL);
10931 
10932 		/* Retrieve the pointer to the original buf */
10933 		obp = (struct buf *)xp->xb_private;
10934 		ASSERT(obp != NULL);
10935 
10936 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
10937 		bioerror(obp, bp->b_error);
10938 
10939 		sd_bioclone_free(bp);
10940 
10941 		/*
10942 		 * Get back the original buf.
10943 		 * Note that since the restoration of xb_blkno below
10944 		 * was removed, the sd_xbuf is not needed.
10945 		 */
10946 		bp = obp;
10947 		/*
10948 		 * xp = SD_GET_XBUF(bp);
10949 		 * ASSERT(xp != NULL);
10950 		 */
10951 	}
10952 
10953 	/*
10954 	 * Convert sd->xb_blkno back to a minor-device relative value.
10955 	 * Note: this has been commented out, as it is not needed in the
10956 	 * current implementation of the driver (ie, since this function
10957 	 * is at the top of the layering chains, so the info will be
10958 	 * discarded) and it is in the "hot" IO path.
10959 	 *
10960 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
10961 	 * xp->xb_blkno -= un->un_offset[partition];
10962 	 */
10963 
10964 	SD_NEXT_IODONE(index, un, bp);
10965 
10966 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10967 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
10968 }
10969 
10970 
10971 /*
10972  *    Function: sd_mapblocksize_iostart
10973  *
10974  * Description: Convert between system block size (un->un_sys_blocksize)
10975  *		and target block size (un->un_tgt_blocksize).
10976  *
10977  *     Context: Can sleep to allocate resources.
10978  *
10979  * Assumptions: A higher layer has already performed any partition validation,
10980  *		and converted the xp->xb_blkno to an absolute value relative
10981  *		to the start of the device.
10982  *
10983  *		It is also assumed that the higher layer has implemented
10984  *		an "overrun" mechanism for the case where the request would
10985  *		read/write beyond the end of a partition.  In this case we
10986  *		assume (and ASSERT) that bp->b_resid == 0.
10987  *
10988  *		Note: The implementation for this routine assumes the target
10989  *		block size remains constant between allocation and transport.
10990  */
10991 
10992 static void
10993 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
10994 {
10995 	struct sd_mapblocksize_info	*bsp;
10996 	struct sd_xbuf			*xp;
10997 	offset_t first_byte;
10998 	daddr_t	start_block, end_block;
10999 	daddr_t	request_bytes;
11000 	ushort_t is_aligned = FALSE;
11001 
11002 	ASSERT(un != NULL);
11003 	ASSERT(bp != NULL);
11004 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11005 	ASSERT(bp->b_resid == 0);
11006 
11007 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11008 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
11009 
11010 	/*
11011 	 * For a non-writable CD, a write request is an error
11012 	 */
11013 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
11014 	    (un->un_f_mmc_writable_media == FALSE)) {
11015 		bioerror(bp, EIO);
11016 		bp->b_resid = bp->b_bcount;
11017 		SD_BEGIN_IODONE(index, un, bp);
11018 		return;
11019 	}
11020 
11021 	/*
11022 	 * We do not need a shadow buf if the device is using
11023 	 * un->un_sys_blocksize as its block size or if bcount == 0.
11024 	 * In this case there is no layer-private data block allocated.
11025 	 */
11026 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
11027 	    (bp->b_bcount == 0)) {
11028 		goto done;
11029 	}
11030 
11031 #if defined(__i386) || defined(__amd64)
11032 	/* We do not support non-block-aligned transfers for ROD devices */
11033 	ASSERT(!ISROD(un));
11034 #endif
11035 
11036 	xp = SD_GET_XBUF(bp);
11037 	ASSERT(xp != NULL);
11038 
11039 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11040 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
11041 	    un->un_tgt_blocksize, un->un_sys_blocksize);
11042 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11043 	    "request start block:0x%x\n", xp->xb_blkno);
11044 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11045 	    "request len:0x%x\n", bp->b_bcount);
11046 
11047 	/*
11048 	 * Allocate the layer-private data area for the mapblocksize layer.
11049 	 * Layers are allowed to use the xp_private member of the sd_xbuf
11050 	 * struct to store the pointer to their layer-private data block, but
11051 	 * each layer also has the responsibility of restoring the prior
11052 	 * contents of xb_private before returning the buf/xbuf to the
11053 	 * higher layer that sent it.
11054 	 *
11055 	 * Here we save the prior contents of xp->xb_private into the
11056 	 * bsp->mbs_oprivate field of our layer-private data area. This value
11057 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
11058 	 * the layer-private area and returning the buf/xbuf to the layer
11059 	 * that sent it.
11060 	 *
11061 	 * Note that here we use kmem_zalloc for the allocation as there are
11062 	 * parts of the mapblocksize code that expect certain fields to be
11063 	 * zero unless explicitly set to a required value.
11064 	 */
11065 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
11066 	bsp->mbs_oprivate = xp->xb_private;
11067 	xp->xb_private = bsp;
11068 
11069 	/*
11070 	 * This treats the data on the disk (target) as an array of bytes.
11071 	 * first_byte is the byte offset, from the beginning of the device,
11072 	 * to the location of the request. This is converted from a
11073 	 * un->un_sys_blocksize block address to a byte offset, and then back
11074 	 * to a block address based upon a un->un_tgt_blocksize block size.
11075 	 *
11076 	 * xp->xb_blkno should be absolute upon entry into this function,
11077 	 * but, but it is based upon partitions that use the "system"
11078 	 * block size. It must be adjusted to reflect the block size of
11079 	 * the target.
11080 	 *
11081 	 * Note that end_block is actually the block that follows the last
11082 	 * block of the request, but that's what is needed for the computation.
11083 	 */
11084 	first_byte  = SD_SYSBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
11085 	start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
11086 	end_block   = (first_byte + bp->b_bcount + un->un_tgt_blocksize - 1) /
11087 	    un->un_tgt_blocksize;
11088 
11089 	/* request_bytes is rounded up to a multiple of the target block size */
11090 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
11091 
11092 	/*
11093 	 * See if the starting address of the request and the request
11094 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
11095 	 * then we do not need to allocate a shadow buf to handle the request.
11096 	 */
11097 	if (((first_byte   % un->un_tgt_blocksize) == 0) &&
11098 	    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
11099 		is_aligned = TRUE;
11100 	}
11101 
11102 	if ((bp->b_flags & B_READ) == 0) {
11103 		/*
11104 		 * Lock the range for a write operation. An aligned request is
11105 		 * considered a simple write; otherwise the request must be a
11106 		 * read-modify-write.
11107 		 */
11108 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
11109 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
11110 	}
11111 
11112 	/*
11113 	 * Alloc a shadow buf if the request is not aligned. Also, this is
11114 	 * where the READ command is generated for a read-modify-write. (The
11115 	 * write phase is deferred until after the read completes.)
11116 	 */
11117 	if (is_aligned == FALSE) {
11118 
11119 		struct sd_mapblocksize_info	*shadow_bsp;
11120 		struct sd_xbuf	*shadow_xp;
11121 		struct buf	*shadow_bp;
11122 
11123 		/*
11124 		 * Allocate the shadow buf and it associated xbuf. Note that
11125 		 * after this call the xb_blkno value in both the original
11126 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
11127 		 * same: absolute relative to the start of the device, and
11128 		 * adjusted for the target block size. The b_blkno in the
11129 		 * shadow buf will also be set to this value. We should never
11130 		 * change b_blkno in the original bp however.
11131 		 *
11132 		 * Note also that the shadow buf will always need to be a
11133 		 * READ command, regardless of whether the incoming command
11134 		 * is a READ or a WRITE.
11135 		 */
11136 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
11137 		    xp->xb_blkno,
11138 		    (int (*)(struct buf *)) sd_mapblocksize_iodone);
11139 
11140 		shadow_xp = SD_GET_XBUF(shadow_bp);
11141 
11142 		/*
11143 		 * Allocate the layer-private data for the shadow buf.
11144 		 * (No need to preserve xb_private in the shadow xbuf.)
11145 		 */
11146 		shadow_xp->xb_private = shadow_bsp =
11147 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
11148 
11149 		/*
11150 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
11151 		 * to figure out where the start of the user data is (based upon
11152 		 * the system block size) in the data returned by the READ
11153 		 * command (which will be based upon the target blocksize). Note
11154 		 * that this is only really used if the request is unaligned.
11155 		 */
11156 		bsp->mbs_copy_offset = (ssize_t)(first_byte -
11157 		    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
11158 		ASSERT((bsp->mbs_copy_offset >= 0) &&
11159 		    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
11160 
11161 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
11162 
11163 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
11164 
11165 		/* Transfer the wmap (if any) to the shadow buf */
11166 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
11167 		bsp->mbs_wmp = NULL;
11168 
11169 		/*
11170 		 * The shadow buf goes on from here in place of the
11171 		 * original buf.
11172 		 */
11173 		shadow_bsp->mbs_orig_bp = bp;
11174 		bp = shadow_bp;
11175 	}
11176 
11177 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11178 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
11179 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11180 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
11181 	    request_bytes);
11182 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11183 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
11184 
11185 done:
11186 	SD_NEXT_IOSTART(index, un, bp);
11187 
11188 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11189 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
11190 }
11191 
11192 
11193 /*
11194  *    Function: sd_mapblocksize_iodone
11195  *
11196  * Description: Completion side processing for block-size mapping.
11197  *
11198  *     Context: May be called under interrupt context
11199  */
11200 
11201 static void
11202 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
11203 {
11204 	struct sd_mapblocksize_info	*bsp;
11205 	struct sd_xbuf	*xp;
11206 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
11207 	struct buf	*orig_bp;	/* ptr to the original buf */
11208 	offset_t	shadow_end;
11209 	offset_t	request_end;
11210 	offset_t	shadow_start;
11211 	ssize_t		copy_offset;
11212 	size_t		copy_length;
11213 	size_t		shortfall;
11214 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
11215 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
11216 
11217 	ASSERT(un != NULL);
11218 	ASSERT(bp != NULL);
11219 
11220 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11221 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
11222 
11223 	/*
11224 	 * There is no shadow buf or layer-private data if the target is
11225 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
11226 	 */
11227 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
11228 	    (bp->b_bcount == 0)) {
11229 		goto exit;
11230 	}
11231 
11232 	xp = SD_GET_XBUF(bp);
11233 	ASSERT(xp != NULL);
11234 
11235 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
11236 	bsp = xp->xb_private;
11237 
11238 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
11239 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
11240 
11241 	if (is_write) {
11242 		/*
11243 		 * For a WRITE request we must free up the block range that
11244 		 * we have locked up.  This holds regardless of whether this is
11245 		 * an aligned write request or a read-modify-write request.
11246 		 */
11247 		sd_range_unlock(un, bsp->mbs_wmp);
11248 		bsp->mbs_wmp = NULL;
11249 	}
11250 
11251 	if ((bp->b_iodone != (int(*)(struct buf *))sd_mapblocksize_iodone)) {
11252 		/*
11253 		 * An aligned read or write command will have no shadow buf;
11254 		 * there is not much else to do with it.
11255 		 */
11256 		goto done;
11257 	}
11258 
11259 	orig_bp = bsp->mbs_orig_bp;
11260 	ASSERT(orig_bp != NULL);
11261 	orig_xp = SD_GET_XBUF(orig_bp);
11262 	ASSERT(orig_xp != NULL);
11263 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11264 
11265 	if (!is_write && has_wmap) {
11266 		/*
11267 		 * A READ with a wmap means this is the READ phase of a
11268 		 * read-modify-write. If an error occurred on the READ then
11269 		 * we do not proceed with the WRITE phase or copy any data.
11270 		 * Just release the write maps and return with an error.
11271 		 */
11272 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
11273 			orig_bp->b_resid = orig_bp->b_bcount;
11274 			bioerror(orig_bp, bp->b_error);
11275 			sd_range_unlock(un, bsp->mbs_wmp);
11276 			goto freebuf_done;
11277 		}
11278 	}
11279 
11280 	/*
11281 	 * Here is where we set up to copy the data from the shadow buf
11282 	 * into the space associated with the original buf.
11283 	 *
11284 	 * To deal with the conversion between block sizes, these
11285 	 * computations treat the data as an array of bytes, with the
11286 	 * first byte (byte 0) corresponding to the first byte in the
11287 	 * first block on the disk.
11288 	 */
11289 
11290 	/*
11291 	 * shadow_start and shadow_len indicate the location and size of
11292 	 * the data returned with the shadow IO request.
11293 	 */
11294 	shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
11295 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
11296 
11297 	/*
11298 	 * copy_offset gives the offset (in bytes) from the start of the first
11299 	 * block of the READ request to the beginning of the data.  We retrieve
11300 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
11301 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
11302 	 * data to be copied (in bytes).
11303 	 */
11304 	copy_offset  = bsp->mbs_copy_offset;
11305 	ASSERT((copy_offset >= 0) && (copy_offset < un->un_tgt_blocksize));
11306 	copy_length  = orig_bp->b_bcount;
11307 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
11308 
11309 	/*
11310 	 * Set up the resid and error fields of orig_bp as appropriate.
11311 	 */
11312 	if (shadow_end >= request_end) {
11313 		/* We got all the requested data; set resid to zero */
11314 		orig_bp->b_resid = 0;
11315 	} else {
11316 		/*
11317 		 * We failed to get enough data to fully satisfy the original
11318 		 * request. Just copy back whatever data we got and set
11319 		 * up the residual and error code as required.
11320 		 *
11321 		 * 'shortfall' is the amount by which the data received with the
11322 		 * shadow buf has "fallen short" of the requested amount.
11323 		 */
11324 		shortfall = (size_t)(request_end - shadow_end);
11325 
11326 		if (shortfall > orig_bp->b_bcount) {
11327 			/*
11328 			 * We did not get enough data to even partially
11329 			 * fulfill the original request.  The residual is
11330 			 * equal to the amount requested.
11331 			 */
11332 			orig_bp->b_resid = orig_bp->b_bcount;
11333 		} else {
11334 			/*
11335 			 * We did not get all the data that we requested
11336 			 * from the device, but we will try to return what
11337 			 * portion we did get.
11338 			 */
11339 			orig_bp->b_resid = shortfall;
11340 		}
11341 		ASSERT(copy_length >= orig_bp->b_resid);
11342 		copy_length  -= orig_bp->b_resid;
11343 	}
11344 
11345 	/* Propagate the error code from the shadow buf to the original buf */
11346 	bioerror(orig_bp, bp->b_error);
11347 
11348 	if (is_write) {
11349 		goto freebuf_done;	/* No data copying for a WRITE */
11350 	}
11351 
11352 	if (has_wmap) {
11353 		/*
11354 		 * This is a READ command from the READ phase of a
11355 		 * read-modify-write request. We have to copy the data given
11356 		 * by the user OVER the data returned by the READ command,
11357 		 * then convert the command from a READ to a WRITE and send
11358 		 * it back to the target.
11359 		 */
11360 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
11361 		    copy_length);
11362 
11363 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
11364 
11365 		/*
11366 		 * Dispatch the WRITE command to the taskq thread, which
11367 		 * will in turn send the command to the target. When the
11368 		 * WRITE command completes, we (sd_mapblocksize_iodone())
11369 		 * will get called again as part of the iodone chain
11370 		 * processing for it. Note that we will still be dealing
11371 		 * with the shadow buf at that point.
11372 		 */
11373 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
11374 		    KM_NOSLEEP) != 0) {
11375 			/*
11376 			 * Dispatch was successful so we are done. Return
11377 			 * without going any higher up the iodone chain. Do
11378 			 * not free up any layer-private data until after the
11379 			 * WRITE completes.
11380 			 */
11381 			return;
11382 		}
11383 
11384 		/*
11385 		 * Dispatch of the WRITE command failed; set up the error
11386 		 * condition and send this IO back up the iodone chain.
11387 		 */
11388 		bioerror(orig_bp, EIO);
11389 		orig_bp->b_resid = orig_bp->b_bcount;
11390 
11391 	} else {
11392 		/*
11393 		 * This is a regular READ request (ie, not a RMW). Copy the
11394 		 * data from the shadow buf into the original buf. The
11395 		 * copy_offset compensates for any "misalignment" between the
11396 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
11397 		 * original buf (with its un->un_sys_blocksize blocks).
11398 		 */
11399 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
11400 		    copy_length);
11401 	}
11402 
11403 freebuf_done:
11404 
11405 	/*
11406 	 * At this point we still have both the shadow buf AND the original
11407 	 * buf to deal with, as well as the layer-private data area in each.
11408 	 * Local variables are as follows:
11409 	 *
11410 	 * bp -- points to shadow buf
11411 	 * xp -- points to xbuf of shadow buf
11412 	 * bsp -- points to layer-private data area of shadow buf
11413 	 * orig_bp -- points to original buf
11414 	 *
11415 	 * First free the shadow buf and its associated xbuf, then free the
11416 	 * layer-private data area from the shadow buf. There is no need to
11417 	 * restore xb_private in the shadow xbuf.
11418 	 */
11419 	sd_shadow_buf_free(bp);
11420 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11421 
11422 	/*
11423 	 * Now update the local variables to point to the original buf, xbuf,
11424 	 * and layer-private area.
11425 	 */
11426 	bp = orig_bp;
11427 	xp = SD_GET_XBUF(bp);
11428 	ASSERT(xp != NULL);
11429 	ASSERT(xp == orig_xp);
11430 	bsp = xp->xb_private;
11431 	ASSERT(bsp != NULL);
11432 
11433 done:
11434 	/*
11435 	 * Restore xb_private to whatever it was set to by the next higher
11436 	 * layer in the chain, then free the layer-private data area.
11437 	 */
11438 	xp->xb_private = bsp->mbs_oprivate;
11439 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11440 
11441 exit:
11442 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
11443 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
11444 
11445 	SD_NEXT_IODONE(index, un, bp);
11446 }
11447 
11448 
11449 /*
11450  *    Function: sd_checksum_iostart
11451  *
11452  * Description: A stub function for a layer that's currently not used.
11453  *		For now just a placeholder.
11454  *
11455  *     Context: Kernel thread context
11456  */
11457 
11458 static void
11459 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
11460 {
11461 	ASSERT(un != NULL);
11462 	ASSERT(bp != NULL);
11463 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11464 	SD_NEXT_IOSTART(index, un, bp);
11465 }
11466 
11467 
11468 /*
11469  *    Function: sd_checksum_iodone
11470  *
11471  * Description: A stub function for a layer that's currently not used.
11472  *		For now just a placeholder.
11473  *
11474  *     Context: May be called under interrupt context
11475  */
11476 
11477 static void
11478 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
11479 {
11480 	ASSERT(un != NULL);
11481 	ASSERT(bp != NULL);
11482 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11483 	SD_NEXT_IODONE(index, un, bp);
11484 }
11485 
11486 
11487 /*
11488  *    Function: sd_checksum_uscsi_iostart
11489  *
11490  * Description: A stub function for a layer that's currently not used.
11491  *		For now just a placeholder.
11492  *
11493  *     Context: Kernel thread context
11494  */
11495 
11496 static void
11497 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
11498 {
11499 	ASSERT(un != NULL);
11500 	ASSERT(bp != NULL);
11501 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11502 	SD_NEXT_IOSTART(index, un, bp);
11503 }
11504 
11505 
11506 /*
11507  *    Function: sd_checksum_uscsi_iodone
11508  *
11509  * Description: A stub function for a layer that's currently not used.
11510  *		For now just a placeholder.
11511  *
11512  *     Context: May be called under interrupt context
11513  */
11514 
11515 static void
11516 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
11517 {
11518 	ASSERT(un != NULL);
11519 	ASSERT(bp != NULL);
11520 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11521 	SD_NEXT_IODONE(index, un, bp);
11522 }
11523 
11524 
11525 /*
11526  *    Function: sd_pm_iostart
11527  *
11528  * Description: iostart-side routine for Power mangement.
11529  *
11530  *     Context: Kernel thread context
11531  */
11532 
11533 static void
11534 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
11535 {
11536 	ASSERT(un != NULL);
11537 	ASSERT(bp != NULL);
11538 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11539 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11540 
11541 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
11542 
11543 	if (sd_pm_entry(un) != DDI_SUCCESS) {
11544 		/*
11545 		 * Set up to return the failed buf back up the 'iodone'
11546 		 * side of the calling chain.
11547 		 */
11548 		bioerror(bp, EIO);
11549 		bp->b_resid = bp->b_bcount;
11550 
11551 		SD_BEGIN_IODONE(index, un, bp);
11552 
11553 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11554 		return;
11555 	}
11556 
11557 	SD_NEXT_IOSTART(index, un, bp);
11558 
11559 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11560 }
11561 
11562 
11563 /*
11564  *    Function: sd_pm_iodone
11565  *
11566  * Description: iodone-side routine for power mangement.
11567  *
11568  *     Context: may be called from interrupt context
11569  */
11570 
11571 static void
11572 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
11573 {
11574 	ASSERT(un != NULL);
11575 	ASSERT(bp != NULL);
11576 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11577 
11578 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
11579 
11580 	/*
11581 	 * After attach the following flag is only read, so don't
11582 	 * take the penalty of acquiring a mutex for it.
11583 	 */
11584 	if (un->un_f_pm_is_enabled == TRUE) {
11585 		sd_pm_exit(un);
11586 	}
11587 
11588 	SD_NEXT_IODONE(index, un, bp);
11589 
11590 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
11591 }
11592 
11593 
11594 /*
11595  *    Function: sd_core_iostart
11596  *
11597  * Description: Primary driver function for enqueuing buf(9S) structs from
11598  *		the system and initiating IO to the target device
11599  *
11600  *     Context: Kernel thread context. Can sleep.
11601  *
11602  * Assumptions:  - The given xp->xb_blkno is absolute
11603  *		   (ie, relative to the start of the device).
11604  *		 - The IO is to be done using the native blocksize of
11605  *		   the device, as specified in un->un_tgt_blocksize.
11606  */
11607 /* ARGSUSED */
11608 static void
11609 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
11610 {
11611 	struct sd_xbuf *xp;
11612 
11613 	ASSERT(un != NULL);
11614 	ASSERT(bp != NULL);
11615 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11616 	ASSERT(bp->b_resid == 0);
11617 
11618 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
11619 
11620 	xp = SD_GET_XBUF(bp);
11621 	ASSERT(xp != NULL);
11622 
11623 	mutex_enter(SD_MUTEX(un));
11624 
11625 	/*
11626 	 * If we are currently in the failfast state, fail any new IO
11627 	 * that has B_FAILFAST set, then return.
11628 	 */
11629 	if ((bp->b_flags & B_FAILFAST) &&
11630 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
11631 		mutex_exit(SD_MUTEX(un));
11632 		bioerror(bp, EIO);
11633 		bp->b_resid = bp->b_bcount;
11634 		SD_BEGIN_IODONE(index, un, bp);
11635 		return;
11636 	}
11637 
11638 	if (SD_IS_DIRECT_PRIORITY(xp)) {
11639 		/*
11640 		 * Priority command -- transport it immediately.
11641 		 *
11642 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
11643 		 * because all direct priority commands should be associated
11644 		 * with error recovery actions which we don't want to retry.
11645 		 */
11646 		sd_start_cmds(un, bp);
11647 	} else {
11648 		/*
11649 		 * Normal command -- add it to the wait queue, then start
11650 		 * transporting commands from the wait queue.
11651 		 */
11652 		sd_add_buf_to_waitq(un, bp);
11653 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
11654 		sd_start_cmds(un, NULL);
11655 	}
11656 
11657 	mutex_exit(SD_MUTEX(un));
11658 
11659 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
11660 }
11661 
11662 
11663 /*
11664  *    Function: sd_init_cdb_limits
11665  *
11666  * Description: This is to handle scsi_pkt initialization differences
11667  *		between the driver platforms.
11668  *
11669  *		Legacy behaviors:
11670  *
11671  *		If the block number or the sector count exceeds the
11672  *		capabilities of a Group 0 command, shift over to a
11673  *		Group 1 command. We don't blindly use Group 1
11674  *		commands because a) some drives (CDC Wren IVs) get a
11675  *		bit confused, and b) there is probably a fair amount
11676  *		of speed difference for a target to receive and decode
11677  *		a 10 byte command instead of a 6 byte command.
11678  *
11679  *		The xfer time difference of 6 vs 10 byte CDBs is
11680  *		still significant so this code is still worthwhile.
11681  *		10 byte CDBs are very inefficient with the fas HBA driver
11682  *		and older disks. Each CDB byte took 1 usec with some
11683  *		popular disks.
11684  *
11685  *     Context: Must be called at attach time
11686  */
11687 
11688 static void
11689 sd_init_cdb_limits(struct sd_lun *un)
11690 {
11691 	int hba_cdb_limit;
11692 
11693 	/*
11694 	 * Use CDB_GROUP1 commands for most devices except for
11695 	 * parallel SCSI fixed drives in which case we get better
11696 	 * performance using CDB_GROUP0 commands (where applicable).
11697 	 */
11698 	un->un_mincdb = SD_CDB_GROUP1;
11699 #if !defined(__fibre)
11700 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
11701 	    !un->un_f_has_removable_media) {
11702 		un->un_mincdb = SD_CDB_GROUP0;
11703 	}
11704 #endif
11705 
11706 	/*
11707 	 * Try to read the max-cdb-length supported by HBA.
11708 	 */
11709 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
11710 	if (0 >= un->un_max_hba_cdb) {
11711 		un->un_max_hba_cdb = CDB_GROUP4;
11712 		hba_cdb_limit = SD_CDB_GROUP4;
11713 	} else if (0 < un->un_max_hba_cdb &&
11714 	    un->un_max_hba_cdb < CDB_GROUP1) {
11715 		hba_cdb_limit = SD_CDB_GROUP0;
11716 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
11717 	    un->un_max_hba_cdb < CDB_GROUP5) {
11718 		hba_cdb_limit = SD_CDB_GROUP1;
11719 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
11720 	    un->un_max_hba_cdb < CDB_GROUP4) {
11721 		hba_cdb_limit = SD_CDB_GROUP5;
11722 	} else {
11723 		hba_cdb_limit = SD_CDB_GROUP4;
11724 	}
11725 
11726 	/*
11727 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
11728 	 * commands for fixed disks unless we are building for a 32 bit
11729 	 * kernel.
11730 	 */
11731 #ifdef _LP64
11732 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11733 	    min(hba_cdb_limit, SD_CDB_GROUP4);
11734 #else
11735 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11736 	    min(hba_cdb_limit, SD_CDB_GROUP1);
11737 #endif
11738 
11739 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
11740 	    ? sizeof (struct scsi_arq_status) : 1);
11741 	un->un_cmd_timeout = (ushort_t)sd_io_time;
11742 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
11743 }
11744 
11745 
11746 /*
11747  *    Function: sd_initpkt_for_buf
11748  *
11749  * Description: Allocate and initialize for transport a scsi_pkt struct,
11750  *		based upon the info specified in the given buf struct.
11751  *
11752  *		Assumes the xb_blkno in the request is absolute (ie,
11753  *		relative to the start of the device (NOT partition!).
11754  *		Also assumes that the request is using the native block
11755  *		size of the device (as returned by the READ CAPACITY
11756  *		command).
11757  *
11758  * Return Code: SD_PKT_ALLOC_SUCCESS
11759  *		SD_PKT_ALLOC_FAILURE
11760  *		SD_PKT_ALLOC_FAILURE_NO_DMA
11761  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11762  *
11763  *     Context: Kernel thread and may be called from software interrupt context
11764  *		as part of a sdrunout callback. This function may not block or
11765  *		call routines that block
11766  */
11767 
11768 static int
11769 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
11770 {
11771 	struct sd_xbuf	*xp;
11772 	struct scsi_pkt *pktp = NULL;
11773 	struct sd_lun	*un;
11774 	size_t		blockcount;
11775 	daddr_t		startblock;
11776 	int		rval;
11777 	int		cmd_flags;
11778 
11779 	ASSERT(bp != NULL);
11780 	ASSERT(pktpp != NULL);
11781 	xp = SD_GET_XBUF(bp);
11782 	ASSERT(xp != NULL);
11783 	un = SD_GET_UN(bp);
11784 	ASSERT(un != NULL);
11785 	ASSERT(mutex_owned(SD_MUTEX(un)));
11786 	ASSERT(bp->b_resid == 0);
11787 
11788 	SD_TRACE(SD_LOG_IO_CORE, un,
11789 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
11790 
11791 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11792 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
11793 		/*
11794 		 * Already have a scsi_pkt -- just need DMA resources.
11795 		 * We must recompute the CDB in case the mapping returns
11796 		 * a nonzero pkt_resid.
11797 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
11798 		 * that is being retried, the unmap/remap of the DMA resouces
11799 		 * will result in the entire transfer starting over again
11800 		 * from the very first block.
11801 		 */
11802 		ASSERT(xp->xb_pktp != NULL);
11803 		pktp = xp->xb_pktp;
11804 	} else {
11805 		pktp = NULL;
11806 	}
11807 #endif /* __i386 || __amd64 */
11808 
11809 	startblock = xp->xb_blkno;	/* Absolute block num. */
11810 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
11811 
11812 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11813 
11814 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
11815 
11816 #else
11817 
11818 	cmd_flags = un->un_pkt_flags | xp->xb_pkt_flags;
11819 
11820 #endif
11821 
11822 	/*
11823 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
11824 	 * call scsi_init_pkt, and build the CDB.
11825 	 */
11826 	rval = sd_setup_rw_pkt(un, &pktp, bp,
11827 	    cmd_flags, sdrunout, (caddr_t)un,
11828 	    startblock, blockcount);
11829 
11830 	if (rval == 0) {
11831 		/*
11832 		 * Success.
11833 		 *
11834 		 * If partial DMA is being used and required for this transfer.
11835 		 * set it up here.
11836 		 */
11837 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
11838 		    (pktp->pkt_resid != 0)) {
11839 
11840 			/*
11841 			 * Save the CDB length and pkt_resid for the
11842 			 * next xfer
11843 			 */
11844 			xp->xb_dma_resid = pktp->pkt_resid;
11845 
11846 			/* rezero resid */
11847 			pktp->pkt_resid = 0;
11848 
11849 		} else {
11850 			xp->xb_dma_resid = 0;
11851 		}
11852 
11853 		pktp->pkt_flags = un->un_tagflags;
11854 		pktp->pkt_time  = un->un_cmd_timeout;
11855 		pktp->pkt_comp  = sdintr;
11856 
11857 		pktp->pkt_private = bp;
11858 		*pktpp = pktp;
11859 
11860 		SD_TRACE(SD_LOG_IO_CORE, un,
11861 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
11862 
11863 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11864 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
11865 #endif
11866 
11867 		return (SD_PKT_ALLOC_SUCCESS);
11868 
11869 	}
11870 
11871 	/*
11872 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
11873 	 * from sd_setup_rw_pkt.
11874 	 */
11875 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
11876 
11877 	if (rval == SD_PKT_ALLOC_FAILURE) {
11878 		*pktpp = NULL;
11879 		/*
11880 		 * Set the driver state to RWAIT to indicate the driver
11881 		 * is waiting on resource allocations. The driver will not
11882 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
11883 		 */
11884 		New_state(un, SD_STATE_RWAIT);
11885 
11886 		SD_ERROR(SD_LOG_IO_CORE, un,
11887 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
11888 
11889 		if ((bp->b_flags & B_ERROR) != 0) {
11890 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
11891 		}
11892 		return (SD_PKT_ALLOC_FAILURE);
11893 	} else {
11894 		/*
11895 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11896 		 *
11897 		 * This should never happen.  Maybe someone messed with the
11898 		 * kernel's minphys?
11899 		 */
11900 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
11901 		    "Request rejected: too large for CDB: "
11902 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
11903 		SD_ERROR(SD_LOG_IO_CORE, un,
11904 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
11905 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
11906 
11907 	}
11908 }
11909 
11910 
11911 /*
11912  *    Function: sd_destroypkt_for_buf
11913  *
11914  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
11915  *
11916  *     Context: Kernel thread or interrupt context
11917  */
11918 
11919 static void
11920 sd_destroypkt_for_buf(struct buf *bp)
11921 {
11922 	ASSERT(bp != NULL);
11923 	ASSERT(SD_GET_UN(bp) != NULL);
11924 
11925 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11926 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
11927 
11928 	ASSERT(SD_GET_PKTP(bp) != NULL);
11929 	scsi_destroy_pkt(SD_GET_PKTP(bp));
11930 
11931 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11932 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
11933 }
11934 
11935 /*
11936  *    Function: sd_setup_rw_pkt
11937  *
11938  * Description: Determines appropriate CDB group for the requested LBA
11939  *		and transfer length, calls scsi_init_pkt, and builds
11940  *		the CDB.  Do not use for partial DMA transfers except
11941  *		for the initial transfer since the CDB size must
11942  *		remain constant.
11943  *
11944  *     Context: Kernel thread and may be called from software interrupt
11945  *		context as part of a sdrunout callback. This function may not
11946  *		block or call routines that block
11947  */
11948 
11949 
11950 int
11951 sd_setup_rw_pkt(struct sd_lun *un,
11952     struct scsi_pkt **pktpp, struct buf *bp, int flags,
11953     int (*callback)(caddr_t), caddr_t callback_arg,
11954     diskaddr_t lba, uint32_t blockcount)
11955 {
11956 	struct scsi_pkt *return_pktp;
11957 	union scsi_cdb *cdbp;
11958 	struct sd_cdbinfo *cp = NULL;
11959 	int i;
11960 
11961 	/*
11962 	 * See which size CDB to use, based upon the request.
11963 	 */
11964 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
11965 
11966 		/*
11967 		 * Check lba and block count against sd_cdbtab limits.
11968 		 * In the partial DMA case, we have to use the same size
11969 		 * CDB for all the transfers.  Check lba + blockcount
11970 		 * against the max LBA so we know that segment of the
11971 		 * transfer can use the CDB we select.
11972 		 */
11973 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
11974 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
11975 
11976 			/*
11977 			 * The command will fit into the CDB type
11978 			 * specified by sd_cdbtab[i].
11979 			 */
11980 			cp = sd_cdbtab + i;
11981 
11982 			/*
11983 			 * Call scsi_init_pkt so we can fill in the
11984 			 * CDB.
11985 			 */
11986 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
11987 			    bp, cp->sc_grpcode, un->un_status_len, 0,
11988 			    flags, callback, callback_arg);
11989 
11990 			if (return_pktp != NULL) {
11991 
11992 				/*
11993 				 * Return new value of pkt
11994 				 */
11995 				*pktpp = return_pktp;
11996 
11997 				/*
11998 				 * To be safe, zero the CDB insuring there is
11999 				 * no leftover data from a previous command.
12000 				 */
12001 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
12002 
12003 				/*
12004 				 * Handle partial DMA mapping
12005 				 */
12006 				if (return_pktp->pkt_resid != 0) {
12007 
12008 					/*
12009 					 * Not going to xfer as many blocks as
12010 					 * originally expected
12011 					 */
12012 					blockcount -=
12013 					    SD_BYTES2TGTBLOCKS(un,
12014 					    return_pktp->pkt_resid);
12015 				}
12016 
12017 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
12018 
12019 				/*
12020 				 * Set command byte based on the CDB
12021 				 * type we matched.
12022 				 */
12023 				cdbp->scc_cmd = cp->sc_grpmask |
12024 				    ((bp->b_flags & B_READ) ?
12025 				    SCMD_READ : SCMD_WRITE);
12026 
12027 				SD_FILL_SCSI1_LUN(un, return_pktp);
12028 
12029 				/*
12030 				 * Fill in LBA and length
12031 				 */
12032 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
12033 				    (cp->sc_grpcode == CDB_GROUP4) ||
12034 				    (cp->sc_grpcode == CDB_GROUP0) ||
12035 				    (cp->sc_grpcode == CDB_GROUP5));
12036 
12037 				if (cp->sc_grpcode == CDB_GROUP1) {
12038 					FORMG1ADDR(cdbp, lba);
12039 					FORMG1COUNT(cdbp, blockcount);
12040 					return (0);
12041 				} else if (cp->sc_grpcode == CDB_GROUP4) {
12042 					FORMG4LONGADDR(cdbp, lba);
12043 					FORMG4COUNT(cdbp, blockcount);
12044 					return (0);
12045 				} else if (cp->sc_grpcode == CDB_GROUP0) {
12046 					FORMG0ADDR(cdbp, lba);
12047 					FORMG0COUNT(cdbp, blockcount);
12048 					return (0);
12049 				} else if (cp->sc_grpcode == CDB_GROUP5) {
12050 					FORMG5ADDR(cdbp, lba);
12051 					FORMG5COUNT(cdbp, blockcount);
12052 					return (0);
12053 				}
12054 
12055 				/*
12056 				 * It should be impossible to not match one
12057 				 * of the CDB types above, so we should never
12058 				 * reach this point.  Set the CDB command byte
12059 				 * to test-unit-ready to avoid writing
12060 				 * to somewhere we don't intend.
12061 				 */
12062 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
12063 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12064 			} else {
12065 				/*
12066 				 * Couldn't get scsi_pkt
12067 				 */
12068 				return (SD_PKT_ALLOC_FAILURE);
12069 			}
12070 		}
12071 	}
12072 
12073 	/*
12074 	 * None of the available CDB types were suitable.  This really
12075 	 * should never happen:  on a 64 bit system we support
12076 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
12077 	 * and on a 32 bit system we will refuse to bind to a device
12078 	 * larger than 2TB so addresses will never be larger than 32 bits.
12079 	 */
12080 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12081 }
12082 
12083 /*
12084  *    Function: sd_setup_next_rw_pkt
12085  *
12086  * Description: Setup packet for partial DMA transfers, except for the
12087  * 		initial transfer.  sd_setup_rw_pkt should be used for
12088  *		the initial transfer.
12089  *
12090  *     Context: Kernel thread and may be called from interrupt context.
12091  */
12092 
12093 int
12094 sd_setup_next_rw_pkt(struct sd_lun *un,
12095     struct scsi_pkt *pktp, struct buf *bp,
12096     diskaddr_t lba, uint32_t blockcount)
12097 {
12098 	uchar_t com;
12099 	union scsi_cdb *cdbp;
12100 	uchar_t cdb_group_id;
12101 
12102 	ASSERT(pktp != NULL);
12103 	ASSERT(pktp->pkt_cdbp != NULL);
12104 
12105 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
12106 	com = cdbp->scc_cmd;
12107 	cdb_group_id = CDB_GROUPID(com);
12108 
12109 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
12110 	    (cdb_group_id == CDB_GROUPID_1) ||
12111 	    (cdb_group_id == CDB_GROUPID_4) ||
12112 	    (cdb_group_id == CDB_GROUPID_5));
12113 
12114 	/*
12115 	 * Move pkt to the next portion of the xfer.
12116 	 * func is NULL_FUNC so we do not have to release
12117 	 * the disk mutex here.
12118 	 */
12119 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
12120 	    NULL_FUNC, NULL) == pktp) {
12121 		/* Success.  Handle partial DMA */
12122 		if (pktp->pkt_resid != 0) {
12123 			blockcount -=
12124 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
12125 		}
12126 
12127 		cdbp->scc_cmd = com;
12128 		SD_FILL_SCSI1_LUN(un, pktp);
12129 		if (cdb_group_id == CDB_GROUPID_1) {
12130 			FORMG1ADDR(cdbp, lba);
12131 			FORMG1COUNT(cdbp, blockcount);
12132 			return (0);
12133 		} else if (cdb_group_id == CDB_GROUPID_4) {
12134 			FORMG4LONGADDR(cdbp, lba);
12135 			FORMG4COUNT(cdbp, blockcount);
12136 			return (0);
12137 		} else if (cdb_group_id == CDB_GROUPID_0) {
12138 			FORMG0ADDR(cdbp, lba);
12139 			FORMG0COUNT(cdbp, blockcount);
12140 			return (0);
12141 		} else if (cdb_group_id == CDB_GROUPID_5) {
12142 			FORMG5ADDR(cdbp, lba);
12143 			FORMG5COUNT(cdbp, blockcount);
12144 			return (0);
12145 		}
12146 
12147 		/* Unreachable */
12148 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12149 	}
12150 
12151 	/*
12152 	 * Error setting up next portion of cmd transfer.
12153 	 * Something is definitely very wrong and this
12154 	 * should not happen.
12155 	 */
12156 	return (SD_PKT_ALLOC_FAILURE);
12157 }
12158 
12159 /*
12160  *    Function: sd_initpkt_for_uscsi
12161  *
12162  * Description: Allocate and initialize for transport a scsi_pkt struct,
12163  *		based upon the info specified in the given uscsi_cmd struct.
12164  *
12165  * Return Code: SD_PKT_ALLOC_SUCCESS
12166  *		SD_PKT_ALLOC_FAILURE
12167  *		SD_PKT_ALLOC_FAILURE_NO_DMA
12168  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
12169  *
12170  *     Context: Kernel thread and may be called from software interrupt context
12171  *		as part of a sdrunout callback. This function may not block or
12172  *		call routines that block
12173  */
12174 
12175 static int
12176 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
12177 {
12178 	struct uscsi_cmd *uscmd;
12179 	struct sd_xbuf	*xp;
12180 	struct scsi_pkt	*pktp;
12181 	struct sd_lun	*un;
12182 	uint32_t	flags = 0;
12183 
12184 	ASSERT(bp != NULL);
12185 	ASSERT(pktpp != NULL);
12186 	xp = SD_GET_XBUF(bp);
12187 	ASSERT(xp != NULL);
12188 	un = SD_GET_UN(bp);
12189 	ASSERT(un != NULL);
12190 	ASSERT(mutex_owned(SD_MUTEX(un)));
12191 
12192 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12193 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12194 	ASSERT(uscmd != NULL);
12195 
12196 	SD_TRACE(SD_LOG_IO_CORE, un,
12197 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
12198 
12199 	/*
12200 	 * Allocate the scsi_pkt for the command.
12201 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
12202 	 *	 during scsi_init_pkt time and will continue to use the
12203 	 *	 same path as long as the same scsi_pkt is used without
12204 	 *	 intervening scsi_dma_free(). Since uscsi command does
12205 	 *	 not call scsi_dmafree() before retry failed command, it
12206 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
12207 	 *	 set such that scsi_vhci can use other available path for
12208 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
12209 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
12210 	 */
12211 	if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
12212 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
12213 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
12214 		    ((int)(uscmd->uscsi_rqlen) + sizeof (struct scsi_arq_status)
12215 		    - sizeof (struct scsi_extended_sense)), 0,
12216 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL) | PKT_XARQ,
12217 		    sdrunout, (caddr_t)un);
12218 	} else {
12219 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
12220 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
12221 		    sizeof (struct scsi_arq_status), 0,
12222 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
12223 		    sdrunout, (caddr_t)un);
12224 	}
12225 
12226 	if (pktp == NULL) {
12227 		*pktpp = NULL;
12228 		/*
12229 		 * Set the driver state to RWAIT to indicate the driver
12230 		 * is waiting on resource allocations. The driver will not
12231 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
12232 		 */
12233 		New_state(un, SD_STATE_RWAIT);
12234 
12235 		SD_ERROR(SD_LOG_IO_CORE, un,
12236 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
12237 
12238 		if ((bp->b_flags & B_ERROR) != 0) {
12239 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
12240 		}
12241 		return (SD_PKT_ALLOC_FAILURE);
12242 	}
12243 
12244 	/*
12245 	 * We do not do DMA breakup for USCSI commands, so return failure
12246 	 * here if all the needed DMA resources were not allocated.
12247 	 */
12248 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
12249 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
12250 		scsi_destroy_pkt(pktp);
12251 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
12252 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
12253 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
12254 	}
12255 
12256 	/* Init the cdb from the given uscsi struct */
12257 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
12258 	    uscmd->uscsi_cdb[0], 0, 0, 0);
12259 
12260 	SD_FILL_SCSI1_LUN(un, pktp);
12261 
12262 	/*
12263 	 * Set up the optional USCSI flags. See the uscsi (7I) man page
12264 	 * for listing of the supported flags.
12265 	 */
12266 
12267 	if (uscmd->uscsi_flags & USCSI_SILENT) {
12268 		flags |= FLAG_SILENT;
12269 	}
12270 
12271 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
12272 		flags |= FLAG_DIAGNOSE;
12273 	}
12274 
12275 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
12276 		flags |= FLAG_ISOLATE;
12277 	}
12278 
12279 	if (un->un_f_is_fibre == FALSE) {
12280 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
12281 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
12282 		}
12283 	}
12284 
12285 	/*
12286 	 * Set the pkt flags here so we save time later.
12287 	 * Note: These flags are NOT in the uscsi man page!!!
12288 	 */
12289 	if (uscmd->uscsi_flags & USCSI_HEAD) {
12290 		flags |= FLAG_HEAD;
12291 	}
12292 
12293 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
12294 		flags |= FLAG_NOINTR;
12295 	}
12296 
12297 	/*
12298 	 * For tagged queueing, things get a bit complicated.
12299 	 * Check first for head of queue and last for ordered queue.
12300 	 * If neither head nor order, use the default driver tag flags.
12301 	 */
12302 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
12303 		if (uscmd->uscsi_flags & USCSI_HTAG) {
12304 			flags |= FLAG_HTAG;
12305 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
12306 			flags |= FLAG_OTAG;
12307 		} else {
12308 			flags |= un->un_tagflags & FLAG_TAGMASK;
12309 		}
12310 	}
12311 
12312 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
12313 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
12314 	}
12315 
12316 	pktp->pkt_flags = flags;
12317 
12318 	/* Copy the caller's CDB into the pkt... */
12319 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
12320 
12321 	if (uscmd->uscsi_timeout == 0) {
12322 		pktp->pkt_time = un->un_uscsi_timeout;
12323 	} else {
12324 		pktp->pkt_time = uscmd->uscsi_timeout;
12325 	}
12326 
12327 	/* need it later to identify USCSI request in sdintr */
12328 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
12329 
12330 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
12331 
12332 	pktp->pkt_private = bp;
12333 	pktp->pkt_comp = sdintr;
12334 	*pktpp = pktp;
12335 
12336 	SD_TRACE(SD_LOG_IO_CORE, un,
12337 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
12338 
12339 	return (SD_PKT_ALLOC_SUCCESS);
12340 }
12341 
12342 
12343 /*
12344  *    Function: sd_destroypkt_for_uscsi
12345  *
12346  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
12347  *		IOs.. Also saves relevant info into the associated uscsi_cmd
12348  *		struct.
12349  *
12350  *     Context: May be called under interrupt context
12351  */
12352 
12353 static void
12354 sd_destroypkt_for_uscsi(struct buf *bp)
12355 {
12356 	struct uscsi_cmd *uscmd;
12357 	struct sd_xbuf	*xp;
12358 	struct scsi_pkt	*pktp;
12359 	struct sd_lun	*un;
12360 
12361 	ASSERT(bp != NULL);
12362 	xp = SD_GET_XBUF(bp);
12363 	ASSERT(xp != NULL);
12364 	un = SD_GET_UN(bp);
12365 	ASSERT(un != NULL);
12366 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12367 	pktp = SD_GET_PKTP(bp);
12368 	ASSERT(pktp != NULL);
12369 
12370 	SD_TRACE(SD_LOG_IO_CORE, un,
12371 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
12372 
12373 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12374 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12375 	ASSERT(uscmd != NULL);
12376 
12377 	/* Save the status and the residual into the uscsi_cmd struct */
12378 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
12379 	uscmd->uscsi_resid  = bp->b_resid;
12380 
12381 	/*
12382 	 * If enabled, copy any saved sense data into the area specified
12383 	 * by the uscsi command.
12384 	 */
12385 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
12386 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
12387 		/*
12388 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
12389 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
12390 		 */
12391 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
12392 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
12393 		if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
12394 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
12395 			    MAX_SENSE_LENGTH);
12396 		} else {
12397 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
12398 			    SENSE_LENGTH);
12399 		}
12400 	}
12401 
12402 	/* We are done with the scsi_pkt; free it now */
12403 	ASSERT(SD_GET_PKTP(bp) != NULL);
12404 	scsi_destroy_pkt(SD_GET_PKTP(bp));
12405 
12406 	SD_TRACE(SD_LOG_IO_CORE, un,
12407 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
12408 }
12409 
12410 
12411 /*
12412  *    Function: sd_bioclone_alloc
12413  *
12414  * Description: Allocate a buf(9S) and init it as per the given buf
12415  *		and the various arguments.  The associated sd_xbuf
12416  *		struct is (nearly) duplicated.  The struct buf *bp
12417  *		argument is saved in new_xp->xb_private.
12418  *
12419  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12420  *		datalen - size of data area for the shadow bp
12421  *		blkno - starting LBA
12422  *		func - function pointer for b_iodone in the shadow buf. (May
12423  *			be NULL if none.)
12424  *
12425  * Return Code: Pointer to allocates buf(9S) struct
12426  *
12427  *     Context: Can sleep.
12428  */
12429 
12430 static struct buf *
12431 sd_bioclone_alloc(struct buf *bp, size_t datalen,
12432 	daddr_t blkno, int (*func)(struct buf *))
12433 {
12434 	struct	sd_lun	*un;
12435 	struct	sd_xbuf	*xp;
12436 	struct	sd_xbuf	*new_xp;
12437 	struct	buf	*new_bp;
12438 
12439 	ASSERT(bp != NULL);
12440 	xp = SD_GET_XBUF(bp);
12441 	ASSERT(xp != NULL);
12442 	un = SD_GET_UN(bp);
12443 	ASSERT(un != NULL);
12444 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12445 
12446 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
12447 	    NULL, KM_SLEEP);
12448 
12449 	new_bp->b_lblkno	= blkno;
12450 
12451 	/*
12452 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12453 	 * original xbuf into it.
12454 	 */
12455 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12456 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12457 
12458 	/*
12459 	 * The given bp is automatically saved in the xb_private member
12460 	 * of the new xbuf.  Callers are allowed to depend on this.
12461 	 */
12462 	new_xp->xb_private = bp;
12463 
12464 	new_bp->b_private  = new_xp;
12465 
12466 	return (new_bp);
12467 }
12468 
12469 /*
12470  *    Function: sd_shadow_buf_alloc
12471  *
12472  * Description: Allocate a buf(9S) and init it as per the given buf
12473  *		and the various arguments.  The associated sd_xbuf
12474  *		struct is (nearly) duplicated.  The struct buf *bp
12475  *		argument is saved in new_xp->xb_private.
12476  *
12477  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12478  *		datalen - size of data area for the shadow bp
12479  *		bflags - B_READ or B_WRITE (pseudo flag)
12480  *		blkno - starting LBA
12481  *		func - function pointer for b_iodone in the shadow buf. (May
12482  *			be NULL if none.)
12483  *
12484  * Return Code: Pointer to allocates buf(9S) struct
12485  *
12486  *     Context: Can sleep.
12487  */
12488 
12489 static struct buf *
12490 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
12491 	daddr_t blkno, int (*func)(struct buf *))
12492 {
12493 	struct	sd_lun	*un;
12494 	struct	sd_xbuf	*xp;
12495 	struct	sd_xbuf	*new_xp;
12496 	struct	buf	*new_bp;
12497 
12498 	ASSERT(bp != NULL);
12499 	xp = SD_GET_XBUF(bp);
12500 	ASSERT(xp != NULL);
12501 	un = SD_GET_UN(bp);
12502 	ASSERT(un != NULL);
12503 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12504 
12505 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
12506 		bp_mapin(bp);
12507 	}
12508 
12509 	bflags &= (B_READ | B_WRITE);
12510 #if defined(__i386) || defined(__amd64)
12511 	new_bp = getrbuf(KM_SLEEP);
12512 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
12513 	new_bp->b_bcount = datalen;
12514 	new_bp->b_flags = bflags |
12515 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
12516 #else
12517 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
12518 	    datalen, bflags, SLEEP_FUNC, NULL);
12519 #endif
12520 	new_bp->av_forw	= NULL;
12521 	new_bp->av_back	= NULL;
12522 	new_bp->b_dev	= bp->b_dev;
12523 	new_bp->b_blkno	= blkno;
12524 	new_bp->b_iodone = func;
12525 	new_bp->b_edev	= bp->b_edev;
12526 	new_bp->b_resid	= 0;
12527 
12528 	/* We need to preserve the B_FAILFAST flag */
12529 	if (bp->b_flags & B_FAILFAST) {
12530 		new_bp->b_flags |= B_FAILFAST;
12531 	}
12532 
12533 	/*
12534 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12535 	 * original xbuf into it.
12536 	 */
12537 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12538 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12539 
12540 	/* Need later to copy data between the shadow buf & original buf! */
12541 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
12542 
12543 	/*
12544 	 * The given bp is automatically saved in the xb_private member
12545 	 * of the new xbuf.  Callers are allowed to depend on this.
12546 	 */
12547 	new_xp->xb_private = bp;
12548 
12549 	new_bp->b_private  = new_xp;
12550 
12551 	return (new_bp);
12552 }
12553 
12554 /*
12555  *    Function: sd_bioclone_free
12556  *
12557  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
12558  *		in the larger than partition operation.
12559  *
12560  *     Context: May be called under interrupt context
12561  */
12562 
12563 static void
12564 sd_bioclone_free(struct buf *bp)
12565 {
12566 	struct sd_xbuf	*xp;
12567 
12568 	ASSERT(bp != NULL);
12569 	xp = SD_GET_XBUF(bp);
12570 	ASSERT(xp != NULL);
12571 
12572 	/*
12573 	 * Call bp_mapout() before freeing the buf,  in case a lower
12574 	 * layer or HBA  had done a bp_mapin().  we must do this here
12575 	 * as we are the "originator" of the shadow buf.
12576 	 */
12577 	bp_mapout(bp);
12578 
12579 	/*
12580 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12581 	 * never gets confused by a stale value in this field. (Just a little
12582 	 * extra defensiveness here.)
12583 	 */
12584 	bp->b_iodone = NULL;
12585 
12586 	freerbuf(bp);
12587 
12588 	kmem_free(xp, sizeof (struct sd_xbuf));
12589 }
12590 
12591 /*
12592  *    Function: sd_shadow_buf_free
12593  *
12594  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
12595  *
12596  *     Context: May be called under interrupt context
12597  */
12598 
12599 static void
12600 sd_shadow_buf_free(struct buf *bp)
12601 {
12602 	struct sd_xbuf	*xp;
12603 
12604 	ASSERT(bp != NULL);
12605 	xp = SD_GET_XBUF(bp);
12606 	ASSERT(xp != NULL);
12607 
12608 #if defined(__sparc)
12609 	/*
12610 	 * Call bp_mapout() before freeing the buf,  in case a lower
12611 	 * layer or HBA  had done a bp_mapin().  we must do this here
12612 	 * as we are the "originator" of the shadow buf.
12613 	 */
12614 	bp_mapout(bp);
12615 #endif
12616 
12617 	/*
12618 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12619 	 * never gets confused by a stale value in this field. (Just a little
12620 	 * extra defensiveness here.)
12621 	 */
12622 	bp->b_iodone = NULL;
12623 
12624 #if defined(__i386) || defined(__amd64)
12625 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
12626 	freerbuf(bp);
12627 #else
12628 	scsi_free_consistent_buf(bp);
12629 #endif
12630 
12631 	kmem_free(xp, sizeof (struct sd_xbuf));
12632 }
12633 
12634 
12635 /*
12636  *    Function: sd_print_transport_rejected_message
12637  *
12638  * Description: This implements the ludicrously complex rules for printing
12639  *		a "transport rejected" message.  This is to address the
12640  *		specific problem of having a flood of this error message
12641  *		produced when a failover occurs.
12642  *
12643  *     Context: Any.
12644  */
12645 
12646 static void
12647 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
12648 	int code)
12649 {
12650 	ASSERT(un != NULL);
12651 	ASSERT(mutex_owned(SD_MUTEX(un)));
12652 	ASSERT(xp != NULL);
12653 
12654 	/*
12655 	 * Print the "transport rejected" message under the following
12656 	 * conditions:
12657 	 *
12658 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
12659 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
12660 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
12661 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
12662 	 *   scsi_transport(9F) (which indicates that the target might have
12663 	 *   gone off-line).  This uses the un->un_tran_fatal_count
12664 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
12665 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
12666 	 *   from scsi_transport().
12667 	 *
12668 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
12669 	 * the preceeding cases in order for the message to be printed.
12670 	 */
12671 	if ((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) {
12672 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
12673 		    (code != TRAN_FATAL_ERROR) ||
12674 		    (un->un_tran_fatal_count == 1)) {
12675 			switch (code) {
12676 			case TRAN_BADPKT:
12677 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12678 				    "transport rejected bad packet\n");
12679 				break;
12680 			case TRAN_FATAL_ERROR:
12681 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12682 				    "transport rejected fatal error\n");
12683 				break;
12684 			default:
12685 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12686 				    "transport rejected (%d)\n", code);
12687 				break;
12688 			}
12689 		}
12690 	}
12691 }
12692 
12693 
12694 /*
12695  *    Function: sd_add_buf_to_waitq
12696  *
12697  * Description: Add the given buf(9S) struct to the wait queue for the
12698  *		instance.  If sorting is enabled, then the buf is added
12699  *		to the queue via an elevator sort algorithm (a la
12700  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
12701  *		If sorting is not enabled, then the buf is just added
12702  *		to the end of the wait queue.
12703  *
12704  * Return Code: void
12705  *
12706  *     Context: Does not sleep/block, therefore technically can be called
12707  *		from any context.  However if sorting is enabled then the
12708  *		execution time is indeterminate, and may take long if
12709  *		the wait queue grows large.
12710  */
12711 
12712 static void
12713 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
12714 {
12715 	struct buf *ap;
12716 
12717 	ASSERT(bp != NULL);
12718 	ASSERT(un != NULL);
12719 	ASSERT(mutex_owned(SD_MUTEX(un)));
12720 
12721 	/* If the queue is empty, add the buf as the only entry & return. */
12722 	if (un->un_waitq_headp == NULL) {
12723 		ASSERT(un->un_waitq_tailp == NULL);
12724 		un->un_waitq_headp = un->un_waitq_tailp = bp;
12725 		bp->av_forw = NULL;
12726 		return;
12727 	}
12728 
12729 	ASSERT(un->un_waitq_tailp != NULL);
12730 
12731 	/*
12732 	 * If sorting is disabled, just add the buf to the tail end of
12733 	 * the wait queue and return.
12734 	 */
12735 	if (un->un_f_disksort_disabled) {
12736 		un->un_waitq_tailp->av_forw = bp;
12737 		un->un_waitq_tailp = bp;
12738 		bp->av_forw = NULL;
12739 		return;
12740 	}
12741 
12742 	/*
12743 	 * Sort thru the list of requests currently on the wait queue
12744 	 * and add the new buf request at the appropriate position.
12745 	 *
12746 	 * The un->un_waitq_headp is an activity chain pointer on which
12747 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
12748 	 * first queue holds those requests which are positioned after
12749 	 * the current SD_GET_BLKNO() (in the first request); the second holds
12750 	 * requests which came in after their SD_GET_BLKNO() number was passed.
12751 	 * Thus we implement a one way scan, retracting after reaching
12752 	 * the end of the drive to the first request on the second
12753 	 * queue, at which time it becomes the first queue.
12754 	 * A one-way scan is natural because of the way UNIX read-ahead
12755 	 * blocks are allocated.
12756 	 *
12757 	 * If we lie after the first request, then we must locate the
12758 	 * second request list and add ourselves to it.
12759 	 */
12760 	ap = un->un_waitq_headp;
12761 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
12762 		while (ap->av_forw != NULL) {
12763 			/*
12764 			 * Look for an "inversion" in the (normally
12765 			 * ascending) block numbers. This indicates
12766 			 * the start of the second request list.
12767 			 */
12768 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
12769 				/*
12770 				 * Search the second request list for the
12771 				 * first request at a larger block number.
12772 				 * We go before that; however if there is
12773 				 * no such request, we go at the end.
12774 				 */
12775 				do {
12776 					if (SD_GET_BLKNO(bp) <
12777 					    SD_GET_BLKNO(ap->av_forw)) {
12778 						goto insert;
12779 					}
12780 					ap = ap->av_forw;
12781 				} while (ap->av_forw != NULL);
12782 				goto insert;		/* after last */
12783 			}
12784 			ap = ap->av_forw;
12785 		}
12786 
12787 		/*
12788 		 * No inversions... we will go after the last, and
12789 		 * be the first request in the second request list.
12790 		 */
12791 		goto insert;
12792 	}
12793 
12794 	/*
12795 	 * Request is at/after the current request...
12796 	 * sort in the first request list.
12797 	 */
12798 	while (ap->av_forw != NULL) {
12799 		/*
12800 		 * We want to go after the current request (1) if
12801 		 * there is an inversion after it (i.e. it is the end
12802 		 * of the first request list), or (2) if the next
12803 		 * request is a larger block no. than our request.
12804 		 */
12805 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
12806 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
12807 			goto insert;
12808 		}
12809 		ap = ap->av_forw;
12810 	}
12811 
12812 	/*
12813 	 * Neither a second list nor a larger request, therefore
12814 	 * we go at the end of the first list (which is the same
12815 	 * as the end of the whole schebang).
12816 	 */
12817 insert:
12818 	bp->av_forw = ap->av_forw;
12819 	ap->av_forw = bp;
12820 
12821 	/*
12822 	 * If we inserted onto the tail end of the waitq, make sure the
12823 	 * tail pointer is updated.
12824 	 */
12825 	if (ap == un->un_waitq_tailp) {
12826 		un->un_waitq_tailp = bp;
12827 	}
12828 }
12829 
12830 
12831 /*
12832  *    Function: sd_start_cmds
12833  *
12834  * Description: Remove and transport cmds from the driver queues.
12835  *
12836  *   Arguments: un - pointer to the unit (soft state) struct for the target.
12837  *
12838  *		immed_bp - ptr to a buf to be transported immediately. Only
12839  *		the immed_bp is transported; bufs on the waitq are not
12840  *		processed and the un_retry_bp is not checked.  If immed_bp is
12841  *		NULL, then normal queue processing is performed.
12842  *
12843  *     Context: May be called from kernel thread context, interrupt context,
12844  *		or runout callback context. This function may not block or
12845  *		call routines that block.
12846  */
12847 
12848 static void
12849 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
12850 {
12851 	struct	sd_xbuf	*xp;
12852 	struct	buf	*bp;
12853 	void	(*statp)(kstat_io_t *);
12854 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12855 	void	(*saved_statp)(kstat_io_t *);
12856 #endif
12857 	int	rval;
12858 
12859 	ASSERT(un != NULL);
12860 	ASSERT(mutex_owned(SD_MUTEX(un)));
12861 	ASSERT(un->un_ncmds_in_transport >= 0);
12862 	ASSERT(un->un_throttle >= 0);
12863 
12864 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
12865 
12866 	do {
12867 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12868 		saved_statp = NULL;
12869 #endif
12870 
12871 		/*
12872 		 * If we are syncing or dumping, fail the command to
12873 		 * avoid recursively calling back into scsi_transport().
12874 		 * The dump I/O itself uses a separate code path so this
12875 		 * only prevents non-dump I/O from being sent while dumping.
12876 		 * File system sync takes place before dumping begins.
12877 		 * During panic, filesystem I/O is allowed provided
12878 		 * un_in_callback is <= 1.  This is to prevent recursion
12879 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
12880 		 * sd_start_cmds and so on.  See panic.c for more information
12881 		 * about the states the system can be in during panic.
12882 		 */
12883 		if ((un->un_state == SD_STATE_DUMPING) ||
12884 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
12885 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12886 			    "sd_start_cmds: panicking\n");
12887 			goto exit;
12888 		}
12889 
12890 		if ((bp = immed_bp) != NULL) {
12891 			/*
12892 			 * We have a bp that must be transported immediately.
12893 			 * It's OK to transport the immed_bp here without doing
12894 			 * the throttle limit check because the immed_bp is
12895 			 * always used in a retry/recovery case. This means
12896 			 * that we know we are not at the throttle limit by
12897 			 * virtue of the fact that to get here we must have
12898 			 * already gotten a command back via sdintr(). This also
12899 			 * relies on (1) the command on un_retry_bp preventing
12900 			 * further commands from the waitq from being issued;
12901 			 * and (2) the code in sd_retry_command checking the
12902 			 * throttle limit before issuing a delayed or immediate
12903 			 * retry. This holds even if the throttle limit is
12904 			 * currently ratcheted down from its maximum value.
12905 			 */
12906 			statp = kstat_runq_enter;
12907 			if (bp == un->un_retry_bp) {
12908 				ASSERT((un->un_retry_statp == NULL) ||
12909 				    (un->un_retry_statp == kstat_waitq_enter) ||
12910 				    (un->un_retry_statp ==
12911 				    kstat_runq_back_to_waitq));
12912 				/*
12913 				 * If the waitq kstat was incremented when
12914 				 * sd_set_retry_bp() queued this bp for a retry,
12915 				 * then we must set up statp so that the waitq
12916 				 * count will get decremented correctly below.
12917 				 * Also we must clear un->un_retry_statp to
12918 				 * ensure that we do not act on a stale value
12919 				 * in this field.
12920 				 */
12921 				if ((un->un_retry_statp == kstat_waitq_enter) ||
12922 				    (un->un_retry_statp ==
12923 				    kstat_runq_back_to_waitq)) {
12924 					statp = kstat_waitq_to_runq;
12925 				}
12926 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12927 				saved_statp = un->un_retry_statp;
12928 #endif
12929 				un->un_retry_statp = NULL;
12930 
12931 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
12932 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
12933 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
12934 				    un, un->un_retry_bp, un->un_throttle,
12935 				    un->un_ncmds_in_transport);
12936 			} else {
12937 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
12938 				    "processing priority bp:0x%p\n", bp);
12939 			}
12940 
12941 		} else if ((bp = un->un_waitq_headp) != NULL) {
12942 			/*
12943 			 * A command on the waitq is ready to go, but do not
12944 			 * send it if:
12945 			 *
12946 			 * (1) the throttle limit has been reached, or
12947 			 * (2) a retry is pending, or
12948 			 * (3) a START_STOP_UNIT callback pending, or
12949 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
12950 			 *	command is pending.
12951 			 *
12952 			 * For all of these conditions, IO processing will
12953 			 * restart after the condition is cleared.
12954 			 */
12955 			if (un->un_ncmds_in_transport >= un->un_throttle) {
12956 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12957 				    "sd_start_cmds: exiting, "
12958 				    "throttle limit reached!\n");
12959 				goto exit;
12960 			}
12961 			if (un->un_retry_bp != NULL) {
12962 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12963 				    "sd_start_cmds: exiting, retry pending!\n");
12964 				goto exit;
12965 			}
12966 			if (un->un_startstop_timeid != NULL) {
12967 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12968 				    "sd_start_cmds: exiting, "
12969 				    "START_STOP pending!\n");
12970 				goto exit;
12971 			}
12972 			if (un->un_direct_priority_timeid != NULL) {
12973 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12974 				    "sd_start_cmds: exiting, "
12975 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
12976 				goto exit;
12977 			}
12978 
12979 			/* Dequeue the command */
12980 			un->un_waitq_headp = bp->av_forw;
12981 			if (un->un_waitq_headp == NULL) {
12982 				un->un_waitq_tailp = NULL;
12983 			}
12984 			bp->av_forw = NULL;
12985 			statp = kstat_waitq_to_runq;
12986 			SD_TRACE(SD_LOG_IO_CORE, un,
12987 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
12988 
12989 		} else {
12990 			/* No work to do so bail out now */
12991 			SD_TRACE(SD_LOG_IO_CORE, un,
12992 			    "sd_start_cmds: no more work, exiting!\n");
12993 			goto exit;
12994 		}
12995 
12996 		/*
12997 		 * Reset the state to normal. This is the mechanism by which
12998 		 * the state transitions from either SD_STATE_RWAIT or
12999 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
13000 		 * If state is SD_STATE_PM_CHANGING then this command is
13001 		 * part of the device power control and the state must
13002 		 * not be put back to normal. Doing so would would
13003 		 * allow new commands to proceed when they shouldn't,
13004 		 * the device may be going off.
13005 		 */
13006 		if ((un->un_state != SD_STATE_SUSPENDED) &&
13007 		    (un->un_state != SD_STATE_PM_CHANGING)) {
13008 			New_state(un, SD_STATE_NORMAL);
13009 		}
13010 
13011 		xp = SD_GET_XBUF(bp);
13012 		ASSERT(xp != NULL);
13013 
13014 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13015 		/*
13016 		 * Allocate the scsi_pkt if we need one, or attach DMA
13017 		 * resources if we have a scsi_pkt that needs them. The
13018 		 * latter should only occur for commands that are being
13019 		 * retried.
13020 		 */
13021 		if ((xp->xb_pktp == NULL) ||
13022 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
13023 #else
13024 		if (xp->xb_pktp == NULL) {
13025 #endif
13026 			/*
13027 			 * There is no scsi_pkt allocated for this buf. Call
13028 			 * the initpkt function to allocate & init one.
13029 			 *
13030 			 * The scsi_init_pkt runout callback functionality is
13031 			 * implemented as follows:
13032 			 *
13033 			 * 1) The initpkt function always calls
13034 			 *    scsi_init_pkt(9F) with sdrunout specified as the
13035 			 *    callback routine.
13036 			 * 2) A successful packet allocation is initialized and
13037 			 *    the I/O is transported.
13038 			 * 3) The I/O associated with an allocation resource
13039 			 *    failure is left on its queue to be retried via
13040 			 *    runout or the next I/O.
13041 			 * 4) The I/O associated with a DMA error is removed
13042 			 *    from the queue and failed with EIO. Processing of
13043 			 *    the transport queues is also halted to be
13044 			 *    restarted via runout or the next I/O.
13045 			 * 5) The I/O associated with a CDB size or packet
13046 			 *    size error is removed from the queue and failed
13047 			 *    with EIO. Processing of the transport queues is
13048 			 *    continued.
13049 			 *
13050 			 * Note: there is no interface for canceling a runout
13051 			 * callback. To prevent the driver from detaching or
13052 			 * suspending while a runout is pending the driver
13053 			 * state is set to SD_STATE_RWAIT
13054 			 *
13055 			 * Note: using the scsi_init_pkt callback facility can
13056 			 * result in an I/O request persisting at the head of
13057 			 * the list which cannot be satisfied even after
13058 			 * multiple retries. In the future the driver may
13059 			 * implement some kind of maximum runout count before
13060 			 * failing an I/O.
13061 			 *
13062 			 * Note: the use of funcp below may seem superfluous,
13063 			 * but it helps warlock figure out the correct
13064 			 * initpkt function calls (see [s]sd.wlcmd).
13065 			 */
13066 			struct scsi_pkt	*pktp;
13067 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
13068 
13069 			ASSERT(bp != un->un_rqs_bp);
13070 
13071 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
13072 			switch ((*funcp)(bp, &pktp)) {
13073 			case  SD_PKT_ALLOC_SUCCESS:
13074 				xp->xb_pktp = pktp;
13075 				SD_TRACE(SD_LOG_IO_CORE, un,
13076 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
13077 				    pktp);
13078 				goto got_pkt;
13079 
13080 			case SD_PKT_ALLOC_FAILURE:
13081 				/*
13082 				 * Temporary (hopefully) resource depletion.
13083 				 * Since retries and RQS commands always have a
13084 				 * scsi_pkt allocated, these cases should never
13085 				 * get here. So the only cases this needs to
13086 				 * handle is a bp from the waitq (which we put
13087 				 * back onto the waitq for sdrunout), or a bp
13088 				 * sent as an immed_bp (which we just fail).
13089 				 */
13090 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13091 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
13092 
13093 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13094 
13095 				if (bp == immed_bp) {
13096 					/*
13097 					 * If SD_XB_DMA_FREED is clear, then
13098 					 * this is a failure to allocate a
13099 					 * scsi_pkt, and we must fail the
13100 					 * command.
13101 					 */
13102 					if ((xp->xb_pkt_flags &
13103 					    SD_XB_DMA_FREED) == 0) {
13104 						break;
13105 					}
13106 
13107 					/*
13108 					 * If this immediate command is NOT our
13109 					 * un_retry_bp, then we must fail it.
13110 					 */
13111 					if (bp != un->un_retry_bp) {
13112 						break;
13113 					}
13114 
13115 					/*
13116 					 * We get here if this cmd is our
13117 					 * un_retry_bp that was DMAFREED, but
13118 					 * scsi_init_pkt() failed to reallocate
13119 					 * DMA resources when we attempted to
13120 					 * retry it. This can happen when an
13121 					 * mpxio failover is in progress, but
13122 					 * we don't want to just fail the
13123 					 * command in this case.
13124 					 *
13125 					 * Use timeout(9F) to restart it after
13126 					 * a 100ms delay.  We don't want to
13127 					 * let sdrunout() restart it, because
13128 					 * sdrunout() is just supposed to start
13129 					 * commands that are sitting on the
13130 					 * wait queue.  The un_retry_bp stays
13131 					 * set until the command completes, but
13132 					 * sdrunout can be called many times
13133 					 * before that happens.  Since sdrunout
13134 					 * cannot tell if the un_retry_bp is
13135 					 * already in the transport, it could
13136 					 * end up calling scsi_transport() for
13137 					 * the un_retry_bp multiple times.
13138 					 *
13139 					 * Also: don't schedule the callback
13140 					 * if some other callback is already
13141 					 * pending.
13142 					 */
13143 					if (un->un_retry_statp == NULL) {
13144 						/*
13145 						 * restore the kstat pointer to
13146 						 * keep kstat counts coherent
13147 						 * when we do retry the command.
13148 						 */
13149 						un->un_retry_statp =
13150 						    saved_statp;
13151 					}
13152 
13153 					if ((un->un_startstop_timeid == NULL) &&
13154 					    (un->un_retry_timeid == NULL) &&
13155 					    (un->un_direct_priority_timeid ==
13156 					    NULL)) {
13157 
13158 						un->un_retry_timeid =
13159 						    timeout(
13160 						    sd_start_retry_command,
13161 						    un, SD_RESTART_TIMEOUT);
13162 					}
13163 					goto exit;
13164 				}
13165 
13166 #else
13167 				if (bp == immed_bp) {
13168 					break;	/* Just fail the command */
13169 				}
13170 #endif
13171 
13172 				/* Add the buf back to the head of the waitq */
13173 				bp->av_forw = un->un_waitq_headp;
13174 				un->un_waitq_headp = bp;
13175 				if (un->un_waitq_tailp == NULL) {
13176 					un->un_waitq_tailp = bp;
13177 				}
13178 				goto exit;
13179 
13180 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
13181 				/*
13182 				 * HBA DMA resource failure. Fail the command
13183 				 * and continue processing of the queues.
13184 				 */
13185 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13186 				    "sd_start_cmds: "
13187 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
13188 				break;
13189 
13190 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
13191 				/*
13192 				 * Note:x86: Partial DMA mapping not supported
13193 				 * for USCSI commands, and all the needed DMA
13194 				 * resources were not allocated.
13195 				 */
13196 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13197 				    "sd_start_cmds: "
13198 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
13199 				break;
13200 
13201 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
13202 				/*
13203 				 * Note:x86: Request cannot fit into CDB based
13204 				 * on lba and len.
13205 				 */
13206 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13207 				    "sd_start_cmds: "
13208 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
13209 				break;
13210 
13211 			default:
13212 				/* Should NEVER get here! */
13213 				panic("scsi_initpkt error");
13214 				/*NOTREACHED*/
13215 			}
13216 
13217 			/*
13218 			 * Fatal error in allocating a scsi_pkt for this buf.
13219 			 * Update kstats & return the buf with an error code.
13220 			 * We must use sd_return_failed_command_no_restart() to
13221 			 * avoid a recursive call back into sd_start_cmds().
13222 			 * However this also means that we must keep processing
13223 			 * the waitq here in order to avoid stalling.
13224 			 */
13225 			if (statp == kstat_waitq_to_runq) {
13226 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
13227 			}
13228 			sd_return_failed_command_no_restart(un, bp, EIO);
13229 			if (bp == immed_bp) {
13230 				/* immed_bp is gone by now, so clear this */
13231 				immed_bp = NULL;
13232 			}
13233 			continue;
13234 		}
13235 got_pkt:
13236 		if (bp == immed_bp) {
13237 			/* goto the head of the class.... */
13238 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13239 		}
13240 
13241 		un->un_ncmds_in_transport++;
13242 		SD_UPDATE_KSTATS(un, statp, bp);
13243 
13244 		/*
13245 		 * Call scsi_transport() to send the command to the target.
13246 		 * According to SCSA architecture, we must drop the mutex here
13247 		 * before calling scsi_transport() in order to avoid deadlock.
13248 		 * Note that the scsi_pkt's completion routine can be executed
13249 		 * (from interrupt context) even before the call to
13250 		 * scsi_transport() returns.
13251 		 */
13252 		SD_TRACE(SD_LOG_IO_CORE, un,
13253 		    "sd_start_cmds: calling scsi_transport()\n");
13254 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
13255 
13256 		mutex_exit(SD_MUTEX(un));
13257 		rval = scsi_transport(xp->xb_pktp);
13258 		mutex_enter(SD_MUTEX(un));
13259 
13260 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13261 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
13262 
13263 		switch (rval) {
13264 		case TRAN_ACCEPT:
13265 			/* Clear this with every pkt accepted by the HBA */
13266 			un->un_tran_fatal_count = 0;
13267 			break;	/* Success; try the next cmd (if any) */
13268 
13269 		case TRAN_BUSY:
13270 			un->un_ncmds_in_transport--;
13271 			ASSERT(un->un_ncmds_in_transport >= 0);
13272 
13273 			/*
13274 			 * Don't retry request sense, the sense data
13275 			 * is lost when another request is sent.
13276 			 * Free up the rqs buf and retry
13277 			 * the original failed cmd.  Update kstat.
13278 			 */
13279 			if (bp == un->un_rqs_bp) {
13280 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13281 				bp = sd_mark_rqs_idle(un, xp);
13282 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
13283 				    NULL, NULL, EIO, SD_BSY_TIMEOUT / 500,
13284 				    kstat_waitq_enter);
13285 				goto exit;
13286 			}
13287 
13288 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13289 			/*
13290 			 * Free the DMA resources for the  scsi_pkt. This will
13291 			 * allow mpxio to select another path the next time
13292 			 * we call scsi_transport() with this scsi_pkt.
13293 			 * See sdintr() for the rationalization behind this.
13294 			 */
13295 			if ((un->un_f_is_fibre == TRUE) &&
13296 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
13297 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
13298 				scsi_dmafree(xp->xb_pktp);
13299 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
13300 			}
13301 #endif
13302 
13303 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
13304 				/*
13305 				 * Commands that are SD_PATH_DIRECT_PRIORITY
13306 				 * are for error recovery situations. These do
13307 				 * not use the normal command waitq, so if they
13308 				 * get a TRAN_BUSY we cannot put them back onto
13309 				 * the waitq for later retry. One possible
13310 				 * problem is that there could already be some
13311 				 * other command on un_retry_bp that is waiting
13312 				 * for this one to complete, so we would be
13313 				 * deadlocked if we put this command back onto
13314 				 * the waitq for later retry (since un_retry_bp
13315 				 * must complete before the driver gets back to
13316 				 * commands on the waitq).
13317 				 *
13318 				 * To avoid deadlock we must schedule a callback
13319 				 * that will restart this command after a set
13320 				 * interval.  This should keep retrying for as
13321 				 * long as the underlying transport keeps
13322 				 * returning TRAN_BUSY (just like for other
13323 				 * commands).  Use the same timeout interval as
13324 				 * for the ordinary TRAN_BUSY retry.
13325 				 */
13326 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13327 				    "sd_start_cmds: scsi_transport() returned "
13328 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
13329 
13330 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13331 				un->un_direct_priority_timeid =
13332 				    timeout(sd_start_direct_priority_command,
13333 				    bp, SD_BSY_TIMEOUT / 500);
13334 
13335 				goto exit;
13336 			}
13337 
13338 			/*
13339 			 * For TRAN_BUSY, we want to reduce the throttle value,
13340 			 * unless we are retrying a command.
13341 			 */
13342 			if (bp != un->un_retry_bp) {
13343 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
13344 			}
13345 
13346 			/*
13347 			 * Set up the bp to be tried again 10 ms later.
13348 			 * Note:x86: Is there a timeout value in the sd_lun
13349 			 * for this condition?
13350 			 */
13351 			sd_set_retry_bp(un, bp, SD_BSY_TIMEOUT / 500,
13352 			    kstat_runq_back_to_waitq);
13353 			goto exit;
13354 
13355 		case TRAN_FATAL_ERROR:
13356 			un->un_tran_fatal_count++;
13357 			/* FALLTHRU */
13358 
13359 		case TRAN_BADPKT:
13360 		default:
13361 			un->un_ncmds_in_transport--;
13362 			ASSERT(un->un_ncmds_in_transport >= 0);
13363 
13364 			/*
13365 			 * If this is our REQUEST SENSE command with a
13366 			 * transport error, we must get back the pointers
13367 			 * to the original buf, and mark the REQUEST
13368 			 * SENSE command as "available".
13369 			 */
13370 			if (bp == un->un_rqs_bp) {
13371 				bp = sd_mark_rqs_idle(un, xp);
13372 				xp = SD_GET_XBUF(bp);
13373 			} else {
13374 				/*
13375 				 * Legacy behavior: do not update transport
13376 				 * error count for request sense commands.
13377 				 */
13378 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
13379 			}
13380 
13381 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13382 			sd_print_transport_rejected_message(un, xp, rval);
13383 
13384 			/*
13385 			 * We must use sd_return_failed_command_no_restart() to
13386 			 * avoid a recursive call back into sd_start_cmds().
13387 			 * However this also means that we must keep processing
13388 			 * the waitq here in order to avoid stalling.
13389 			 */
13390 			sd_return_failed_command_no_restart(un, bp, EIO);
13391 
13392 			/*
13393 			 * Notify any threads waiting in sd_ddi_suspend() that
13394 			 * a command completion has occurred.
13395 			 */
13396 			if (un->un_state == SD_STATE_SUSPENDED) {
13397 				cv_broadcast(&un->un_disk_busy_cv);
13398 			}
13399 
13400 			if (bp == immed_bp) {
13401 				/* immed_bp is gone by now, so clear this */
13402 				immed_bp = NULL;
13403 			}
13404 			break;
13405 		}
13406 
13407 	} while (immed_bp == NULL);
13408 
13409 exit:
13410 	ASSERT(mutex_owned(SD_MUTEX(un)));
13411 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
13412 }
13413 
13414 
13415 /*
13416  *    Function: sd_return_command
13417  *
13418  * Description: Returns a command to its originator (with or without an
13419  *		error).  Also starts commands waiting to be transported
13420  *		to the target.
13421  *
13422  *     Context: May be called from interrupt, kernel, or timeout context
13423  */
13424 
13425 static void
13426 sd_return_command(struct sd_lun *un, struct buf *bp)
13427 {
13428 	struct sd_xbuf *xp;
13429 	struct scsi_pkt *pktp;
13430 
13431 	ASSERT(bp != NULL);
13432 	ASSERT(un != NULL);
13433 	ASSERT(mutex_owned(SD_MUTEX(un)));
13434 	ASSERT(bp != un->un_rqs_bp);
13435 	xp = SD_GET_XBUF(bp);
13436 	ASSERT(xp != NULL);
13437 
13438 	pktp = SD_GET_PKTP(bp);
13439 
13440 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
13441 
13442 	/*
13443 	 * Note: check for the "sdrestart failed" case.
13444 	 */
13445 	if ((un->un_partial_dma_supported == 1) &&
13446 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
13447 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
13448 	    (xp->xb_pktp->pkt_resid == 0)) {
13449 
13450 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
13451 			/*
13452 			 * Successfully set up next portion of cmd
13453 			 * transfer, try sending it
13454 			 */
13455 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
13456 			    NULL, NULL, 0, (clock_t)0, NULL);
13457 			sd_start_cmds(un, NULL);
13458 			return;	/* Note:x86: need a return here? */
13459 		}
13460 	}
13461 
13462 	/*
13463 	 * If this is the failfast bp, clear it from un_failfast_bp. This
13464 	 * can happen if upon being re-tried the failfast bp either
13465 	 * succeeded or encountered another error (possibly even a different
13466 	 * error than the one that precipitated the failfast state, but in
13467 	 * that case it would have had to exhaust retries as well). Regardless,
13468 	 * this should not occur whenever the instance is in the active
13469 	 * failfast state.
13470 	 */
13471 	if (bp == un->un_failfast_bp) {
13472 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13473 		un->un_failfast_bp = NULL;
13474 	}
13475 
13476 	/*
13477 	 * Clear the failfast state upon successful completion of ANY cmd.
13478 	 */
13479 	if (bp->b_error == 0) {
13480 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13481 	}
13482 
13483 	/*
13484 	 * This is used if the command was retried one or more times. Show that
13485 	 * we are done with it, and allow processing of the waitq to resume.
13486 	 */
13487 	if (bp == un->un_retry_bp) {
13488 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13489 		    "sd_return_command: un:0x%p: "
13490 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13491 		un->un_retry_bp = NULL;
13492 		un->un_retry_statp = NULL;
13493 	}
13494 
13495 	SD_UPDATE_RDWR_STATS(un, bp);
13496 	SD_UPDATE_PARTITION_STATS(un, bp);
13497 
13498 	switch (un->un_state) {
13499 	case SD_STATE_SUSPENDED:
13500 		/*
13501 		 * Notify any threads waiting in sd_ddi_suspend() that
13502 		 * a command completion has occurred.
13503 		 */
13504 		cv_broadcast(&un->un_disk_busy_cv);
13505 		break;
13506 	default:
13507 		sd_start_cmds(un, NULL);
13508 		break;
13509 	}
13510 
13511 	/* Return this command up the iodone chain to its originator. */
13512 	mutex_exit(SD_MUTEX(un));
13513 
13514 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13515 	xp->xb_pktp = NULL;
13516 
13517 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13518 
13519 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13520 	mutex_enter(SD_MUTEX(un));
13521 
13522 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
13523 }
13524 
13525 
13526 /*
13527  *    Function: sd_return_failed_command
13528  *
13529  * Description: Command completion when an error occurred.
13530  *
13531  *     Context: May be called from interrupt context
13532  */
13533 
13534 static void
13535 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
13536 {
13537 	ASSERT(bp != NULL);
13538 	ASSERT(un != NULL);
13539 	ASSERT(mutex_owned(SD_MUTEX(un)));
13540 
13541 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13542 	    "sd_return_failed_command: entry\n");
13543 
13544 	/*
13545 	 * b_resid could already be nonzero due to a partial data
13546 	 * transfer, so do not change it here.
13547 	 */
13548 	SD_BIOERROR(bp, errcode);
13549 
13550 	sd_return_command(un, bp);
13551 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13552 	    "sd_return_failed_command: exit\n");
13553 }
13554 
13555 
13556 /*
13557  *    Function: sd_return_failed_command_no_restart
13558  *
13559  * Description: Same as sd_return_failed_command, but ensures that no
13560  *		call back into sd_start_cmds will be issued.
13561  *
13562  *     Context: May be called from interrupt context
13563  */
13564 
13565 static void
13566 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
13567 	int errcode)
13568 {
13569 	struct sd_xbuf *xp;
13570 
13571 	ASSERT(bp != NULL);
13572 	ASSERT(un != NULL);
13573 	ASSERT(mutex_owned(SD_MUTEX(un)));
13574 	xp = SD_GET_XBUF(bp);
13575 	ASSERT(xp != NULL);
13576 	ASSERT(errcode != 0);
13577 
13578 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13579 	    "sd_return_failed_command_no_restart: entry\n");
13580 
13581 	/*
13582 	 * b_resid could already be nonzero due to a partial data
13583 	 * transfer, so do not change it here.
13584 	 */
13585 	SD_BIOERROR(bp, errcode);
13586 
13587 	/*
13588 	 * If this is the failfast bp, clear it. This can happen if the
13589 	 * failfast bp encounterd a fatal error when we attempted to
13590 	 * re-try it (such as a scsi_transport(9F) failure).  However
13591 	 * we should NOT be in an active failfast state if the failfast
13592 	 * bp is not NULL.
13593 	 */
13594 	if (bp == un->un_failfast_bp) {
13595 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13596 		un->un_failfast_bp = NULL;
13597 	}
13598 
13599 	if (bp == un->un_retry_bp) {
13600 		/*
13601 		 * This command was retried one or more times. Show that we are
13602 		 * done with it, and allow processing of the waitq to resume.
13603 		 */
13604 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13605 		    "sd_return_failed_command_no_restart: "
13606 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13607 		un->un_retry_bp = NULL;
13608 		un->un_retry_statp = NULL;
13609 	}
13610 
13611 	SD_UPDATE_RDWR_STATS(un, bp);
13612 	SD_UPDATE_PARTITION_STATS(un, bp);
13613 
13614 	mutex_exit(SD_MUTEX(un));
13615 
13616 	if (xp->xb_pktp != NULL) {
13617 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13618 		xp->xb_pktp = NULL;
13619 	}
13620 
13621 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13622 
13623 	mutex_enter(SD_MUTEX(un));
13624 
13625 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13626 	    "sd_return_failed_command_no_restart: exit\n");
13627 }
13628 
13629 
13630 /*
13631  *    Function: sd_retry_command
13632  *
13633  * Description: queue up a command for retry, or (optionally) fail it
13634  *		if retry counts are exhausted.
13635  *
13636  *   Arguments: un - Pointer to the sd_lun struct for the target.
13637  *
13638  *		bp - Pointer to the buf for the command to be retried.
13639  *
13640  *		retry_check_flag - Flag to see which (if any) of the retry
13641  *		   counts should be decremented/checked. If the indicated
13642  *		   retry count is exhausted, then the command will not be
13643  *		   retried; it will be failed instead. This should use a
13644  *		   value equal to one of the following:
13645  *
13646  *			SD_RETRIES_NOCHECK
13647  *			SD_RESD_RETRIES_STANDARD
13648  *			SD_RETRIES_VICTIM
13649  *
13650  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
13651  *		   if the check should be made to see of FLAG_ISOLATE is set
13652  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
13653  *		   not retried, it is simply failed.
13654  *
13655  *		user_funcp - Ptr to function to call before dispatching the
13656  *		   command. May be NULL if no action needs to be performed.
13657  *		   (Primarily intended for printing messages.)
13658  *
13659  *		user_arg - Optional argument to be passed along to
13660  *		   the user_funcp call.
13661  *
13662  *		failure_code - errno return code to set in the bp if the
13663  *		   command is going to be failed.
13664  *
13665  *		retry_delay - Retry delay interval in (clock_t) units. May
13666  *		   be zero which indicates that the retry should be retried
13667  *		   immediately (ie, without an intervening delay).
13668  *
13669  *		statp - Ptr to kstat function to be updated if the command
13670  *		   is queued for a delayed retry. May be NULL if no kstat
13671  *		   update is desired.
13672  *
13673  *     Context: May be called from interrupt context.
13674  */
13675 
13676 static void
13677 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
13678 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int
13679 	code), void *user_arg, int failure_code,  clock_t retry_delay,
13680 	void (*statp)(kstat_io_t *))
13681 {
13682 	struct sd_xbuf	*xp;
13683 	struct scsi_pkt	*pktp;
13684 
13685 	ASSERT(un != NULL);
13686 	ASSERT(mutex_owned(SD_MUTEX(un)));
13687 	ASSERT(bp != NULL);
13688 	xp = SD_GET_XBUF(bp);
13689 	ASSERT(xp != NULL);
13690 	pktp = SD_GET_PKTP(bp);
13691 	ASSERT(pktp != NULL);
13692 
13693 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
13694 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
13695 
13696 	/*
13697 	 * If we are syncing or dumping, fail the command to avoid
13698 	 * recursively calling back into scsi_transport().
13699 	 */
13700 	if (ddi_in_panic()) {
13701 		goto fail_command_no_log;
13702 	}
13703 
13704 	/*
13705 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
13706 	 * log an error and fail the command.
13707 	 */
13708 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
13709 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
13710 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
13711 		sd_dump_memory(un, SD_LOG_IO, "CDB",
13712 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
13713 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
13714 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
13715 		goto fail_command;
13716 	}
13717 
13718 	/*
13719 	 * If we are suspended, then put the command onto head of the
13720 	 * wait queue since we don't want to start more commands, and
13721 	 * clear the un_retry_bp. Next time when we are resumed, will
13722 	 * handle the command in the wait queue.
13723 	 */
13724 	switch (un->un_state) {
13725 	case SD_STATE_SUSPENDED:
13726 	case SD_STATE_DUMPING:
13727 		bp->av_forw = un->un_waitq_headp;
13728 		un->un_waitq_headp = bp;
13729 		if (un->un_waitq_tailp == NULL) {
13730 			un->un_waitq_tailp = bp;
13731 		}
13732 		if (bp == un->un_retry_bp) {
13733 			un->un_retry_bp = NULL;
13734 			un->un_retry_statp = NULL;
13735 		}
13736 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13737 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
13738 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
13739 		return;
13740 	default:
13741 		break;
13742 	}
13743 
13744 	/*
13745 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
13746 	 * is set; if it is then we do not want to retry the command.
13747 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
13748 	 */
13749 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
13750 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
13751 			goto fail_command;
13752 		}
13753 	}
13754 
13755 
13756 	/*
13757 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
13758 	 * command timeout or a selection timeout has occurred. This means
13759 	 * that we were unable to establish an kind of communication with
13760 	 * the target, and subsequent retries and/or commands are likely
13761 	 * to encounter similar results and take a long time to complete.
13762 	 *
13763 	 * If this is a failfast error condition, we need to update the
13764 	 * failfast state, even if this bp does not have B_FAILFAST set.
13765 	 */
13766 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
13767 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
13768 			ASSERT(un->un_failfast_bp == NULL);
13769 			/*
13770 			 * If we are already in the active failfast state, and
13771 			 * another failfast error condition has been detected,
13772 			 * then fail this command if it has B_FAILFAST set.
13773 			 * If B_FAILFAST is clear, then maintain the legacy
13774 			 * behavior of retrying heroically, even tho this will
13775 			 * take a lot more time to fail the command.
13776 			 */
13777 			if (bp->b_flags & B_FAILFAST) {
13778 				goto fail_command;
13779 			}
13780 		} else {
13781 			/*
13782 			 * We're not in the active failfast state, but we
13783 			 * have a failfast error condition, so we must begin
13784 			 * transition to the next state. We do this regardless
13785 			 * of whether or not this bp has B_FAILFAST set.
13786 			 */
13787 			if (un->un_failfast_bp == NULL) {
13788 				/*
13789 				 * This is the first bp to meet a failfast
13790 				 * condition so save it on un_failfast_bp &
13791 				 * do normal retry processing. Do not enter
13792 				 * active failfast state yet. This marks
13793 				 * entry into the "failfast pending" state.
13794 				 */
13795 				un->un_failfast_bp = bp;
13796 
13797 			} else if (un->un_failfast_bp == bp) {
13798 				/*
13799 				 * This is the second time *this* bp has
13800 				 * encountered a failfast error condition,
13801 				 * so enter active failfast state & flush
13802 				 * queues as appropriate.
13803 				 */
13804 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
13805 				un->un_failfast_bp = NULL;
13806 				sd_failfast_flushq(un);
13807 
13808 				/*
13809 				 * Fail this bp now if B_FAILFAST set;
13810 				 * otherwise continue with retries. (It would
13811 				 * be pretty ironic if this bp succeeded on a
13812 				 * subsequent retry after we just flushed all
13813 				 * the queues).
13814 				 */
13815 				if (bp->b_flags & B_FAILFAST) {
13816 					goto fail_command;
13817 				}
13818 
13819 #if !defined(lint) && !defined(__lint)
13820 			} else {
13821 				/*
13822 				 * If neither of the preceeding conditionals
13823 				 * was true, it means that there is some
13824 				 * *other* bp that has met an inital failfast
13825 				 * condition and is currently either being
13826 				 * retried or is waiting to be retried. In
13827 				 * that case we should perform normal retry
13828 				 * processing on *this* bp, since there is a
13829 				 * chance that the current failfast condition
13830 				 * is transient and recoverable. If that does
13831 				 * not turn out to be the case, then retries
13832 				 * will be cleared when the wait queue is
13833 				 * flushed anyway.
13834 				 */
13835 #endif
13836 			}
13837 		}
13838 	} else {
13839 		/*
13840 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
13841 		 * likely were able to at least establish some level of
13842 		 * communication with the target and subsequent commands
13843 		 * and/or retries are likely to get through to the target,
13844 		 * In this case we want to be aggressive about clearing
13845 		 * the failfast state. Note that this does not affect
13846 		 * the "failfast pending" condition.
13847 		 */
13848 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13849 	}
13850 
13851 
13852 	/*
13853 	 * Check the specified retry count to see if we can still do
13854 	 * any retries with this pkt before we should fail it.
13855 	 */
13856 	switch (retry_check_flag & SD_RETRIES_MASK) {
13857 	case SD_RETRIES_VICTIM:
13858 		/*
13859 		 * Check the victim retry count. If exhausted, then fall
13860 		 * thru & check against the standard retry count.
13861 		 */
13862 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
13863 			/* Increment count & proceed with the retry */
13864 			xp->xb_victim_retry_count++;
13865 			break;
13866 		}
13867 		/* Victim retries exhausted, fall back to std. retries... */
13868 		/* FALLTHRU */
13869 
13870 	case SD_RETRIES_STANDARD:
13871 		if (xp->xb_retry_count >= un->un_retry_count) {
13872 			/* Retries exhausted, fail the command */
13873 			SD_TRACE(SD_LOG_IO_CORE, un,
13874 			    "sd_retry_command: retries exhausted!\n");
13875 			/*
13876 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
13877 			 * commands with nonzero pkt_resid.
13878 			 */
13879 			if ((pktp->pkt_reason == CMD_CMPLT) &&
13880 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
13881 			    (pktp->pkt_resid != 0)) {
13882 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
13883 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
13884 					SD_UPDATE_B_RESID(bp, pktp);
13885 				}
13886 			}
13887 			goto fail_command;
13888 		}
13889 		xp->xb_retry_count++;
13890 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13891 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13892 		break;
13893 
13894 	case SD_RETRIES_UA:
13895 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
13896 			/* Retries exhausted, fail the command */
13897 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13898 			    "Unit Attention retries exhausted. "
13899 			    "Check the target.\n");
13900 			goto fail_command;
13901 		}
13902 		xp->xb_ua_retry_count++;
13903 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13904 		    "sd_retry_command: retry count:%d\n",
13905 		    xp->xb_ua_retry_count);
13906 		break;
13907 
13908 	case SD_RETRIES_BUSY:
13909 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
13910 			/* Retries exhausted, fail the command */
13911 			SD_TRACE(SD_LOG_IO_CORE, un,
13912 			    "sd_retry_command: retries exhausted!\n");
13913 			goto fail_command;
13914 		}
13915 		xp->xb_retry_count++;
13916 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13917 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13918 		break;
13919 
13920 	case SD_RETRIES_NOCHECK:
13921 	default:
13922 		/* No retry count to check. Just proceed with the retry */
13923 		break;
13924 	}
13925 
13926 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13927 
13928 	/*
13929 	 * If we were given a zero timeout, we must attempt to retry the
13930 	 * command immediately (ie, without a delay).
13931 	 */
13932 	if (retry_delay == 0) {
13933 		/*
13934 		 * Check some limiting conditions to see if we can actually
13935 		 * do the immediate retry.  If we cannot, then we must
13936 		 * fall back to queueing up a delayed retry.
13937 		 */
13938 		if (un->un_ncmds_in_transport >= un->un_throttle) {
13939 			/*
13940 			 * We are at the throttle limit for the target,
13941 			 * fall back to delayed retry.
13942 			 */
13943 			retry_delay = SD_BSY_TIMEOUT;
13944 			statp = kstat_waitq_enter;
13945 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13946 			    "sd_retry_command: immed. retry hit "
13947 			    "throttle!\n");
13948 		} else {
13949 			/*
13950 			 * We're clear to proceed with the immediate retry.
13951 			 * First call the user-provided function (if any)
13952 			 */
13953 			if (user_funcp != NULL) {
13954 				(*user_funcp)(un, bp, user_arg,
13955 				    SD_IMMEDIATE_RETRY_ISSUED);
13956 #ifdef __lock_lint
13957 				sd_print_incomplete_msg(un, bp, user_arg,
13958 				    SD_IMMEDIATE_RETRY_ISSUED);
13959 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
13960 				    SD_IMMEDIATE_RETRY_ISSUED);
13961 				sd_print_sense_failed_msg(un, bp, user_arg,
13962 				    SD_IMMEDIATE_RETRY_ISSUED);
13963 #endif
13964 			}
13965 
13966 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13967 			    "sd_retry_command: issuing immediate retry\n");
13968 
13969 			/*
13970 			 * Call sd_start_cmds() to transport the command to
13971 			 * the target.
13972 			 */
13973 			sd_start_cmds(un, bp);
13974 
13975 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13976 			    "sd_retry_command exit\n");
13977 			return;
13978 		}
13979 	}
13980 
13981 	/*
13982 	 * Set up to retry the command after a delay.
13983 	 * First call the user-provided function (if any)
13984 	 */
13985 	if (user_funcp != NULL) {
13986 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
13987 	}
13988 
13989 	sd_set_retry_bp(un, bp, retry_delay, statp);
13990 
13991 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
13992 	return;
13993 
13994 fail_command:
13995 
13996 	if (user_funcp != NULL) {
13997 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
13998 	}
13999 
14000 fail_command_no_log:
14001 
14002 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14003 	    "sd_retry_command: returning failed command\n");
14004 
14005 	sd_return_failed_command(un, bp, failure_code);
14006 
14007 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
14008 }
14009 
14010 
14011 /*
14012  *    Function: sd_set_retry_bp
14013  *
14014  * Description: Set up the given bp for retry.
14015  *
14016  *   Arguments: un - ptr to associated softstate
14017  *		bp - ptr to buf(9S) for the command
14018  *		retry_delay - time interval before issuing retry (may be 0)
14019  *		statp - optional pointer to kstat function
14020  *
14021  *     Context: May be called under interrupt context
14022  */
14023 
14024 static void
14025 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
14026 	void (*statp)(kstat_io_t *))
14027 {
14028 	ASSERT(un != NULL);
14029 	ASSERT(mutex_owned(SD_MUTEX(un)));
14030 	ASSERT(bp != NULL);
14031 
14032 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14033 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
14034 
14035 	/*
14036 	 * Indicate that the command is being retried. This will not allow any
14037 	 * other commands on the wait queue to be transported to the target
14038 	 * until this command has been completed (success or failure). The
14039 	 * "retry command" is not transported to the target until the given
14040 	 * time delay expires, unless the user specified a 0 retry_delay.
14041 	 *
14042 	 * Note: the timeout(9F) callback routine is what actually calls
14043 	 * sd_start_cmds() to transport the command, with the exception of a
14044 	 * zero retry_delay. The only current implementor of a zero retry delay
14045 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
14046 	 */
14047 	if (un->un_retry_bp == NULL) {
14048 		ASSERT(un->un_retry_statp == NULL);
14049 		un->un_retry_bp = bp;
14050 
14051 		/*
14052 		 * If the user has not specified a delay the command should
14053 		 * be queued and no timeout should be scheduled.
14054 		 */
14055 		if (retry_delay == 0) {
14056 			/*
14057 			 * Save the kstat pointer that will be used in the
14058 			 * call to SD_UPDATE_KSTATS() below, so that
14059 			 * sd_start_cmds() can correctly decrement the waitq
14060 			 * count when it is time to transport this command.
14061 			 */
14062 			un->un_retry_statp = statp;
14063 			goto done;
14064 		}
14065 	}
14066 
14067 	if (un->un_retry_bp == bp) {
14068 		/*
14069 		 * Save the kstat pointer that will be used in the call to
14070 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
14071 		 * correctly decrement the waitq count when it is time to
14072 		 * transport this command.
14073 		 */
14074 		un->un_retry_statp = statp;
14075 
14076 		/*
14077 		 * Schedule a timeout if:
14078 		 *   1) The user has specified a delay.
14079 		 *   2) There is not a START_STOP_UNIT callback pending.
14080 		 *
14081 		 * If no delay has been specified, then it is up to the caller
14082 		 * to ensure that IO processing continues without stalling.
14083 		 * Effectively, this means that the caller will issue the
14084 		 * required call to sd_start_cmds(). The START_STOP_UNIT
14085 		 * callback does this after the START STOP UNIT command has
14086 		 * completed. In either of these cases we should not schedule
14087 		 * a timeout callback here.  Also don't schedule the timeout if
14088 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
14089 		 */
14090 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
14091 		    (un->un_direct_priority_timeid == NULL)) {
14092 			un->un_retry_timeid =
14093 			    timeout(sd_start_retry_command, un, retry_delay);
14094 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14095 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
14096 			    " bp:0x%p un_retry_timeid:0x%p\n",
14097 			    un, bp, un->un_retry_timeid);
14098 		}
14099 	} else {
14100 		/*
14101 		 * We only get in here if there is already another command
14102 		 * waiting to be retried.  In this case, we just put the
14103 		 * given command onto the wait queue, so it can be transported
14104 		 * after the current retry command has completed.
14105 		 *
14106 		 * Also we have to make sure that if the command at the head
14107 		 * of the wait queue is the un_failfast_bp, that we do not
14108 		 * put ahead of it any other commands that are to be retried.
14109 		 */
14110 		if ((un->un_failfast_bp != NULL) &&
14111 		    (un->un_failfast_bp == un->un_waitq_headp)) {
14112 			/*
14113 			 * Enqueue this command AFTER the first command on
14114 			 * the wait queue (which is also un_failfast_bp).
14115 			 */
14116 			bp->av_forw = un->un_waitq_headp->av_forw;
14117 			un->un_waitq_headp->av_forw = bp;
14118 			if (un->un_waitq_headp == un->un_waitq_tailp) {
14119 				un->un_waitq_tailp = bp;
14120 			}
14121 		} else {
14122 			/* Enqueue this command at the head of the waitq. */
14123 			bp->av_forw = un->un_waitq_headp;
14124 			un->un_waitq_headp = bp;
14125 			if (un->un_waitq_tailp == NULL) {
14126 				un->un_waitq_tailp = bp;
14127 			}
14128 		}
14129 
14130 		if (statp == NULL) {
14131 			statp = kstat_waitq_enter;
14132 		}
14133 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14134 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
14135 	}
14136 
14137 done:
14138 	if (statp != NULL) {
14139 		SD_UPDATE_KSTATS(un, statp, bp);
14140 	}
14141 
14142 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14143 	    "sd_set_retry_bp: exit un:0x%p\n", un);
14144 }
14145 
14146 
14147 /*
14148  *    Function: sd_start_retry_command
14149  *
14150  * Description: Start the command that has been waiting on the target's
14151  *		retry queue.  Called from timeout(9F) context after the
14152  *		retry delay interval has expired.
14153  *
14154  *   Arguments: arg - pointer to associated softstate for the device.
14155  *
14156  *     Context: timeout(9F) thread context.  May not sleep.
14157  */
14158 
14159 static void
14160 sd_start_retry_command(void *arg)
14161 {
14162 	struct sd_lun *un = arg;
14163 
14164 	ASSERT(un != NULL);
14165 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14166 
14167 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14168 	    "sd_start_retry_command: entry\n");
14169 
14170 	mutex_enter(SD_MUTEX(un));
14171 
14172 	un->un_retry_timeid = NULL;
14173 
14174 	if (un->un_retry_bp != NULL) {
14175 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14176 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
14177 		    un, un->un_retry_bp);
14178 		sd_start_cmds(un, un->un_retry_bp);
14179 	}
14180 
14181 	mutex_exit(SD_MUTEX(un));
14182 
14183 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14184 	    "sd_start_retry_command: exit\n");
14185 }
14186 
14187 
14188 /*
14189  *    Function: sd_start_direct_priority_command
14190  *
14191  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
14192  *		received TRAN_BUSY when we called scsi_transport() to send it
14193  *		to the underlying HBA. This function is called from timeout(9F)
14194  *		context after the delay interval has expired.
14195  *
14196  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
14197  *
14198  *     Context: timeout(9F) thread context.  May not sleep.
14199  */
14200 
14201 static void
14202 sd_start_direct_priority_command(void *arg)
14203 {
14204 	struct buf	*priority_bp = arg;
14205 	struct sd_lun	*un;
14206 
14207 	ASSERT(priority_bp != NULL);
14208 	un = SD_GET_UN(priority_bp);
14209 	ASSERT(un != NULL);
14210 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14211 
14212 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14213 	    "sd_start_direct_priority_command: entry\n");
14214 
14215 	mutex_enter(SD_MUTEX(un));
14216 	un->un_direct_priority_timeid = NULL;
14217 	sd_start_cmds(un, priority_bp);
14218 	mutex_exit(SD_MUTEX(un));
14219 
14220 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14221 	    "sd_start_direct_priority_command: exit\n");
14222 }
14223 
14224 
14225 /*
14226  *    Function: sd_send_request_sense_command
14227  *
14228  * Description: Sends a REQUEST SENSE command to the target
14229  *
14230  *     Context: May be called from interrupt context.
14231  */
14232 
14233 static void
14234 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
14235 	struct scsi_pkt *pktp)
14236 {
14237 	ASSERT(bp != NULL);
14238 	ASSERT(un != NULL);
14239 	ASSERT(mutex_owned(SD_MUTEX(un)));
14240 
14241 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
14242 	    "entry: buf:0x%p\n", bp);
14243 
14244 	/*
14245 	 * If we are syncing or dumping, then fail the command to avoid a
14246 	 * recursive callback into scsi_transport(). Also fail the command
14247 	 * if we are suspended (legacy behavior).
14248 	 */
14249 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
14250 	    (un->un_state == SD_STATE_DUMPING)) {
14251 		sd_return_failed_command(un, bp, EIO);
14252 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14253 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
14254 		return;
14255 	}
14256 
14257 	/*
14258 	 * Retry the failed command and don't issue the request sense if:
14259 	 *    1) the sense buf is busy
14260 	 *    2) we have 1 or more outstanding commands on the target
14261 	 *    (the sense data will be cleared or invalidated any way)
14262 	 *
14263 	 * Note: There could be an issue with not checking a retry limit here,
14264 	 * the problem is determining which retry limit to check.
14265 	 */
14266 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
14267 		/* Don't retry if the command is flagged as non-retryable */
14268 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
14269 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
14270 			    NULL, NULL, 0, SD_BSY_TIMEOUT, kstat_waitq_enter);
14271 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14272 			    "sd_send_request_sense_command: "
14273 			    "at full throttle, retrying exit\n");
14274 		} else {
14275 			sd_return_failed_command(un, bp, EIO);
14276 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14277 			    "sd_send_request_sense_command: "
14278 			    "at full throttle, non-retryable exit\n");
14279 		}
14280 		return;
14281 	}
14282 
14283 	sd_mark_rqs_busy(un, bp);
14284 	sd_start_cmds(un, un->un_rqs_bp);
14285 
14286 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14287 	    "sd_send_request_sense_command: exit\n");
14288 }
14289 
14290 
14291 /*
14292  *    Function: sd_mark_rqs_busy
14293  *
14294  * Description: Indicate that the request sense bp for this instance is
14295  *		in use.
14296  *
14297  *     Context: May be called under interrupt context
14298  */
14299 
14300 static void
14301 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
14302 {
14303 	struct sd_xbuf	*sense_xp;
14304 
14305 	ASSERT(un != NULL);
14306 	ASSERT(bp != NULL);
14307 	ASSERT(mutex_owned(SD_MUTEX(un)));
14308 	ASSERT(un->un_sense_isbusy == 0);
14309 
14310 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
14311 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
14312 
14313 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
14314 	ASSERT(sense_xp != NULL);
14315 
14316 	SD_INFO(SD_LOG_IO, un,
14317 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
14318 
14319 	ASSERT(sense_xp->xb_pktp != NULL);
14320 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
14321 	    == (FLAG_SENSING | FLAG_HEAD));
14322 
14323 	un->un_sense_isbusy = 1;
14324 	un->un_rqs_bp->b_resid = 0;
14325 	sense_xp->xb_pktp->pkt_resid  = 0;
14326 	sense_xp->xb_pktp->pkt_reason = 0;
14327 
14328 	/* So we can get back the bp at interrupt time! */
14329 	sense_xp->xb_sense_bp = bp;
14330 
14331 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
14332 
14333 	/*
14334 	 * Mark this buf as awaiting sense data. (This is already set in
14335 	 * the pkt_flags for the RQS packet.)
14336 	 */
14337 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
14338 
14339 	sense_xp->xb_retry_count	= 0;
14340 	sense_xp->xb_victim_retry_count = 0;
14341 	sense_xp->xb_ua_retry_count	= 0;
14342 	sense_xp->xb_nr_retry_count 	= 0;
14343 	sense_xp->xb_dma_resid  = 0;
14344 
14345 	/* Clean up the fields for auto-request sense */
14346 	sense_xp->xb_sense_status = 0;
14347 	sense_xp->xb_sense_state  = 0;
14348 	sense_xp->xb_sense_resid  = 0;
14349 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
14350 
14351 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
14352 }
14353 
14354 
14355 /*
14356  *    Function: sd_mark_rqs_idle
14357  *
14358  * Description: SD_MUTEX must be held continuously through this routine
14359  *		to prevent reuse of the rqs struct before the caller can
14360  *		complete it's processing.
14361  *
14362  * Return Code: Pointer to the RQS buf
14363  *
14364  *     Context: May be called under interrupt context
14365  */
14366 
14367 static struct buf *
14368 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
14369 {
14370 	struct buf *bp;
14371 	ASSERT(un != NULL);
14372 	ASSERT(sense_xp != NULL);
14373 	ASSERT(mutex_owned(SD_MUTEX(un)));
14374 	ASSERT(un->un_sense_isbusy != 0);
14375 
14376 	un->un_sense_isbusy = 0;
14377 	bp = sense_xp->xb_sense_bp;
14378 	sense_xp->xb_sense_bp = NULL;
14379 
14380 	/* This pkt is no longer interested in getting sense data */
14381 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
14382 
14383 	return (bp);
14384 }
14385 
14386 
14387 
14388 /*
14389  *    Function: sd_alloc_rqs
14390  *
14391  * Description: Set up the unit to receive auto request sense data
14392  *
14393  * Return Code: DDI_SUCCESS or DDI_FAILURE
14394  *
14395  *     Context: Called under attach(9E) context
14396  */
14397 
14398 static int
14399 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
14400 {
14401 	struct sd_xbuf *xp;
14402 
14403 	ASSERT(un != NULL);
14404 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14405 	ASSERT(un->un_rqs_bp == NULL);
14406 	ASSERT(un->un_rqs_pktp == NULL);
14407 
14408 	/*
14409 	 * First allocate the required buf and scsi_pkt structs, then set up
14410 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
14411 	 */
14412 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
14413 	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
14414 	if (un->un_rqs_bp == NULL) {
14415 		return (DDI_FAILURE);
14416 	}
14417 
14418 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
14419 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
14420 
14421 	if (un->un_rqs_pktp == NULL) {
14422 		sd_free_rqs(un);
14423 		return (DDI_FAILURE);
14424 	}
14425 
14426 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
14427 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
14428 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
14429 
14430 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
14431 
14432 	/* Set up the other needed members in the ARQ scsi_pkt. */
14433 	un->un_rqs_pktp->pkt_comp   = sdintr;
14434 	un->un_rqs_pktp->pkt_time   = sd_io_time;
14435 	un->un_rqs_pktp->pkt_flags |=
14436 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
14437 
14438 	/*
14439 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
14440 	 * provide any intpkt, destroypkt routines as we take care of
14441 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
14442 	 */
14443 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14444 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
14445 	xp->xb_pktp = un->un_rqs_pktp;
14446 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
14447 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
14448 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
14449 
14450 	/*
14451 	 * Save the pointer to the request sense private bp so it can
14452 	 * be retrieved in sdintr.
14453 	 */
14454 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
14455 	ASSERT(un->un_rqs_bp->b_private == xp);
14456 
14457 	/*
14458 	 * See if the HBA supports auto-request sense for the specified
14459 	 * target/lun. If it does, then try to enable it (if not already
14460 	 * enabled).
14461 	 *
14462 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
14463 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
14464 	 * return success.  However, in both of these cases ARQ is always
14465 	 * enabled and scsi_ifgetcap will always return true. The best approach
14466 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
14467 	 *
14468 	 * The 3rd case is the HBA (adp) always return enabled on
14469 	 * scsi_ifgetgetcap even when it's not enable, the best approach
14470 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
14471 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
14472 	 */
14473 
14474 	if (un->un_f_is_fibre == TRUE) {
14475 		un->un_f_arq_enabled = TRUE;
14476 	} else {
14477 #if defined(__i386) || defined(__amd64)
14478 		/*
14479 		 * Circumvent the Adaptec bug, remove this code when
14480 		 * the bug is fixed
14481 		 */
14482 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
14483 #endif
14484 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
14485 		case 0:
14486 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14487 			    "sd_alloc_rqs: HBA supports ARQ\n");
14488 			/*
14489 			 * ARQ is supported by this HBA but currently is not
14490 			 * enabled. Attempt to enable it and if successful then
14491 			 * mark this instance as ARQ enabled.
14492 			 */
14493 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
14494 			    == 1) {
14495 				/* Successfully enabled ARQ in the HBA */
14496 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14497 				    "sd_alloc_rqs: ARQ enabled\n");
14498 				un->un_f_arq_enabled = TRUE;
14499 			} else {
14500 				/* Could not enable ARQ in the HBA */
14501 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14502 				    "sd_alloc_rqs: failed ARQ enable\n");
14503 				un->un_f_arq_enabled = FALSE;
14504 			}
14505 			break;
14506 		case 1:
14507 			/*
14508 			 * ARQ is supported by this HBA and is already enabled.
14509 			 * Just mark ARQ as enabled for this instance.
14510 			 */
14511 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14512 			    "sd_alloc_rqs: ARQ already enabled\n");
14513 			un->un_f_arq_enabled = TRUE;
14514 			break;
14515 		default:
14516 			/*
14517 			 * ARQ is not supported by this HBA; disable it for this
14518 			 * instance.
14519 			 */
14520 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14521 			    "sd_alloc_rqs: HBA does not support ARQ\n");
14522 			un->un_f_arq_enabled = FALSE;
14523 			break;
14524 		}
14525 	}
14526 
14527 	return (DDI_SUCCESS);
14528 }
14529 
14530 
14531 /*
14532  *    Function: sd_free_rqs
14533  *
14534  * Description: Cleanup for the pre-instance RQS command.
14535  *
14536  *     Context: Kernel thread context
14537  */
14538 
14539 static void
14540 sd_free_rqs(struct sd_lun *un)
14541 {
14542 	ASSERT(un != NULL);
14543 
14544 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
14545 
14546 	/*
14547 	 * If consistent memory is bound to a scsi_pkt, the pkt
14548 	 * has to be destroyed *before* freeing the consistent memory.
14549 	 * Don't change the sequence of this operations.
14550 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
14551 	 * after it was freed in scsi_free_consistent_buf().
14552 	 */
14553 	if (un->un_rqs_pktp != NULL) {
14554 		scsi_destroy_pkt(un->un_rqs_pktp);
14555 		un->un_rqs_pktp = NULL;
14556 	}
14557 
14558 	if (un->un_rqs_bp != NULL) {
14559 		kmem_free(SD_GET_XBUF(un->un_rqs_bp), sizeof (struct sd_xbuf));
14560 		scsi_free_consistent_buf(un->un_rqs_bp);
14561 		un->un_rqs_bp = NULL;
14562 	}
14563 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
14564 }
14565 
14566 
14567 
14568 /*
14569  *    Function: sd_reduce_throttle
14570  *
14571  * Description: Reduces the maximum # of outstanding commands on a
14572  *		target to the current number of outstanding commands.
14573  *		Queues a tiemout(9F) callback to restore the limit
14574  *		after a specified interval has elapsed.
14575  *		Typically used when we get a TRAN_BUSY return code
14576  *		back from scsi_transport().
14577  *
14578  *   Arguments: un - ptr to the sd_lun softstate struct
14579  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
14580  *
14581  *     Context: May be called from interrupt context
14582  */
14583 
14584 static void
14585 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
14586 {
14587 	ASSERT(un != NULL);
14588 	ASSERT(mutex_owned(SD_MUTEX(un)));
14589 	ASSERT(un->un_ncmds_in_transport >= 0);
14590 
14591 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14592 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
14593 	    un, un->un_throttle, un->un_ncmds_in_transport);
14594 
14595 	if (un->un_throttle > 1) {
14596 		if (un->un_f_use_adaptive_throttle == TRUE) {
14597 			switch (throttle_type) {
14598 			case SD_THROTTLE_TRAN_BUSY:
14599 				if (un->un_busy_throttle == 0) {
14600 					un->un_busy_throttle = un->un_throttle;
14601 				}
14602 				break;
14603 			case SD_THROTTLE_QFULL:
14604 				un->un_busy_throttle = 0;
14605 				break;
14606 			default:
14607 				ASSERT(FALSE);
14608 			}
14609 
14610 			if (un->un_ncmds_in_transport > 0) {
14611 				un->un_throttle = un->un_ncmds_in_transport;
14612 			}
14613 
14614 		} else {
14615 			if (un->un_ncmds_in_transport == 0) {
14616 				un->un_throttle = 1;
14617 			} else {
14618 				un->un_throttle = un->un_ncmds_in_transport;
14619 			}
14620 		}
14621 	}
14622 
14623 	/* Reschedule the timeout if none is currently active */
14624 	if (un->un_reset_throttle_timeid == NULL) {
14625 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
14626 		    un, SD_THROTTLE_RESET_INTERVAL);
14627 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14628 		    "sd_reduce_throttle: timeout scheduled!\n");
14629 	}
14630 
14631 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14632 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14633 }
14634 
14635 
14636 
14637 /*
14638  *    Function: sd_restore_throttle
14639  *
14640  * Description: Callback function for timeout(9F).  Resets the current
14641  *		value of un->un_throttle to its default.
14642  *
14643  *   Arguments: arg - pointer to associated softstate for the device.
14644  *
14645  *     Context: May be called from interrupt context
14646  */
14647 
14648 static void
14649 sd_restore_throttle(void *arg)
14650 {
14651 	struct sd_lun	*un = arg;
14652 
14653 	ASSERT(un != NULL);
14654 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14655 
14656 	mutex_enter(SD_MUTEX(un));
14657 
14658 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14659 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14660 
14661 	un->un_reset_throttle_timeid = NULL;
14662 
14663 	if (un->un_f_use_adaptive_throttle == TRUE) {
14664 		/*
14665 		 * If un_busy_throttle is nonzero, then it contains the
14666 		 * value that un_throttle was when we got a TRAN_BUSY back
14667 		 * from scsi_transport(). We want to revert back to this
14668 		 * value.
14669 		 *
14670 		 * In the QFULL case, the throttle limit will incrementally
14671 		 * increase until it reaches max throttle.
14672 		 */
14673 		if (un->un_busy_throttle > 0) {
14674 			un->un_throttle = un->un_busy_throttle;
14675 			un->un_busy_throttle = 0;
14676 		} else {
14677 			/*
14678 			 * increase throttle by 10% open gate slowly, schedule
14679 			 * another restore if saved throttle has not been
14680 			 * reached
14681 			 */
14682 			short throttle;
14683 			if (sd_qfull_throttle_enable) {
14684 				throttle = un->un_throttle +
14685 				    max((un->un_throttle / 10), 1);
14686 				un->un_throttle =
14687 				    (throttle < un->un_saved_throttle) ?
14688 				    throttle : un->un_saved_throttle;
14689 				if (un->un_throttle < un->un_saved_throttle) {
14690 					un->un_reset_throttle_timeid =
14691 					    timeout(sd_restore_throttle,
14692 					    un,
14693 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
14694 				}
14695 			}
14696 		}
14697 
14698 		/*
14699 		 * If un_throttle has fallen below the low-water mark, we
14700 		 * restore the maximum value here (and allow it to ratchet
14701 		 * down again if necessary).
14702 		 */
14703 		if (un->un_throttle < un->un_min_throttle) {
14704 			un->un_throttle = un->un_saved_throttle;
14705 		}
14706 	} else {
14707 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14708 		    "restoring limit from 0x%x to 0x%x\n",
14709 		    un->un_throttle, un->un_saved_throttle);
14710 		un->un_throttle = un->un_saved_throttle;
14711 	}
14712 
14713 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14714 	    "sd_restore_throttle: calling sd_start_cmds!\n");
14715 
14716 	sd_start_cmds(un, NULL);
14717 
14718 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14719 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
14720 	    un, un->un_throttle);
14721 
14722 	mutex_exit(SD_MUTEX(un));
14723 
14724 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
14725 }
14726 
14727 /*
14728  *    Function: sdrunout
14729  *
14730  * Description: Callback routine for scsi_init_pkt when a resource allocation
14731  *		fails.
14732  *
14733  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
14734  *		soft state instance.
14735  *
14736  * Return Code: The scsi_init_pkt routine allows for the callback function to
14737  *		return a 0 indicating the callback should be rescheduled or a 1
14738  *		indicating not to reschedule. This routine always returns 1
14739  *		because the driver always provides a callback function to
14740  *		scsi_init_pkt. This results in a callback always being scheduled
14741  *		(via the scsi_init_pkt callback implementation) if a resource
14742  *		failure occurs.
14743  *
14744  *     Context: This callback function may not block or call routines that block
14745  *
14746  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
14747  *		request persisting at the head of the list which cannot be
14748  *		satisfied even after multiple retries. In the future the driver
14749  *		may implement some time of maximum runout count before failing
14750  *		an I/O.
14751  */
14752 
14753 static int
14754 sdrunout(caddr_t arg)
14755 {
14756 	struct sd_lun	*un = (struct sd_lun *)arg;
14757 
14758 	ASSERT(un != NULL);
14759 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14760 
14761 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
14762 
14763 	mutex_enter(SD_MUTEX(un));
14764 	sd_start_cmds(un, NULL);
14765 	mutex_exit(SD_MUTEX(un));
14766 	/*
14767 	 * This callback routine always returns 1 (i.e. do not reschedule)
14768 	 * because we always specify sdrunout as the callback handler for
14769 	 * scsi_init_pkt inside the call to sd_start_cmds.
14770 	 */
14771 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
14772 	return (1);
14773 }
14774 
14775 
14776 /*
14777  *    Function: sdintr
14778  *
14779  * Description: Completion callback routine for scsi_pkt(9S) structs
14780  *		sent to the HBA driver via scsi_transport(9F).
14781  *
14782  *     Context: Interrupt context
14783  */
14784 
14785 static void
14786 sdintr(struct scsi_pkt *pktp)
14787 {
14788 	struct buf	*bp;
14789 	struct sd_xbuf	*xp;
14790 	struct sd_lun	*un;
14791 	size_t		actual_len;
14792 
14793 	ASSERT(pktp != NULL);
14794 	bp = (struct buf *)pktp->pkt_private;
14795 	ASSERT(bp != NULL);
14796 	xp = SD_GET_XBUF(bp);
14797 	ASSERT(xp != NULL);
14798 	ASSERT(xp->xb_pktp != NULL);
14799 	un = SD_GET_UN(bp);
14800 	ASSERT(un != NULL);
14801 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14802 
14803 #ifdef SD_FAULT_INJECTION
14804 
14805 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
14806 	/* SD FaultInjection */
14807 	sd_faultinjection(pktp);
14808 
14809 #endif /* SD_FAULT_INJECTION */
14810 
14811 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
14812 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
14813 
14814 	mutex_enter(SD_MUTEX(un));
14815 
14816 	/* Reduce the count of the #commands currently in transport */
14817 	un->un_ncmds_in_transport--;
14818 	ASSERT(un->un_ncmds_in_transport >= 0);
14819 
14820 	/* Increment counter to indicate that the callback routine is active */
14821 	un->un_in_callback++;
14822 
14823 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14824 
14825 #ifdef	SDDEBUG
14826 	if (bp == un->un_retry_bp) {
14827 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
14828 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
14829 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
14830 	}
14831 #endif
14832 
14833 	/*
14834 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
14835 	 * state if needed.
14836 	 */
14837 	if (pktp->pkt_reason == CMD_DEV_GONE) {
14838 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
14839 		    "Device is gone\n");
14840 		if (un->un_mediastate != DKIO_DEV_GONE) {
14841 			un->un_mediastate = DKIO_DEV_GONE;
14842 			cv_broadcast(&un->un_state_cv);
14843 		}
14844 		sd_return_failed_command(un, bp, EIO);
14845 		goto exit;
14846 	}
14847 
14848 	if (pktp->pkt_state & STATE_XARQ_DONE) {
14849 		SD_TRACE(SD_LOG_COMMON, un,
14850 		    "sdintr: extra sense data received. pkt=%p\n", pktp);
14851 	}
14852 
14853 	/*
14854 	 * First see if the pkt has auto-request sense data with it....
14855 	 * Look at the packet state first so we don't take a performance
14856 	 * hit looking at the arq enabled flag unless absolutely necessary.
14857 	 */
14858 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
14859 	    (un->un_f_arq_enabled == TRUE)) {
14860 		/*
14861 		 * The HBA did an auto request sense for this command so check
14862 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
14863 		 * driver command that should not be retried.
14864 		 */
14865 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
14866 			/*
14867 			 * Save the relevant sense info into the xp for the
14868 			 * original cmd.
14869 			 */
14870 			struct scsi_arq_status *asp;
14871 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
14872 			xp->xb_sense_status =
14873 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
14874 			xp->xb_sense_state  = asp->sts_rqpkt_state;
14875 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
14876 			if (pktp->pkt_state & STATE_XARQ_DONE) {
14877 				actual_len = MAX_SENSE_LENGTH -
14878 				    xp->xb_sense_resid;
14879 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
14880 				    MAX_SENSE_LENGTH);
14881 			} else {
14882 				if (xp->xb_sense_resid > SENSE_LENGTH) {
14883 					actual_len = MAX_SENSE_LENGTH -
14884 					    xp->xb_sense_resid;
14885 				} else {
14886 					actual_len = SENSE_LENGTH -
14887 					    xp->xb_sense_resid;
14888 				}
14889 				if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
14890 					xp->xb_sense_resid =
14891 					    (int)(((struct uscsi_cmd *)
14892 					    (xp->xb_pktinfo))->
14893 					    uscsi_rqlen) - actual_len;
14894 				}
14895 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
14896 				    SENSE_LENGTH);
14897 			}
14898 
14899 			/* fail the command */
14900 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14901 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
14902 			sd_return_failed_command(un, bp, EIO);
14903 			goto exit;
14904 		}
14905 
14906 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
14907 		/*
14908 		 * We want to either retry or fail this command, so free
14909 		 * the DMA resources here.  If we retry the command then
14910 		 * the DMA resources will be reallocated in sd_start_cmds().
14911 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
14912 		 * causes the *entire* transfer to start over again from the
14913 		 * beginning of the request, even for PARTIAL chunks that
14914 		 * have already transferred successfully.
14915 		 */
14916 		if ((un->un_f_is_fibre == TRUE) &&
14917 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14918 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
14919 			scsi_dmafree(pktp);
14920 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
14921 		}
14922 #endif
14923 
14924 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14925 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
14926 
14927 		sd_handle_auto_request_sense(un, bp, xp, pktp);
14928 		goto exit;
14929 	}
14930 
14931 	/* Next see if this is the REQUEST SENSE pkt for the instance */
14932 	if (pktp->pkt_flags & FLAG_SENSING)  {
14933 		/* This pktp is from the unit's REQUEST_SENSE command */
14934 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14935 		    "sdintr: sd_handle_request_sense\n");
14936 		sd_handle_request_sense(un, bp, xp, pktp);
14937 		goto exit;
14938 	}
14939 
14940 	/*
14941 	 * Check to see if the command successfully completed as requested;
14942 	 * this is the most common case (and also the hot performance path).
14943 	 *
14944 	 * Requirements for successful completion are:
14945 	 * pkt_reason is CMD_CMPLT and packet status is status good.
14946 	 * In addition:
14947 	 * - A residual of zero indicates successful completion no matter what
14948 	 *   the command is.
14949 	 * - If the residual is not zero and the command is not a read or
14950 	 *   write, then it's still defined as successful completion. In other
14951 	 *   words, if the command is a read or write the residual must be
14952 	 *   zero for successful completion.
14953 	 * - If the residual is not zero and the command is a read or
14954 	 *   write, and it's a USCSICMD, then it's still defined as
14955 	 *   successful completion.
14956 	 */
14957 	if ((pktp->pkt_reason == CMD_CMPLT) &&
14958 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
14959 
14960 		/*
14961 		 * Since this command is returned with a good status, we
14962 		 * can reset the count for Sonoma failover.
14963 		 */
14964 		un->un_sonoma_failure_count = 0;
14965 
14966 		/*
14967 		 * Return all USCSI commands on good status
14968 		 */
14969 		if (pktp->pkt_resid == 0) {
14970 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14971 			    "sdintr: returning command for resid == 0\n");
14972 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
14973 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
14974 			SD_UPDATE_B_RESID(bp, pktp);
14975 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14976 			    "sdintr: returning command for resid != 0\n");
14977 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
14978 			SD_UPDATE_B_RESID(bp, pktp);
14979 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14980 			    "sdintr: returning uscsi command\n");
14981 		} else {
14982 			goto not_successful;
14983 		}
14984 		sd_return_command(un, bp);
14985 
14986 		/*
14987 		 * Decrement counter to indicate that the callback routine
14988 		 * is done.
14989 		 */
14990 		un->un_in_callback--;
14991 		ASSERT(un->un_in_callback >= 0);
14992 		mutex_exit(SD_MUTEX(un));
14993 
14994 		return;
14995 	}
14996 
14997 not_successful:
14998 
14999 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
15000 	/*
15001 	 * The following is based upon knowledge of the underlying transport
15002 	 * and its use of DMA resources.  This code should be removed when
15003 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
15004 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
15005 	 * and sd_start_cmds().
15006 	 *
15007 	 * Free any DMA resources associated with this command if there
15008 	 * is a chance it could be retried or enqueued for later retry.
15009 	 * If we keep the DMA binding then mpxio cannot reissue the
15010 	 * command on another path whenever a path failure occurs.
15011 	 *
15012 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
15013 	 * causes the *entire* transfer to start over again from the
15014 	 * beginning of the request, even for PARTIAL chunks that
15015 	 * have already transferred successfully.
15016 	 *
15017 	 * This is only done for non-uscsi commands (and also skipped for the
15018 	 * driver's internal RQS command). Also just do this for Fibre Channel
15019 	 * devices as these are the only ones that support mpxio.
15020 	 */
15021 	if ((un->un_f_is_fibre == TRUE) &&
15022 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
15023 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
15024 		scsi_dmafree(pktp);
15025 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
15026 	}
15027 #endif
15028 
15029 	/*
15030 	 * The command did not successfully complete as requested so check
15031 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
15032 	 * driver command that should not be retried so just return. If
15033 	 * FLAG_DIAGNOSE is not set the error will be processed below.
15034 	 */
15035 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
15036 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15037 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
15038 		/*
15039 		 * Issue a request sense if a check condition caused the error
15040 		 * (we handle the auto request sense case above), otherwise
15041 		 * just fail the command.
15042 		 */
15043 		if ((pktp->pkt_reason == CMD_CMPLT) &&
15044 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
15045 			sd_send_request_sense_command(un, bp, pktp);
15046 		} else {
15047 			sd_return_failed_command(un, bp, EIO);
15048 		}
15049 		goto exit;
15050 	}
15051 
15052 	/*
15053 	 * The command did not successfully complete as requested so process
15054 	 * the error, retry, and/or attempt recovery.
15055 	 */
15056 	switch (pktp->pkt_reason) {
15057 	case CMD_CMPLT:
15058 		switch (SD_GET_PKT_STATUS(pktp)) {
15059 		case STATUS_GOOD:
15060 			/*
15061 			 * The command completed successfully with a non-zero
15062 			 * residual
15063 			 */
15064 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15065 			    "sdintr: STATUS_GOOD \n");
15066 			sd_pkt_status_good(un, bp, xp, pktp);
15067 			break;
15068 
15069 		case STATUS_CHECK:
15070 		case STATUS_TERMINATED:
15071 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15072 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
15073 			sd_pkt_status_check_condition(un, bp, xp, pktp);
15074 			break;
15075 
15076 		case STATUS_BUSY:
15077 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15078 			    "sdintr: STATUS_BUSY\n");
15079 			sd_pkt_status_busy(un, bp, xp, pktp);
15080 			break;
15081 
15082 		case STATUS_RESERVATION_CONFLICT:
15083 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15084 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
15085 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
15086 			break;
15087 
15088 		case STATUS_QFULL:
15089 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15090 			    "sdintr: STATUS_QFULL\n");
15091 			sd_pkt_status_qfull(un, bp, xp, pktp);
15092 			break;
15093 
15094 		case STATUS_MET:
15095 		case STATUS_INTERMEDIATE:
15096 		case STATUS_SCSI2:
15097 		case STATUS_INTERMEDIATE_MET:
15098 		case STATUS_ACA_ACTIVE:
15099 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
15100 			    "Unexpected SCSI status received: 0x%x\n",
15101 			    SD_GET_PKT_STATUS(pktp));
15102 			sd_return_failed_command(un, bp, EIO);
15103 			break;
15104 
15105 		default:
15106 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
15107 			    "Invalid SCSI status received: 0x%x\n",
15108 			    SD_GET_PKT_STATUS(pktp));
15109 			sd_return_failed_command(un, bp, EIO);
15110 			break;
15111 
15112 		}
15113 		break;
15114 
15115 	case CMD_INCOMPLETE:
15116 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15117 		    "sdintr:  CMD_INCOMPLETE\n");
15118 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
15119 		break;
15120 	case CMD_TRAN_ERR:
15121 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15122 		    "sdintr: CMD_TRAN_ERR\n");
15123 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
15124 		break;
15125 	case CMD_RESET:
15126 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15127 		    "sdintr: CMD_RESET \n");
15128 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
15129 		break;
15130 	case CMD_ABORTED:
15131 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15132 		    "sdintr: CMD_ABORTED \n");
15133 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
15134 		break;
15135 	case CMD_TIMEOUT:
15136 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15137 		    "sdintr: CMD_TIMEOUT\n");
15138 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
15139 		break;
15140 	case CMD_UNX_BUS_FREE:
15141 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15142 		    "sdintr: CMD_UNX_BUS_FREE \n");
15143 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
15144 		break;
15145 	case CMD_TAG_REJECT:
15146 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15147 		    "sdintr: CMD_TAG_REJECT\n");
15148 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
15149 		break;
15150 	default:
15151 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15152 		    "sdintr: default\n");
15153 		sd_pkt_reason_default(un, bp, xp, pktp);
15154 		break;
15155 	}
15156 
15157 exit:
15158 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
15159 
15160 	/* Decrement counter to indicate that the callback routine is done. */
15161 	un->un_in_callback--;
15162 	ASSERT(un->un_in_callback >= 0);
15163 
15164 	/*
15165 	 * At this point, the pkt has been dispatched, ie, it is either
15166 	 * being re-tried or has been returned to its caller and should
15167 	 * not be referenced.
15168 	 */
15169 
15170 	mutex_exit(SD_MUTEX(un));
15171 }
15172 
15173 
15174 /*
15175  *    Function: sd_print_incomplete_msg
15176  *
15177  * Description: Prints the error message for a CMD_INCOMPLETE error.
15178  *
15179  *   Arguments: un - ptr to associated softstate for the device.
15180  *		bp - ptr to the buf(9S) for the command.
15181  *		arg - message string ptr
15182  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
15183  *			or SD_NO_RETRY_ISSUED.
15184  *
15185  *     Context: May be called under interrupt context
15186  */
15187 
15188 static void
15189 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
15190 {
15191 	struct scsi_pkt	*pktp;
15192 	char	*msgp;
15193 	char	*cmdp = arg;
15194 
15195 	ASSERT(un != NULL);
15196 	ASSERT(mutex_owned(SD_MUTEX(un)));
15197 	ASSERT(bp != NULL);
15198 	ASSERT(arg != NULL);
15199 	pktp = SD_GET_PKTP(bp);
15200 	ASSERT(pktp != NULL);
15201 
15202 	switch (code) {
15203 	case SD_DELAYED_RETRY_ISSUED:
15204 	case SD_IMMEDIATE_RETRY_ISSUED:
15205 		msgp = "retrying";
15206 		break;
15207 	case SD_NO_RETRY_ISSUED:
15208 	default:
15209 		msgp = "giving up";
15210 		break;
15211 	}
15212 
15213 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
15214 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15215 		    "incomplete %s- %s\n", cmdp, msgp);
15216 	}
15217 }
15218 
15219 
15220 
15221 /*
15222  *    Function: sd_pkt_status_good
15223  *
15224  * Description: Processing for a STATUS_GOOD code in pkt_status.
15225  *
15226  *     Context: May be called under interrupt context
15227  */
15228 
15229 static void
15230 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
15231 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15232 {
15233 	char	*cmdp;
15234 
15235 	ASSERT(un != NULL);
15236 	ASSERT(mutex_owned(SD_MUTEX(un)));
15237 	ASSERT(bp != NULL);
15238 	ASSERT(xp != NULL);
15239 	ASSERT(pktp != NULL);
15240 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
15241 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
15242 	ASSERT(pktp->pkt_resid != 0);
15243 
15244 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
15245 
15246 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
15247 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
15248 	case SCMD_READ:
15249 		cmdp = "read";
15250 		break;
15251 	case SCMD_WRITE:
15252 		cmdp = "write";
15253 		break;
15254 	default:
15255 		SD_UPDATE_B_RESID(bp, pktp);
15256 		sd_return_command(un, bp);
15257 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15258 		return;
15259 	}
15260 
15261 	/*
15262 	 * See if we can retry the read/write, preferrably immediately.
15263 	 * If retries are exhaused, then sd_retry_command() will update
15264 	 * the b_resid count.
15265 	 */
15266 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
15267 	    cmdp, EIO, (clock_t)0, NULL);
15268 
15269 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15270 }
15271 
15272 
15273 
15274 
15275 
15276 /*
15277  *    Function: sd_handle_request_sense
15278  *
15279  * Description: Processing for non-auto Request Sense command.
15280  *
15281  *   Arguments: un - ptr to associated softstate
15282  *		sense_bp - ptr to buf(9S) for the RQS command
15283  *		sense_xp - ptr to the sd_xbuf for the RQS command
15284  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
15285  *
15286  *     Context: May be called under interrupt context
15287  */
15288 
15289 static void
15290 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
15291 	struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
15292 {
15293 	struct buf	*cmd_bp;	/* buf for the original command */
15294 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
15295 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
15296 	size_t		actual_len;	/* actual sense data length */
15297 
15298 	ASSERT(un != NULL);
15299 	ASSERT(mutex_owned(SD_MUTEX(un)));
15300 	ASSERT(sense_bp != NULL);
15301 	ASSERT(sense_xp != NULL);
15302 	ASSERT(sense_pktp != NULL);
15303 
15304 	/*
15305 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
15306 	 * RQS command and not the original command.
15307 	 */
15308 	ASSERT(sense_pktp == un->un_rqs_pktp);
15309 	ASSERT(sense_bp   == un->un_rqs_bp);
15310 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
15311 	    (FLAG_SENSING | FLAG_HEAD));
15312 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
15313 	    FLAG_SENSING) == FLAG_SENSING);
15314 
15315 	/* These are the bp, xp, and pktp for the original command */
15316 	cmd_bp = sense_xp->xb_sense_bp;
15317 	cmd_xp = SD_GET_XBUF(cmd_bp);
15318 	cmd_pktp = SD_GET_PKTP(cmd_bp);
15319 
15320 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
15321 		/*
15322 		 * The REQUEST SENSE command failed.  Release the REQUEST
15323 		 * SENSE command for re-use, get back the bp for the original
15324 		 * command, and attempt to re-try the original command if
15325 		 * FLAG_DIAGNOSE is not set in the original packet.
15326 		 */
15327 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
15328 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15329 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
15330 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
15331 			    NULL, NULL, EIO, (clock_t)0, NULL);
15332 			return;
15333 		}
15334 	}
15335 
15336 	/*
15337 	 * Save the relevant sense info into the xp for the original cmd.
15338 	 *
15339 	 * Note: if the request sense failed the state info will be zero
15340 	 * as set in sd_mark_rqs_busy()
15341 	 */
15342 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
15343 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
15344 	actual_len = MAX_SENSE_LENGTH - sense_pktp->pkt_resid;
15345 	if ((cmd_xp->xb_pkt_flags & SD_XB_USCSICMD) &&
15346 	    (((struct uscsi_cmd *)cmd_xp->xb_pktinfo)->uscsi_rqlen >
15347 	    SENSE_LENGTH)) {
15348 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
15349 		    MAX_SENSE_LENGTH);
15350 		cmd_xp->xb_sense_resid = sense_pktp->pkt_resid;
15351 	} else {
15352 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
15353 		    SENSE_LENGTH);
15354 		if (actual_len < SENSE_LENGTH) {
15355 			cmd_xp->xb_sense_resid = SENSE_LENGTH - actual_len;
15356 		} else {
15357 			cmd_xp->xb_sense_resid = 0;
15358 		}
15359 	}
15360 
15361 	/*
15362 	 *  Free up the RQS command....
15363 	 *  NOTE:
15364 	 *	Must do this BEFORE calling sd_validate_sense_data!
15365 	 *	sd_validate_sense_data may return the original command in
15366 	 *	which case the pkt will be freed and the flags can no
15367 	 *	longer be touched.
15368 	 *	SD_MUTEX is held through this process until the command
15369 	 *	is dispatched based upon the sense data, so there are
15370 	 *	no race conditions.
15371 	 */
15372 	(void) sd_mark_rqs_idle(un, sense_xp);
15373 
15374 	/*
15375 	 * For a retryable command see if we have valid sense data, if so then
15376 	 * turn it over to sd_decode_sense() to figure out the right course of
15377 	 * action. Just fail a non-retryable command.
15378 	 */
15379 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15380 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp, actual_len) ==
15381 		    SD_SENSE_DATA_IS_VALID) {
15382 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
15383 		}
15384 	} else {
15385 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
15386 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15387 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
15388 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15389 		sd_return_failed_command(un, cmd_bp, EIO);
15390 	}
15391 }
15392 
15393 
15394 
15395 
15396 /*
15397  *    Function: sd_handle_auto_request_sense
15398  *
15399  * Description: Processing for auto-request sense information.
15400  *
15401  *   Arguments: un - ptr to associated softstate
15402  *		bp - ptr to buf(9S) for the command
15403  *		xp - ptr to the sd_xbuf for the command
15404  *		pktp - ptr to the scsi_pkt(9S) for the command
15405  *
15406  *     Context: May be called under interrupt context
15407  */
15408 
15409 static void
15410 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
15411 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15412 {
15413 	struct scsi_arq_status *asp;
15414 	size_t actual_len;
15415 
15416 	ASSERT(un != NULL);
15417 	ASSERT(mutex_owned(SD_MUTEX(un)));
15418 	ASSERT(bp != NULL);
15419 	ASSERT(xp != NULL);
15420 	ASSERT(pktp != NULL);
15421 	ASSERT(pktp != un->un_rqs_pktp);
15422 	ASSERT(bp   != un->un_rqs_bp);
15423 
15424 	/*
15425 	 * For auto-request sense, we get a scsi_arq_status back from
15426 	 * the HBA, with the sense data in the sts_sensedata member.
15427 	 * The pkt_scbp of the packet points to this scsi_arq_status.
15428 	 */
15429 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
15430 
15431 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
15432 		/*
15433 		 * The auto REQUEST SENSE failed; see if we can re-try
15434 		 * the original command.
15435 		 */
15436 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15437 		    "auto request sense failed (reason=%s)\n",
15438 		    scsi_rname(asp->sts_rqpkt_reason));
15439 
15440 		sd_reset_target(un, pktp);
15441 
15442 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15443 		    NULL, NULL, EIO, (clock_t)0, NULL);
15444 		return;
15445 	}
15446 
15447 	/* Save the relevant sense info into the xp for the original cmd. */
15448 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
15449 	xp->xb_sense_state  = asp->sts_rqpkt_state;
15450 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
15451 	if (xp->xb_sense_state & STATE_XARQ_DONE) {
15452 		actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
15453 		bcopy(&asp->sts_sensedata, xp->xb_sense_data,
15454 		    MAX_SENSE_LENGTH);
15455 	} else {
15456 		if (xp->xb_sense_resid > SENSE_LENGTH) {
15457 			actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
15458 		} else {
15459 			actual_len = SENSE_LENGTH - xp->xb_sense_resid;
15460 		}
15461 		if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
15462 			xp->xb_sense_resid = (int)(((struct uscsi_cmd *)
15463 			    (xp->xb_pktinfo))->uscsi_rqlen) - actual_len;
15464 		}
15465 		bcopy(&asp->sts_sensedata, xp->xb_sense_data, SENSE_LENGTH);
15466 	}
15467 
15468 	/*
15469 	 * See if we have valid sense data, if so then turn it over to
15470 	 * sd_decode_sense() to figure out the right course of action.
15471 	 */
15472 	if (sd_validate_sense_data(un, bp, xp, actual_len) ==
15473 	    SD_SENSE_DATA_IS_VALID) {
15474 		sd_decode_sense(un, bp, xp, pktp);
15475 	}
15476 }
15477 
15478 
15479 /*
15480  *    Function: sd_print_sense_failed_msg
15481  *
15482  * Description: Print log message when RQS has failed.
15483  *
15484  *   Arguments: un - ptr to associated softstate
15485  *		bp - ptr to buf(9S) for the command
15486  *		arg - generic message string ptr
15487  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15488  *			or SD_NO_RETRY_ISSUED
15489  *
15490  *     Context: May be called from interrupt context
15491  */
15492 
15493 static void
15494 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
15495 	int code)
15496 {
15497 	char	*msgp = arg;
15498 
15499 	ASSERT(un != NULL);
15500 	ASSERT(mutex_owned(SD_MUTEX(un)));
15501 	ASSERT(bp != NULL);
15502 
15503 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
15504 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
15505 	}
15506 }
15507 
15508 
15509 /*
15510  *    Function: sd_validate_sense_data
15511  *
15512  * Description: Check the given sense data for validity.
15513  *		If the sense data is not valid, the command will
15514  *		be either failed or retried!
15515  *
15516  * Return Code: SD_SENSE_DATA_IS_INVALID
15517  *		SD_SENSE_DATA_IS_VALID
15518  *
15519  *     Context: May be called from interrupt context
15520  */
15521 
15522 static int
15523 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
15524 	size_t actual_len)
15525 {
15526 	struct scsi_extended_sense *esp;
15527 	struct	scsi_pkt *pktp;
15528 	char	*msgp = NULL;
15529 
15530 	ASSERT(un != NULL);
15531 	ASSERT(mutex_owned(SD_MUTEX(un)));
15532 	ASSERT(bp != NULL);
15533 	ASSERT(bp != un->un_rqs_bp);
15534 	ASSERT(xp != NULL);
15535 
15536 	pktp = SD_GET_PKTP(bp);
15537 	ASSERT(pktp != NULL);
15538 
15539 	/*
15540 	 * Check the status of the RQS command (auto or manual).
15541 	 */
15542 	switch (xp->xb_sense_status & STATUS_MASK) {
15543 	case STATUS_GOOD:
15544 		break;
15545 
15546 	case STATUS_RESERVATION_CONFLICT:
15547 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
15548 		return (SD_SENSE_DATA_IS_INVALID);
15549 
15550 	case STATUS_BUSY:
15551 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15552 		    "Busy Status on REQUEST SENSE\n");
15553 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
15554 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15555 		return (SD_SENSE_DATA_IS_INVALID);
15556 
15557 	case STATUS_QFULL:
15558 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15559 		    "QFULL Status on REQUEST SENSE\n");
15560 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
15561 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15562 		return (SD_SENSE_DATA_IS_INVALID);
15563 
15564 	case STATUS_CHECK:
15565 	case STATUS_TERMINATED:
15566 		msgp = "Check Condition on REQUEST SENSE\n";
15567 		goto sense_failed;
15568 
15569 	default:
15570 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
15571 		goto sense_failed;
15572 	}
15573 
15574 	/*
15575 	 * See if we got the minimum required amount of sense data.
15576 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
15577 	 * or less.
15578 	 */
15579 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
15580 	    (actual_len == 0)) {
15581 		msgp = "Request Sense couldn't get sense data\n";
15582 		goto sense_failed;
15583 	}
15584 
15585 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
15586 		msgp = "Not enough sense information\n";
15587 		goto sense_failed;
15588 	}
15589 
15590 	/*
15591 	 * We require the extended sense data
15592 	 */
15593 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
15594 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
15595 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
15596 			static char tmp[8];
15597 			static char buf[148];
15598 			char *p = (char *)(xp->xb_sense_data);
15599 			int i;
15600 
15601 			mutex_enter(&sd_sense_mutex);
15602 			(void) strcpy(buf, "undecodable sense information:");
15603 			for (i = 0; i < actual_len; i++) {
15604 				(void) sprintf(tmp, " 0x%x", *(p++)&0xff);
15605 				(void) strcpy(&buf[strlen(buf)], tmp);
15606 			}
15607 			i = strlen(buf);
15608 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
15609 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, buf);
15610 			mutex_exit(&sd_sense_mutex);
15611 		}
15612 		/* Note: Legacy behavior, fail the command with no retry */
15613 		sd_return_failed_command(un, bp, EIO);
15614 		return (SD_SENSE_DATA_IS_INVALID);
15615 	}
15616 
15617 	/*
15618 	 * Check that es_code is valid (es_class concatenated with es_code
15619 	 * make up the "response code" field.  es_class will always be 7, so
15620 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
15621 	 * format.
15622 	 */
15623 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
15624 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
15625 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
15626 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
15627 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
15628 		goto sense_failed;
15629 	}
15630 
15631 	return (SD_SENSE_DATA_IS_VALID);
15632 
15633 sense_failed:
15634 	/*
15635 	 * If the request sense failed (for whatever reason), attempt
15636 	 * to retry the original command.
15637 	 */
15638 #if defined(__i386) || defined(__amd64)
15639 	/*
15640 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
15641 	 * sddef.h for Sparc platform, and x86 uses 1 binary
15642 	 * for both SCSI/FC.
15643 	 * The SD_RETRY_DELAY value need to be adjusted here
15644 	 * when SD_RETRY_DELAY change in sddef.h
15645 	 */
15646 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15647 	    sd_print_sense_failed_msg, msgp, EIO,
15648 	    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0, NULL);
15649 #else
15650 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15651 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
15652 #endif
15653 
15654 	return (SD_SENSE_DATA_IS_INVALID);
15655 }
15656 
15657 
15658 
15659 /*
15660  *    Function: sd_decode_sense
15661  *
15662  * Description: Take recovery action(s) when SCSI Sense Data is received.
15663  *
15664  *     Context: Interrupt context.
15665  */
15666 
15667 static void
15668 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
15669 	struct scsi_pkt *pktp)
15670 {
15671 	uint8_t sense_key;
15672 
15673 	ASSERT(un != NULL);
15674 	ASSERT(mutex_owned(SD_MUTEX(un)));
15675 	ASSERT(bp != NULL);
15676 	ASSERT(bp != un->un_rqs_bp);
15677 	ASSERT(xp != NULL);
15678 	ASSERT(pktp != NULL);
15679 
15680 	sense_key = scsi_sense_key(xp->xb_sense_data);
15681 
15682 	switch (sense_key) {
15683 	case KEY_NO_SENSE:
15684 		sd_sense_key_no_sense(un, bp, xp, pktp);
15685 		break;
15686 	case KEY_RECOVERABLE_ERROR:
15687 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
15688 		    bp, xp, pktp);
15689 		break;
15690 	case KEY_NOT_READY:
15691 		sd_sense_key_not_ready(un, xp->xb_sense_data,
15692 		    bp, xp, pktp);
15693 		break;
15694 	case KEY_MEDIUM_ERROR:
15695 	case KEY_HARDWARE_ERROR:
15696 		sd_sense_key_medium_or_hardware_error(un,
15697 		    xp->xb_sense_data, bp, xp, pktp);
15698 		break;
15699 	case KEY_ILLEGAL_REQUEST:
15700 		sd_sense_key_illegal_request(un, bp, xp, pktp);
15701 		break;
15702 	case KEY_UNIT_ATTENTION:
15703 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
15704 		    bp, xp, pktp);
15705 		break;
15706 	case KEY_WRITE_PROTECT:
15707 	case KEY_VOLUME_OVERFLOW:
15708 	case KEY_MISCOMPARE:
15709 		sd_sense_key_fail_command(un, bp, xp, pktp);
15710 		break;
15711 	case KEY_BLANK_CHECK:
15712 		sd_sense_key_blank_check(un, bp, xp, pktp);
15713 		break;
15714 	case KEY_ABORTED_COMMAND:
15715 		sd_sense_key_aborted_command(un, bp, xp, pktp);
15716 		break;
15717 	case KEY_VENDOR_UNIQUE:
15718 	case KEY_COPY_ABORTED:
15719 	case KEY_EQUAL:
15720 	case KEY_RESERVED:
15721 	default:
15722 		sd_sense_key_default(un, xp->xb_sense_data,
15723 		    bp, xp, pktp);
15724 		break;
15725 	}
15726 }
15727 
15728 
15729 /*
15730  *    Function: sd_dump_memory
15731  *
15732  * Description: Debug logging routine to print the contents of a user provided
15733  *		buffer. The output of the buffer is broken up into 256 byte
15734  *		segments due to a size constraint of the scsi_log.
15735  *		implementation.
15736  *
15737  *   Arguments: un - ptr to softstate
15738  *		comp - component mask
15739  *		title - "title" string to preceed data when printed
15740  *		data - ptr to data block to be printed
15741  *		len - size of data block to be printed
15742  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
15743  *
15744  *     Context: May be called from interrupt context
15745  */
15746 
15747 #define	SD_DUMP_MEMORY_BUF_SIZE	256
15748 
15749 static char *sd_dump_format_string[] = {
15750 		" 0x%02x",
15751 		" %c"
15752 };
15753 
15754 static void
15755 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
15756     int len, int fmt)
15757 {
15758 	int	i, j;
15759 	int	avail_count;
15760 	int	start_offset;
15761 	int	end_offset;
15762 	size_t	entry_len;
15763 	char	*bufp;
15764 	char	*local_buf;
15765 	char	*format_string;
15766 
15767 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
15768 
15769 	/*
15770 	 * In the debug version of the driver, this function is called from a
15771 	 * number of places which are NOPs in the release driver.
15772 	 * The debug driver therefore has additional methods of filtering
15773 	 * debug output.
15774 	 */
15775 #ifdef SDDEBUG
15776 	/*
15777 	 * In the debug version of the driver we can reduce the amount of debug
15778 	 * messages by setting sd_error_level to something other than
15779 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
15780 	 * sd_component_mask.
15781 	 */
15782 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
15783 	    (sd_error_level != SCSI_ERR_ALL)) {
15784 		return;
15785 	}
15786 	if (((sd_component_mask & comp) == 0) ||
15787 	    (sd_error_level != SCSI_ERR_ALL)) {
15788 		return;
15789 	}
15790 #else
15791 	if (sd_error_level != SCSI_ERR_ALL) {
15792 		return;
15793 	}
15794 #endif
15795 
15796 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
15797 	bufp = local_buf;
15798 	/*
15799 	 * Available length is the length of local_buf[], minus the
15800 	 * length of the title string, minus one for the ":", minus
15801 	 * one for the newline, minus one for the NULL terminator.
15802 	 * This gives the #bytes available for holding the printed
15803 	 * values from the given data buffer.
15804 	 */
15805 	if (fmt == SD_LOG_HEX) {
15806 		format_string = sd_dump_format_string[0];
15807 	} else /* SD_LOG_CHAR */ {
15808 		format_string = sd_dump_format_string[1];
15809 	}
15810 	/*
15811 	 * Available count is the number of elements from the given
15812 	 * data buffer that we can fit into the available length.
15813 	 * This is based upon the size of the format string used.
15814 	 * Make one entry and find it's size.
15815 	 */
15816 	(void) sprintf(bufp, format_string, data[0]);
15817 	entry_len = strlen(bufp);
15818 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
15819 
15820 	j = 0;
15821 	while (j < len) {
15822 		bufp = local_buf;
15823 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
15824 		start_offset = j;
15825 
15826 		end_offset = start_offset + avail_count;
15827 
15828 		(void) sprintf(bufp, "%s:", title);
15829 		bufp += strlen(bufp);
15830 		for (i = start_offset; ((i < end_offset) && (j < len));
15831 		    i++, j++) {
15832 			(void) sprintf(bufp, format_string, data[i]);
15833 			bufp += entry_len;
15834 		}
15835 		(void) sprintf(bufp, "\n");
15836 
15837 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
15838 	}
15839 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
15840 }
15841 
15842 /*
15843  *    Function: sd_print_sense_msg
15844  *
15845  * Description: Log a message based upon the given sense data.
15846  *
15847  *   Arguments: un - ptr to associated softstate
15848  *		bp - ptr to buf(9S) for the command
15849  *		arg - ptr to associate sd_sense_info struct
15850  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15851  *			or SD_NO_RETRY_ISSUED
15852  *
15853  *     Context: May be called from interrupt context
15854  */
15855 
15856 static void
15857 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
15858 {
15859 	struct sd_xbuf	*xp;
15860 	struct scsi_pkt	*pktp;
15861 	uint8_t *sensep;
15862 	daddr_t request_blkno;
15863 	diskaddr_t err_blkno;
15864 	int severity;
15865 	int pfa_flag;
15866 	extern struct scsi_key_strings scsi_cmds[];
15867 
15868 	ASSERT(un != NULL);
15869 	ASSERT(mutex_owned(SD_MUTEX(un)));
15870 	ASSERT(bp != NULL);
15871 	xp = SD_GET_XBUF(bp);
15872 	ASSERT(xp != NULL);
15873 	pktp = SD_GET_PKTP(bp);
15874 	ASSERT(pktp != NULL);
15875 	ASSERT(arg != NULL);
15876 
15877 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
15878 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
15879 
15880 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
15881 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
15882 		severity = SCSI_ERR_RETRYABLE;
15883 	}
15884 
15885 	/* Use absolute block number for the request block number */
15886 	request_blkno = xp->xb_blkno;
15887 
15888 	/*
15889 	 * Now try to get the error block number from the sense data
15890 	 */
15891 	sensep = xp->xb_sense_data;
15892 
15893 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
15894 	    (uint64_t *)&err_blkno)) {
15895 		/*
15896 		 * We retrieved the error block number from the information
15897 		 * portion of the sense data.
15898 		 *
15899 		 * For USCSI commands we are better off using the error
15900 		 * block no. as the requested block no. (This is the best
15901 		 * we can estimate.)
15902 		 */
15903 		if ((SD_IS_BUFIO(xp) == FALSE) &&
15904 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
15905 			request_blkno = err_blkno;
15906 		}
15907 	} else {
15908 		/*
15909 		 * Without the es_valid bit set (for fixed format) or an
15910 		 * information descriptor (for descriptor format) we cannot
15911 		 * be certain of the error blkno, so just use the
15912 		 * request_blkno.
15913 		 */
15914 		err_blkno = (diskaddr_t)request_blkno;
15915 	}
15916 
15917 	/*
15918 	 * The following will log the buffer contents for the release driver
15919 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
15920 	 * level is set to verbose.
15921 	 */
15922 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
15923 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15924 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15925 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
15926 
15927 	if (pfa_flag == FALSE) {
15928 		/* This is normally only set for USCSI */
15929 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
15930 			return;
15931 		}
15932 
15933 		if ((SD_IS_BUFIO(xp) == TRUE) &&
15934 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
15935 		    (severity < sd_error_level))) {
15936 			return;
15937 		}
15938 	}
15939 
15940 	/*
15941 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
15942 	 */
15943 	if ((SD_IS_LSI(un)) &&
15944 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
15945 	    (scsi_sense_asc(sensep) == 0x94) &&
15946 	    (scsi_sense_ascq(sensep) == 0x01)) {
15947 		un->un_sonoma_failure_count++;
15948 		if (un->un_sonoma_failure_count > 1) {
15949 			return;
15950 		}
15951 	}
15952 
15953 	scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
15954 	    request_blkno, err_blkno, scsi_cmds,
15955 	    (struct scsi_extended_sense *)sensep,
15956 	    un->un_additional_codes, NULL);
15957 }
15958 
15959 /*
15960  *    Function: sd_sense_key_no_sense
15961  *
15962  * Description: Recovery action when sense data was not received.
15963  *
15964  *     Context: May be called from interrupt context
15965  */
15966 
15967 static void
15968 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
15969 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15970 {
15971 	struct sd_sense_info	si;
15972 
15973 	ASSERT(un != NULL);
15974 	ASSERT(mutex_owned(SD_MUTEX(un)));
15975 	ASSERT(bp != NULL);
15976 	ASSERT(xp != NULL);
15977 	ASSERT(pktp != NULL);
15978 
15979 	si.ssi_severity = SCSI_ERR_FATAL;
15980 	si.ssi_pfa_flag = FALSE;
15981 
15982 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
15983 
15984 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
15985 	    &si, EIO, (clock_t)0, NULL);
15986 }
15987 
15988 
15989 /*
15990  *    Function: sd_sense_key_recoverable_error
15991  *
15992  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
15993  *
15994  *     Context: May be called from interrupt context
15995  */
15996 
15997 static void
15998 sd_sense_key_recoverable_error(struct sd_lun *un,
15999 	uint8_t *sense_datap,
16000 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16001 {
16002 	struct sd_sense_info	si;
16003 	uint8_t asc = scsi_sense_asc(sense_datap);
16004 
16005 	ASSERT(un != NULL);
16006 	ASSERT(mutex_owned(SD_MUTEX(un)));
16007 	ASSERT(bp != NULL);
16008 	ASSERT(xp != NULL);
16009 	ASSERT(pktp != NULL);
16010 
16011 	/*
16012 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
16013 	 */
16014 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
16015 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
16016 		si.ssi_severity = SCSI_ERR_INFO;
16017 		si.ssi_pfa_flag = TRUE;
16018 	} else {
16019 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
16020 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
16021 		si.ssi_severity = SCSI_ERR_RECOVERED;
16022 		si.ssi_pfa_flag = FALSE;
16023 	}
16024 
16025 	if (pktp->pkt_resid == 0) {
16026 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16027 		sd_return_command(un, bp);
16028 		return;
16029 	}
16030 
16031 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16032 	    &si, EIO, (clock_t)0, NULL);
16033 }
16034 
16035 
16036 
16037 
16038 /*
16039  *    Function: sd_sense_key_not_ready
16040  *
16041  * Description: Recovery actions for a SCSI "Not Ready" sense key.
16042  *
16043  *     Context: May be called from interrupt context
16044  */
16045 
16046 static void
16047 sd_sense_key_not_ready(struct sd_lun *un,
16048 	uint8_t *sense_datap,
16049 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16050 {
16051 	struct sd_sense_info	si;
16052 	uint8_t asc = scsi_sense_asc(sense_datap);
16053 	uint8_t ascq = scsi_sense_ascq(sense_datap);
16054 
16055 	ASSERT(un != NULL);
16056 	ASSERT(mutex_owned(SD_MUTEX(un)));
16057 	ASSERT(bp != NULL);
16058 	ASSERT(xp != NULL);
16059 	ASSERT(pktp != NULL);
16060 
16061 	si.ssi_severity = SCSI_ERR_FATAL;
16062 	si.ssi_pfa_flag = FALSE;
16063 
16064 	/*
16065 	 * Update error stats after first NOT READY error. Disks may have
16066 	 * been powered down and may need to be restarted.  For CDROMs,
16067 	 * report NOT READY errors only if media is present.
16068 	 */
16069 	if ((ISCD(un) && (asc == 0x3A)) ||
16070 	    (xp->xb_nr_retry_count > 0)) {
16071 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16072 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
16073 	}
16074 
16075 	/*
16076 	 * Just fail if the "not ready" retry limit has been reached.
16077 	 */
16078 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
16079 		/* Special check for error message printing for removables. */
16080 		if (un->un_f_has_removable_media && (asc == 0x04) &&
16081 		    (ascq >= 0x04)) {
16082 			si.ssi_severity = SCSI_ERR_ALL;
16083 		}
16084 		goto fail_command;
16085 	}
16086 
16087 	/*
16088 	 * Check the ASC and ASCQ in the sense data as needed, to determine
16089 	 * what to do.
16090 	 */
16091 	switch (asc) {
16092 	case 0x04:	/* LOGICAL UNIT NOT READY */
16093 		/*
16094 		 * disk drives that don't spin up result in a very long delay
16095 		 * in format without warning messages. We will log a message
16096 		 * if the error level is set to verbose.
16097 		 */
16098 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16099 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16100 			    "logical unit not ready, resetting disk\n");
16101 		}
16102 
16103 		/*
16104 		 * There are different requirements for CDROMs and disks for
16105 		 * the number of retries.  If a CD-ROM is giving this, it is
16106 		 * probably reading TOC and is in the process of getting
16107 		 * ready, so we should keep on trying for a long time to make
16108 		 * sure that all types of media are taken in account (for
16109 		 * some media the drive takes a long time to read TOC).  For
16110 		 * disks we do not want to retry this too many times as this
16111 		 * can cause a long hang in format when the drive refuses to
16112 		 * spin up (a very common failure).
16113 		 */
16114 		switch (ascq) {
16115 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
16116 			/*
16117 			 * Disk drives frequently refuse to spin up which
16118 			 * results in a very long hang in format without
16119 			 * warning messages.
16120 			 *
16121 			 * Note: This code preserves the legacy behavior of
16122 			 * comparing xb_nr_retry_count against zero for fibre
16123 			 * channel targets instead of comparing against the
16124 			 * un_reset_retry_count value.  The reason for this
16125 			 * discrepancy has been so utterly lost beneath the
16126 			 * Sands of Time that even Indiana Jones could not
16127 			 * find it.
16128 			 */
16129 			if (un->un_f_is_fibre == TRUE) {
16130 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
16131 				    (xp->xb_nr_retry_count > 0)) &&
16132 				    (un->un_startstop_timeid == NULL)) {
16133 					scsi_log(SD_DEVINFO(un), sd_label,
16134 					    CE_WARN, "logical unit not ready, "
16135 					    "resetting disk\n");
16136 					sd_reset_target(un, pktp);
16137 				}
16138 			} else {
16139 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
16140 				    (xp->xb_nr_retry_count >
16141 				    un->un_reset_retry_count)) &&
16142 				    (un->un_startstop_timeid == NULL)) {
16143 					scsi_log(SD_DEVINFO(un), sd_label,
16144 					    CE_WARN, "logical unit not ready, "
16145 					    "resetting disk\n");
16146 					sd_reset_target(un, pktp);
16147 				}
16148 			}
16149 			break;
16150 
16151 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
16152 			/*
16153 			 * If the target is in the process of becoming
16154 			 * ready, just proceed with the retry. This can
16155 			 * happen with CD-ROMs that take a long time to
16156 			 * read TOC after a power cycle or reset.
16157 			 */
16158 			goto do_retry;
16159 
16160 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
16161 			break;
16162 
16163 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
16164 			/*
16165 			 * Retries cannot help here so just fail right away.
16166 			 */
16167 			goto fail_command;
16168 
16169 		case 0x88:
16170 			/*
16171 			 * Vendor-unique code for T3/T4: it indicates a
16172 			 * path problem in a mutipathed config, but as far as
16173 			 * the target driver is concerned it equates to a fatal
16174 			 * error, so we should just fail the command right away
16175 			 * (without printing anything to the console). If this
16176 			 * is not a T3/T4, fall thru to the default recovery
16177 			 * action.
16178 			 * T3/T4 is FC only, don't need to check is_fibre
16179 			 */
16180 			if (SD_IS_T3(un) || SD_IS_T4(un)) {
16181 				sd_return_failed_command(un, bp, EIO);
16182 				return;
16183 			}
16184 			/* FALLTHRU */
16185 
16186 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
16187 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
16188 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
16189 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
16190 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
16191 		default:    /* Possible future codes in SCSI spec? */
16192 			/*
16193 			 * For removable-media devices, do not retry if
16194 			 * ASCQ > 2 as these result mostly from USCSI commands
16195 			 * on MMC devices issued to check status of an
16196 			 * operation initiated in immediate mode.  Also for
16197 			 * ASCQ >= 4 do not print console messages as these
16198 			 * mainly represent a user-initiated operation
16199 			 * instead of a system failure.
16200 			 */
16201 			if (un->un_f_has_removable_media) {
16202 				si.ssi_severity = SCSI_ERR_ALL;
16203 				goto fail_command;
16204 			}
16205 			break;
16206 		}
16207 
16208 		/*
16209 		 * As part of our recovery attempt for the NOT READY
16210 		 * condition, we issue a START STOP UNIT command. However
16211 		 * we want to wait for a short delay before attempting this
16212 		 * as there may still be more commands coming back from the
16213 		 * target with the check condition. To do this we use
16214 		 * timeout(9F) to call sd_start_stop_unit_callback() after
16215 		 * the delay interval expires. (sd_start_stop_unit_callback()
16216 		 * dispatches sd_start_stop_unit_task(), which will issue
16217 		 * the actual START STOP UNIT command. The delay interval
16218 		 * is one-half of the delay that we will use to retry the
16219 		 * command that generated the NOT READY condition.
16220 		 *
16221 		 * Note that we could just dispatch sd_start_stop_unit_task()
16222 		 * from here and allow it to sleep for the delay interval,
16223 		 * but then we would be tying up the taskq thread
16224 		 * uncesessarily for the duration of the delay.
16225 		 *
16226 		 * Do not issue the START STOP UNIT if the current command
16227 		 * is already a START STOP UNIT.
16228 		 */
16229 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
16230 			break;
16231 		}
16232 
16233 		/*
16234 		 * Do not schedule the timeout if one is already pending.
16235 		 */
16236 		if (un->un_startstop_timeid != NULL) {
16237 			SD_INFO(SD_LOG_ERROR, un,
16238 			    "sd_sense_key_not_ready: restart already issued to"
16239 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
16240 			    ddi_get_instance(SD_DEVINFO(un)));
16241 			break;
16242 		}
16243 
16244 		/*
16245 		 * Schedule the START STOP UNIT command, then queue the command
16246 		 * for a retry.
16247 		 *
16248 		 * Note: A timeout is not scheduled for this retry because we
16249 		 * want the retry to be serial with the START_STOP_UNIT. The
16250 		 * retry will be started when the START_STOP_UNIT is completed
16251 		 * in sd_start_stop_unit_task.
16252 		 */
16253 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
16254 		    un, SD_BSY_TIMEOUT / 2);
16255 		xp->xb_nr_retry_count++;
16256 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
16257 		return;
16258 
16259 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
16260 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16261 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16262 			    "unit does not respond to selection\n");
16263 		}
16264 		break;
16265 
16266 	case 0x3A:	/* MEDIUM NOT PRESENT */
16267 		if (sd_error_level >= SCSI_ERR_FATAL) {
16268 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16269 			    "Caddy not inserted in drive\n");
16270 		}
16271 
16272 		sr_ejected(un);
16273 		un->un_mediastate = DKIO_EJECTED;
16274 		/* The state has changed, inform the media watch routines */
16275 		cv_broadcast(&un->un_state_cv);
16276 		/* Just fail if no media is present in the drive. */
16277 		goto fail_command;
16278 
16279 	default:
16280 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16281 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
16282 			    "Unit not Ready. Additional sense code 0x%x\n",
16283 			    asc);
16284 		}
16285 		break;
16286 	}
16287 
16288 do_retry:
16289 
16290 	/*
16291 	 * Retry the command, as some targets may report NOT READY for
16292 	 * several seconds after being reset.
16293 	 */
16294 	xp->xb_nr_retry_count++;
16295 	si.ssi_severity = SCSI_ERR_RETRYABLE;
16296 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
16297 	    &si, EIO, SD_BSY_TIMEOUT, NULL);
16298 
16299 	return;
16300 
16301 fail_command:
16302 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16303 	sd_return_failed_command(un, bp, EIO);
16304 }
16305 
16306 
16307 
16308 /*
16309  *    Function: sd_sense_key_medium_or_hardware_error
16310  *
16311  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
16312  *		sense key.
16313  *
16314  *     Context: May be called from interrupt context
16315  */
16316 
16317 static void
16318 sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
16319 	uint8_t *sense_datap,
16320 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16321 {
16322 	struct sd_sense_info	si;
16323 	uint8_t sense_key = scsi_sense_key(sense_datap);
16324 	uint8_t asc = scsi_sense_asc(sense_datap);
16325 
16326 	ASSERT(un != NULL);
16327 	ASSERT(mutex_owned(SD_MUTEX(un)));
16328 	ASSERT(bp != NULL);
16329 	ASSERT(xp != NULL);
16330 	ASSERT(pktp != NULL);
16331 
16332 	si.ssi_severity = SCSI_ERR_FATAL;
16333 	si.ssi_pfa_flag = FALSE;
16334 
16335 	if (sense_key == KEY_MEDIUM_ERROR) {
16336 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
16337 	}
16338 
16339 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16340 
16341 	if ((un->un_reset_retry_count != 0) &&
16342 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
16343 		mutex_exit(SD_MUTEX(un));
16344 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
16345 		if (un->un_f_allow_bus_device_reset == TRUE) {
16346 
16347 			boolean_t try_resetting_target = B_TRUE;
16348 
16349 			/*
16350 			 * We need to be able to handle specific ASC when we are
16351 			 * handling a KEY_HARDWARE_ERROR. In particular
16352 			 * taking the default action of resetting the target may
16353 			 * not be the appropriate way to attempt recovery.
16354 			 * Resetting a target because of a single LUN failure
16355 			 * victimizes all LUNs on that target.
16356 			 *
16357 			 * This is true for the LSI arrays, if an LSI
16358 			 * array controller returns an ASC of 0x84 (LUN Dead) we
16359 			 * should trust it.
16360 			 */
16361 
16362 			if (sense_key == KEY_HARDWARE_ERROR) {
16363 				switch (asc) {
16364 				case 0x84:
16365 					if (SD_IS_LSI(un)) {
16366 						try_resetting_target = B_FALSE;
16367 					}
16368 					break;
16369 				default:
16370 					break;
16371 				}
16372 			}
16373 
16374 			if (try_resetting_target == B_TRUE) {
16375 				int reset_retval = 0;
16376 				if (un->un_f_lun_reset_enabled == TRUE) {
16377 					SD_TRACE(SD_LOG_IO_CORE, un,
16378 					    "sd_sense_key_medium_or_hardware_"
16379 					    "error: issuing RESET_LUN\n");
16380 					reset_retval =
16381 					    scsi_reset(SD_ADDRESS(un),
16382 					    RESET_LUN);
16383 				}
16384 				if (reset_retval == 0) {
16385 					SD_TRACE(SD_LOG_IO_CORE, un,
16386 					    "sd_sense_key_medium_or_hardware_"
16387 					    "error: issuing RESET_TARGET\n");
16388 					(void) scsi_reset(SD_ADDRESS(un),
16389 					    RESET_TARGET);
16390 				}
16391 			}
16392 		}
16393 		mutex_enter(SD_MUTEX(un));
16394 	}
16395 
16396 	/*
16397 	 * This really ought to be a fatal error, but we will retry anyway
16398 	 * as some drives report this as a spurious error.
16399 	 */
16400 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16401 	    &si, EIO, (clock_t)0, NULL);
16402 }
16403 
16404 
16405 
16406 /*
16407  *    Function: sd_sense_key_illegal_request
16408  *
16409  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
16410  *
16411  *     Context: May be called from interrupt context
16412  */
16413 
16414 static void
16415 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
16416 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16417 {
16418 	struct sd_sense_info	si;
16419 
16420 	ASSERT(un != NULL);
16421 	ASSERT(mutex_owned(SD_MUTEX(un)));
16422 	ASSERT(bp != NULL);
16423 	ASSERT(xp != NULL);
16424 	ASSERT(pktp != NULL);
16425 
16426 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
16427 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
16428 
16429 	si.ssi_severity = SCSI_ERR_INFO;
16430 	si.ssi_pfa_flag = FALSE;
16431 
16432 	/* Pointless to retry if the target thinks it's an illegal request */
16433 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16434 	sd_return_failed_command(un, bp, EIO);
16435 }
16436 
16437 
16438 
16439 
16440 /*
16441  *    Function: sd_sense_key_unit_attention
16442  *
16443  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
16444  *
16445  *     Context: May be called from interrupt context
16446  */
16447 
16448 static void
16449 sd_sense_key_unit_attention(struct sd_lun *un,
16450 	uint8_t *sense_datap,
16451 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16452 {
16453 	/*
16454 	 * For UNIT ATTENTION we allow retries for one minute. Devices
16455 	 * like Sonoma can return UNIT ATTENTION close to a minute
16456 	 * under certain conditions.
16457 	 */
16458 	int	retry_check_flag = SD_RETRIES_UA;
16459 	boolean_t	kstat_updated = B_FALSE;
16460 	struct	sd_sense_info		si;
16461 	uint8_t asc = scsi_sense_asc(sense_datap);
16462 
16463 	ASSERT(un != NULL);
16464 	ASSERT(mutex_owned(SD_MUTEX(un)));
16465 	ASSERT(bp != NULL);
16466 	ASSERT(xp != NULL);
16467 	ASSERT(pktp != NULL);
16468 
16469 	si.ssi_severity = SCSI_ERR_INFO;
16470 	si.ssi_pfa_flag = FALSE;
16471 
16472 
16473 	switch (asc) {
16474 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
16475 		if (sd_report_pfa != 0) {
16476 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
16477 			si.ssi_pfa_flag = TRUE;
16478 			retry_check_flag = SD_RETRIES_STANDARD;
16479 			goto do_retry;
16480 		}
16481 
16482 		break;
16483 
16484 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
16485 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
16486 			un->un_resvd_status |=
16487 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
16488 		}
16489 #ifdef _LP64
16490 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
16491 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
16492 			    un, KM_NOSLEEP) == 0) {
16493 				/*
16494 				 * If we can't dispatch the task we'll just
16495 				 * live without descriptor sense.  We can
16496 				 * try again on the next "unit attention"
16497 				 */
16498 				SD_ERROR(SD_LOG_ERROR, un,
16499 				    "sd_sense_key_unit_attention: "
16500 				    "Could not dispatch "
16501 				    "sd_reenable_dsense_task\n");
16502 			}
16503 		}
16504 #endif /* _LP64 */
16505 		/* FALLTHRU */
16506 
16507 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
16508 		if (!un->un_f_has_removable_media) {
16509 			break;
16510 		}
16511 
16512 		/*
16513 		 * When we get a unit attention from a removable-media device,
16514 		 * it may be in a state that will take a long time to recover
16515 		 * (e.g., from a reset).  Since we are executing in interrupt
16516 		 * context here, we cannot wait around for the device to come
16517 		 * back. So hand this command off to sd_media_change_task()
16518 		 * for deferred processing under taskq thread context. (Note
16519 		 * that the command still may be failed if a problem is
16520 		 * encountered at a later time.)
16521 		 */
16522 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
16523 		    KM_NOSLEEP) == 0) {
16524 			/*
16525 			 * Cannot dispatch the request so fail the command.
16526 			 */
16527 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
16528 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16529 			si.ssi_severity = SCSI_ERR_FATAL;
16530 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16531 			sd_return_failed_command(un, bp, EIO);
16532 		}
16533 
16534 		/*
16535 		 * If failed to dispatch sd_media_change_task(), we already
16536 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
16537 		 * we should update kstat later if it encounters an error. So,
16538 		 * we update kstat_updated flag here.
16539 		 */
16540 		kstat_updated = B_TRUE;
16541 
16542 		/*
16543 		 * Either the command has been successfully dispatched to a
16544 		 * task Q for retrying, or the dispatch failed. In either case
16545 		 * do NOT retry again by calling sd_retry_command. This sets up
16546 		 * two retries of the same command and when one completes and
16547 		 * frees the resources the other will access freed memory,
16548 		 * a bad thing.
16549 		 */
16550 		return;
16551 
16552 	default:
16553 		break;
16554 	}
16555 
16556 	/*
16557 	 * Update kstat if we haven't done that.
16558 	 */
16559 	if (!kstat_updated) {
16560 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16561 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16562 	}
16563 
16564 do_retry:
16565 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
16566 	    EIO, SD_UA_RETRY_DELAY, NULL);
16567 }
16568 
16569 
16570 
16571 /*
16572  *    Function: sd_sense_key_fail_command
16573  *
16574  * Description: Use to fail a command when we don't like the sense key that
16575  *		was returned.
16576  *
16577  *     Context: May be called from interrupt context
16578  */
16579 
16580 static void
16581 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
16582 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16583 {
16584 	struct sd_sense_info	si;
16585 
16586 	ASSERT(un != NULL);
16587 	ASSERT(mutex_owned(SD_MUTEX(un)));
16588 	ASSERT(bp != NULL);
16589 	ASSERT(xp != NULL);
16590 	ASSERT(pktp != NULL);
16591 
16592 	si.ssi_severity = SCSI_ERR_FATAL;
16593 	si.ssi_pfa_flag = FALSE;
16594 
16595 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16596 	sd_return_failed_command(un, bp, EIO);
16597 }
16598 
16599 
16600 
16601 /*
16602  *    Function: sd_sense_key_blank_check
16603  *
16604  * Description: Recovery actions for a SCSI "Blank Check" sense key.
16605  *		Has no monetary connotation.
16606  *
16607  *     Context: May be called from interrupt context
16608  */
16609 
16610 static void
16611 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
16612 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16613 {
16614 	struct sd_sense_info	si;
16615 
16616 	ASSERT(un != NULL);
16617 	ASSERT(mutex_owned(SD_MUTEX(un)));
16618 	ASSERT(bp != NULL);
16619 	ASSERT(xp != NULL);
16620 	ASSERT(pktp != NULL);
16621 
16622 	/*
16623 	 * Blank check is not fatal for removable devices, therefore
16624 	 * it does not require a console message.
16625 	 */
16626 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
16627 	    SCSI_ERR_FATAL;
16628 	si.ssi_pfa_flag = FALSE;
16629 
16630 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16631 	sd_return_failed_command(un, bp, EIO);
16632 }
16633 
16634 
16635 
16636 
16637 /*
16638  *    Function: sd_sense_key_aborted_command
16639  *
16640  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
16641  *
16642  *     Context: May be called from interrupt context
16643  */
16644 
16645 static void
16646 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
16647 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16648 {
16649 	struct sd_sense_info	si;
16650 
16651 	ASSERT(un != NULL);
16652 	ASSERT(mutex_owned(SD_MUTEX(un)));
16653 	ASSERT(bp != NULL);
16654 	ASSERT(xp != NULL);
16655 	ASSERT(pktp != NULL);
16656 
16657 	si.ssi_severity = SCSI_ERR_FATAL;
16658 	si.ssi_pfa_flag = FALSE;
16659 
16660 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16661 
16662 	/*
16663 	 * This really ought to be a fatal error, but we will retry anyway
16664 	 * as some drives report this as a spurious error.
16665 	 */
16666 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16667 	    &si, EIO, drv_usectohz(100000), NULL);
16668 }
16669 
16670 
16671 
16672 /*
16673  *    Function: sd_sense_key_default
16674  *
16675  * Description: Default recovery action for several SCSI sense keys (basically
16676  *		attempts a retry).
16677  *
16678  *     Context: May be called from interrupt context
16679  */
16680 
16681 static void
16682 sd_sense_key_default(struct sd_lun *un,
16683 	uint8_t *sense_datap,
16684 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16685 {
16686 	struct sd_sense_info	si;
16687 	uint8_t sense_key = scsi_sense_key(sense_datap);
16688 
16689 	ASSERT(un != NULL);
16690 	ASSERT(mutex_owned(SD_MUTEX(un)));
16691 	ASSERT(bp != NULL);
16692 	ASSERT(xp != NULL);
16693 	ASSERT(pktp != NULL);
16694 
16695 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16696 
16697 	/*
16698 	 * Undecoded sense key.	Attempt retries and hope that will fix
16699 	 * the problem.  Otherwise, we're dead.
16700 	 */
16701 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
16702 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16703 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
16704 	}
16705 
16706 	si.ssi_severity = SCSI_ERR_FATAL;
16707 	si.ssi_pfa_flag = FALSE;
16708 
16709 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16710 	    &si, EIO, (clock_t)0, NULL);
16711 }
16712 
16713 
16714 
16715 /*
16716  *    Function: sd_print_retry_msg
16717  *
16718  * Description: Print a message indicating the retry action being taken.
16719  *
16720  *   Arguments: un - ptr to associated softstate
16721  *		bp - ptr to buf(9S) for the command
16722  *		arg - not used.
16723  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16724  *			or SD_NO_RETRY_ISSUED
16725  *
16726  *     Context: May be called from interrupt context
16727  */
16728 /* ARGSUSED */
16729 static void
16730 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
16731 {
16732 	struct sd_xbuf	*xp;
16733 	struct scsi_pkt *pktp;
16734 	char *reasonp;
16735 	char *msgp;
16736 
16737 	ASSERT(un != NULL);
16738 	ASSERT(mutex_owned(SD_MUTEX(un)));
16739 	ASSERT(bp != NULL);
16740 	pktp = SD_GET_PKTP(bp);
16741 	ASSERT(pktp != NULL);
16742 	xp = SD_GET_XBUF(bp);
16743 	ASSERT(xp != NULL);
16744 
16745 	ASSERT(!mutex_owned(&un->un_pm_mutex));
16746 	mutex_enter(&un->un_pm_mutex);
16747 	if ((un->un_state == SD_STATE_SUSPENDED) ||
16748 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
16749 	    (pktp->pkt_flags & FLAG_SILENT)) {
16750 		mutex_exit(&un->un_pm_mutex);
16751 		goto update_pkt_reason;
16752 	}
16753 	mutex_exit(&un->un_pm_mutex);
16754 
16755 	/*
16756 	 * Suppress messages if they are all the same pkt_reason; with
16757 	 * TQ, many (up to 256) are returned with the same pkt_reason.
16758 	 * If we are in panic, then suppress the retry messages.
16759 	 */
16760 	switch (flag) {
16761 	case SD_NO_RETRY_ISSUED:
16762 		msgp = "giving up";
16763 		break;
16764 	case SD_IMMEDIATE_RETRY_ISSUED:
16765 	case SD_DELAYED_RETRY_ISSUED:
16766 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
16767 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
16768 		    (sd_error_level != SCSI_ERR_ALL))) {
16769 			return;
16770 		}
16771 		msgp = "retrying command";
16772 		break;
16773 	default:
16774 		goto update_pkt_reason;
16775 	}
16776 
16777 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
16778 	    scsi_rname(pktp->pkt_reason));
16779 
16780 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16781 	    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
16782 
16783 update_pkt_reason:
16784 	/*
16785 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
16786 	 * This is to prevent multiple console messages for the same failure
16787 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
16788 	 * when the command is retried successfully because there still may be
16789 	 * more commands coming back with the same value of pktp->pkt_reason.
16790 	 */
16791 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
16792 		un->un_last_pkt_reason = pktp->pkt_reason;
16793 	}
16794 }
16795 
16796 
16797 /*
16798  *    Function: sd_print_cmd_incomplete_msg
16799  *
16800  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
16801  *
16802  *   Arguments: un - ptr to associated softstate
16803  *		bp - ptr to buf(9S) for the command
16804  *		arg - passed to sd_print_retry_msg()
16805  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16806  *			or SD_NO_RETRY_ISSUED
16807  *
16808  *     Context: May be called from interrupt context
16809  */
16810 
16811 static void
16812 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
16813 	int code)
16814 {
16815 	dev_info_t	*dip;
16816 
16817 	ASSERT(un != NULL);
16818 	ASSERT(mutex_owned(SD_MUTEX(un)));
16819 	ASSERT(bp != NULL);
16820 
16821 	switch (code) {
16822 	case SD_NO_RETRY_ISSUED:
16823 		/* Command was failed. Someone turned off this target? */
16824 		if (un->un_state != SD_STATE_OFFLINE) {
16825 			/*
16826 			 * Suppress message if we are detaching and
16827 			 * device has been disconnected
16828 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
16829 			 * private interface and not part of the DDI
16830 			 */
16831 			dip = un->un_sd->sd_dev;
16832 			if (!(DEVI_IS_DETACHING(dip) &&
16833 			    DEVI_IS_DEVICE_REMOVED(dip))) {
16834 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16835 				"disk not responding to selection\n");
16836 			}
16837 			New_state(un, SD_STATE_OFFLINE);
16838 		}
16839 		break;
16840 
16841 	case SD_DELAYED_RETRY_ISSUED:
16842 	case SD_IMMEDIATE_RETRY_ISSUED:
16843 	default:
16844 		/* Command was successfully queued for retry */
16845 		sd_print_retry_msg(un, bp, arg, code);
16846 		break;
16847 	}
16848 }
16849 
16850 
16851 /*
16852  *    Function: sd_pkt_reason_cmd_incomplete
16853  *
16854  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
16855  *
16856  *     Context: May be called from interrupt context
16857  */
16858 
16859 static void
16860 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
16861 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16862 {
16863 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
16864 
16865 	ASSERT(un != NULL);
16866 	ASSERT(mutex_owned(SD_MUTEX(un)));
16867 	ASSERT(bp != NULL);
16868 	ASSERT(xp != NULL);
16869 	ASSERT(pktp != NULL);
16870 
16871 	/* Do not do a reset if selection did not complete */
16872 	/* Note: Should this not just check the bit? */
16873 	if (pktp->pkt_state != STATE_GOT_BUS) {
16874 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
16875 		sd_reset_target(un, pktp);
16876 	}
16877 
16878 	/*
16879 	 * If the target was not successfully selected, then set
16880 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
16881 	 * with the target, and further retries and/or commands are
16882 	 * likely to take a long time.
16883 	 */
16884 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
16885 		flag |= SD_RETRIES_FAILFAST;
16886 	}
16887 
16888 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16889 
16890 	sd_retry_command(un, bp, flag,
16891 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16892 }
16893 
16894 
16895 
16896 /*
16897  *    Function: sd_pkt_reason_cmd_tran_err
16898  *
16899  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
16900  *
16901  *     Context: May be called from interrupt context
16902  */
16903 
16904 static void
16905 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
16906 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16907 {
16908 	ASSERT(un != NULL);
16909 	ASSERT(mutex_owned(SD_MUTEX(un)));
16910 	ASSERT(bp != NULL);
16911 	ASSERT(xp != NULL);
16912 	ASSERT(pktp != NULL);
16913 
16914 	/*
16915 	 * Do not reset if we got a parity error, or if
16916 	 * selection did not complete.
16917 	 */
16918 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16919 	/* Note: Should this not just check the bit for pkt_state? */
16920 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
16921 	    (pktp->pkt_state != STATE_GOT_BUS)) {
16922 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
16923 		sd_reset_target(un, pktp);
16924 	}
16925 
16926 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16927 
16928 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
16929 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16930 }
16931 
16932 
16933 
16934 /*
16935  *    Function: sd_pkt_reason_cmd_reset
16936  *
16937  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
16938  *
16939  *     Context: May be called from interrupt context
16940  */
16941 
16942 static void
16943 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
16944 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16945 {
16946 	ASSERT(un != NULL);
16947 	ASSERT(mutex_owned(SD_MUTEX(un)));
16948 	ASSERT(bp != NULL);
16949 	ASSERT(xp != NULL);
16950 	ASSERT(pktp != NULL);
16951 
16952 	/* The target may still be running the command, so try to reset. */
16953 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16954 	sd_reset_target(un, pktp);
16955 
16956 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16957 
16958 	/*
16959 	 * If pkt_reason is CMD_RESET chances are that this pkt got
16960 	 * reset because another target on this bus caused it. The target
16961 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
16962 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
16963 	 */
16964 
16965 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
16966 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16967 }
16968 
16969 
16970 
16971 
16972 /*
16973  *    Function: sd_pkt_reason_cmd_aborted
16974  *
16975  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
16976  *
16977  *     Context: May be called from interrupt context
16978  */
16979 
16980 static void
16981 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
16982 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16983 {
16984 	ASSERT(un != NULL);
16985 	ASSERT(mutex_owned(SD_MUTEX(un)));
16986 	ASSERT(bp != NULL);
16987 	ASSERT(xp != NULL);
16988 	ASSERT(pktp != NULL);
16989 
16990 	/* The target may still be running the command, so try to reset. */
16991 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16992 	sd_reset_target(un, pktp);
16993 
16994 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16995 
16996 	/*
16997 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
16998 	 * aborted because another target on this bus caused it. The target
16999 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
17000 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
17001 	 */
17002 
17003 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
17004 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17005 }
17006 
17007 
17008 
17009 /*
17010  *    Function: sd_pkt_reason_cmd_timeout
17011  *
17012  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
17013  *
17014  *     Context: May be called from interrupt context
17015  */
17016 
17017 static void
17018 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
17019 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17020 {
17021 	ASSERT(un != NULL);
17022 	ASSERT(mutex_owned(SD_MUTEX(un)));
17023 	ASSERT(bp != NULL);
17024 	ASSERT(xp != NULL);
17025 	ASSERT(pktp != NULL);
17026 
17027 
17028 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
17029 	sd_reset_target(un, pktp);
17030 
17031 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17032 
17033 	/*
17034 	 * A command timeout indicates that we could not establish
17035 	 * communication with the target, so set SD_RETRIES_FAILFAST
17036 	 * as further retries/commands are likely to take a long time.
17037 	 */
17038 	sd_retry_command(un, bp,
17039 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
17040 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17041 }
17042 
17043 
17044 
17045 /*
17046  *    Function: sd_pkt_reason_cmd_unx_bus_free
17047  *
17048  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
17049  *
17050  *     Context: May be called from interrupt context
17051  */
17052 
17053 static void
17054 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
17055 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17056 {
17057 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
17058 
17059 	ASSERT(un != NULL);
17060 	ASSERT(mutex_owned(SD_MUTEX(un)));
17061 	ASSERT(bp != NULL);
17062 	ASSERT(xp != NULL);
17063 	ASSERT(pktp != NULL);
17064 
17065 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17066 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17067 
17068 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
17069 	    sd_print_retry_msg : NULL;
17070 
17071 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
17072 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17073 }
17074 
17075 
17076 /*
17077  *    Function: sd_pkt_reason_cmd_tag_reject
17078  *
17079  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
17080  *
17081  *     Context: May be called from interrupt context
17082  */
17083 
17084 static void
17085 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
17086 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17087 {
17088 	ASSERT(un != NULL);
17089 	ASSERT(mutex_owned(SD_MUTEX(un)));
17090 	ASSERT(bp != NULL);
17091 	ASSERT(xp != NULL);
17092 	ASSERT(pktp != NULL);
17093 
17094 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17095 	pktp->pkt_flags = 0;
17096 	un->un_tagflags = 0;
17097 	if (un->un_f_opt_queueing == TRUE) {
17098 		un->un_throttle = min(un->un_throttle, 3);
17099 	} else {
17100 		un->un_throttle = 1;
17101 	}
17102 	mutex_exit(SD_MUTEX(un));
17103 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
17104 	mutex_enter(SD_MUTEX(un));
17105 
17106 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17107 
17108 	/* Legacy behavior not to check retry counts here. */
17109 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
17110 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17111 }
17112 
17113 
17114 /*
17115  *    Function: sd_pkt_reason_default
17116  *
17117  * Description: Default recovery actions for SCSA pkt_reason values that
17118  *		do not have more explicit recovery actions.
17119  *
17120  *     Context: May be called from interrupt context
17121  */
17122 
17123 static void
17124 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
17125 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17126 {
17127 	ASSERT(un != NULL);
17128 	ASSERT(mutex_owned(SD_MUTEX(un)));
17129 	ASSERT(bp != NULL);
17130 	ASSERT(xp != NULL);
17131 	ASSERT(pktp != NULL);
17132 
17133 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
17134 	sd_reset_target(un, pktp);
17135 
17136 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17137 
17138 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
17139 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17140 }
17141 
17142 
17143 
17144 /*
17145  *    Function: sd_pkt_status_check_condition
17146  *
17147  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
17148  *
17149  *     Context: May be called from interrupt context
17150  */
17151 
17152 static void
17153 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
17154 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17155 {
17156 	ASSERT(un != NULL);
17157 	ASSERT(mutex_owned(SD_MUTEX(un)));
17158 	ASSERT(bp != NULL);
17159 	ASSERT(xp != NULL);
17160 	ASSERT(pktp != NULL);
17161 
17162 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
17163 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
17164 
17165 	/*
17166 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
17167 	 * command will be retried after the request sense). Otherwise, retry
17168 	 * the command. Note: we are issuing the request sense even though the
17169 	 * retry limit may have been reached for the failed command.
17170 	 */
17171 	if (un->un_f_arq_enabled == FALSE) {
17172 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
17173 		    "no ARQ, sending request sense command\n");
17174 		sd_send_request_sense_command(un, bp, pktp);
17175 	} else {
17176 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
17177 		    "ARQ,retrying request sense command\n");
17178 #if defined(__i386) || defined(__amd64)
17179 		/*
17180 		 * The SD_RETRY_DELAY value need to be adjusted here
17181 		 * when SD_RETRY_DELAY change in sddef.h
17182 		 */
17183 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
17184 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
17185 		    NULL);
17186 #else
17187 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
17188 		    EIO, SD_RETRY_DELAY, NULL);
17189 #endif
17190 	}
17191 
17192 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
17193 }
17194 
17195 
17196 /*
17197  *    Function: sd_pkt_status_busy
17198  *
17199  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
17200  *
17201  *     Context: May be called from interrupt context
17202  */
17203 
17204 static void
17205 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17206 	struct scsi_pkt *pktp)
17207 {
17208 	ASSERT(un != NULL);
17209 	ASSERT(mutex_owned(SD_MUTEX(un)));
17210 	ASSERT(bp != NULL);
17211 	ASSERT(xp != NULL);
17212 	ASSERT(pktp != NULL);
17213 
17214 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17215 	    "sd_pkt_status_busy: entry\n");
17216 
17217 	/* If retries are exhausted, just fail the command. */
17218 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
17219 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17220 		    "device busy too long\n");
17221 		sd_return_failed_command(un, bp, EIO);
17222 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17223 		    "sd_pkt_status_busy: exit\n");
17224 		return;
17225 	}
17226 	xp->xb_retry_count++;
17227 
17228 	/*
17229 	 * Try to reset the target. However, we do not want to perform
17230 	 * more than one reset if the device continues to fail. The reset
17231 	 * will be performed when the retry count reaches the reset
17232 	 * threshold.  This threshold should be set such that at least
17233 	 * one retry is issued before the reset is performed.
17234 	 */
17235 	if (xp->xb_retry_count ==
17236 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
17237 		int rval = 0;
17238 		mutex_exit(SD_MUTEX(un));
17239 		if (un->un_f_allow_bus_device_reset == TRUE) {
17240 			/*
17241 			 * First try to reset the LUN; if we cannot then
17242 			 * try to reset the target.
17243 			 */
17244 			if (un->un_f_lun_reset_enabled == TRUE) {
17245 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17246 				    "sd_pkt_status_busy: RESET_LUN\n");
17247 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
17248 			}
17249 			if (rval == 0) {
17250 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17251 				    "sd_pkt_status_busy: RESET_TARGET\n");
17252 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
17253 			}
17254 		}
17255 		if (rval == 0) {
17256 			/*
17257 			 * If the RESET_LUN and/or RESET_TARGET failed,
17258 			 * try RESET_ALL
17259 			 */
17260 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17261 			    "sd_pkt_status_busy: RESET_ALL\n");
17262 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
17263 		}
17264 		mutex_enter(SD_MUTEX(un));
17265 		if (rval == 0) {
17266 			/*
17267 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
17268 			 * At this point we give up & fail the command.
17269 			 */
17270 			sd_return_failed_command(un, bp, EIO);
17271 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17272 			    "sd_pkt_status_busy: exit (failed cmd)\n");
17273 			return;
17274 		}
17275 	}
17276 
17277 	/*
17278 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
17279 	 * we have already checked the retry counts above.
17280 	 */
17281 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
17282 	    EIO, SD_BSY_TIMEOUT, NULL);
17283 
17284 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17285 	    "sd_pkt_status_busy: exit\n");
17286 }
17287 
17288 
17289 /*
17290  *    Function: sd_pkt_status_reservation_conflict
17291  *
17292  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
17293  *		command status.
17294  *
17295  *     Context: May be called from interrupt context
17296  */
17297 
17298 static void
17299 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
17300 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17301 {
17302 	ASSERT(un != NULL);
17303 	ASSERT(mutex_owned(SD_MUTEX(un)));
17304 	ASSERT(bp != NULL);
17305 	ASSERT(xp != NULL);
17306 	ASSERT(pktp != NULL);
17307 
17308 	/*
17309 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
17310 	 * conflict could be due to various reasons like incorrect keys, not
17311 	 * registered or not reserved etc. So, we return EACCES to the caller.
17312 	 */
17313 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
17314 		int cmd = SD_GET_PKT_OPCODE(pktp);
17315 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
17316 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
17317 			sd_return_failed_command(un, bp, EACCES);
17318 			return;
17319 		}
17320 	}
17321 
17322 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
17323 
17324 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
17325 		if (sd_failfast_enable != 0) {
17326 			/* By definition, we must panic here.... */
17327 			sd_panic_for_res_conflict(un);
17328 			/*NOTREACHED*/
17329 		}
17330 		SD_ERROR(SD_LOG_IO, un,
17331 		    "sd_handle_resv_conflict: Disk Reserved\n");
17332 		sd_return_failed_command(un, bp, EACCES);
17333 		return;
17334 	}
17335 
17336 	/*
17337 	 * 1147670: retry only if sd_retry_on_reservation_conflict
17338 	 * property is set (default is 1). Retries will not succeed
17339 	 * on a disk reserved by another initiator. HA systems
17340 	 * may reset this via sd.conf to avoid these retries.
17341 	 *
17342 	 * Note: The legacy return code for this failure is EIO, however EACCES
17343 	 * seems more appropriate for a reservation conflict.
17344 	 */
17345 	if (sd_retry_on_reservation_conflict == 0) {
17346 		SD_ERROR(SD_LOG_IO, un,
17347 		    "sd_handle_resv_conflict: Device Reserved\n");
17348 		sd_return_failed_command(un, bp, EIO);
17349 		return;
17350 	}
17351 
17352 	/*
17353 	 * Retry the command if we can.
17354 	 *
17355 	 * Note: The legacy return code for this failure is EIO, however EACCES
17356 	 * seems more appropriate for a reservation conflict.
17357 	 */
17358 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
17359 	    (clock_t)2, NULL);
17360 }
17361 
17362 
17363 
17364 /*
17365  *    Function: sd_pkt_status_qfull
17366  *
17367  * Description: Handle a QUEUE FULL condition from the target.  This can
17368  *		occur if the HBA does not handle the queue full condition.
17369  *		(Basically this means third-party HBAs as Sun HBAs will
17370  *		handle the queue full condition.)  Note that if there are
17371  *		some commands already in the transport, then the queue full
17372  *		has occurred because the queue for this nexus is actually
17373  *		full. If there are no commands in the transport, then the
17374  *		queue full is resulting from some other initiator or lun
17375  *		consuming all the resources at the target.
17376  *
17377  *     Context: May be called from interrupt context
17378  */
17379 
17380 static void
17381 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
17382 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17383 {
17384 	ASSERT(un != NULL);
17385 	ASSERT(mutex_owned(SD_MUTEX(un)));
17386 	ASSERT(bp != NULL);
17387 	ASSERT(xp != NULL);
17388 	ASSERT(pktp != NULL);
17389 
17390 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17391 	    "sd_pkt_status_qfull: entry\n");
17392 
17393 	/*
17394 	 * Just lower the QFULL throttle and retry the command.  Note that
17395 	 * we do not limit the number of retries here.
17396 	 */
17397 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
17398 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
17399 	    SD_RESTART_TIMEOUT, NULL);
17400 
17401 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17402 	    "sd_pkt_status_qfull: exit\n");
17403 }
17404 
17405 
17406 /*
17407  *    Function: sd_reset_target
17408  *
17409  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
17410  *		RESET_TARGET, or RESET_ALL.
17411  *
17412  *     Context: May be called under interrupt context.
17413  */
17414 
17415 static void
17416 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
17417 {
17418 	int rval = 0;
17419 
17420 	ASSERT(un != NULL);
17421 	ASSERT(mutex_owned(SD_MUTEX(un)));
17422 	ASSERT(pktp != NULL);
17423 
17424 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
17425 
17426 	/*
17427 	 * No need to reset if the transport layer has already done so.
17428 	 */
17429 	if ((pktp->pkt_statistics &
17430 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
17431 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17432 		    "sd_reset_target: no reset\n");
17433 		return;
17434 	}
17435 
17436 	mutex_exit(SD_MUTEX(un));
17437 
17438 	if (un->un_f_allow_bus_device_reset == TRUE) {
17439 		if (un->un_f_lun_reset_enabled == TRUE) {
17440 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17441 			    "sd_reset_target: RESET_LUN\n");
17442 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
17443 		}
17444 		if (rval == 0) {
17445 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17446 			    "sd_reset_target: RESET_TARGET\n");
17447 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
17448 		}
17449 	}
17450 
17451 	if (rval == 0) {
17452 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17453 		    "sd_reset_target: RESET_ALL\n");
17454 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
17455 	}
17456 
17457 	mutex_enter(SD_MUTEX(un));
17458 
17459 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
17460 }
17461 
17462 
17463 /*
17464  *    Function: sd_media_change_task
17465  *
17466  * Description: Recovery action for CDROM to become available.
17467  *
17468  *     Context: Executes in a taskq() thread context
17469  */
17470 
17471 static void
17472 sd_media_change_task(void *arg)
17473 {
17474 	struct	scsi_pkt	*pktp = arg;
17475 	struct	sd_lun		*un;
17476 	struct	buf		*bp;
17477 	struct	sd_xbuf		*xp;
17478 	int	err		= 0;
17479 	int	retry_count	= 0;
17480 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
17481 	struct	sd_sense_info	si;
17482 
17483 	ASSERT(pktp != NULL);
17484 	bp = (struct buf *)pktp->pkt_private;
17485 	ASSERT(bp != NULL);
17486 	xp = SD_GET_XBUF(bp);
17487 	ASSERT(xp != NULL);
17488 	un = SD_GET_UN(bp);
17489 	ASSERT(un != NULL);
17490 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17491 	ASSERT(un->un_f_monitor_media_state);
17492 
17493 	si.ssi_severity = SCSI_ERR_INFO;
17494 	si.ssi_pfa_flag = FALSE;
17495 
17496 	/*
17497 	 * When a reset is issued on a CDROM, it takes a long time to
17498 	 * recover. First few attempts to read capacity and other things
17499 	 * related to handling unit attention fail (with a ASC 0x4 and
17500 	 * ASCQ 0x1). In that case we want to do enough retries and we want
17501 	 * to limit the retries in other cases of genuine failures like
17502 	 * no media in drive.
17503 	 */
17504 	while (retry_count++ < retry_limit) {
17505 		if ((err = sd_handle_mchange(un)) == 0) {
17506 			break;
17507 		}
17508 		if (err == EAGAIN) {
17509 			retry_limit = SD_UNIT_ATTENTION_RETRY;
17510 		}
17511 		/* Sleep for 0.5 sec. & try again */
17512 		delay(drv_usectohz(500000));
17513 	}
17514 
17515 	/*
17516 	 * Dispatch (retry or fail) the original command here,
17517 	 * along with appropriate console messages....
17518 	 *
17519 	 * Must grab the mutex before calling sd_retry_command,
17520 	 * sd_print_sense_msg and sd_return_failed_command.
17521 	 */
17522 	mutex_enter(SD_MUTEX(un));
17523 	if (err != SD_CMD_SUCCESS) {
17524 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17525 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
17526 		si.ssi_severity = SCSI_ERR_FATAL;
17527 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17528 		sd_return_failed_command(un, bp, EIO);
17529 	} else {
17530 		sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
17531 		    &si, EIO, (clock_t)0, NULL);
17532 	}
17533 	mutex_exit(SD_MUTEX(un));
17534 }
17535 
17536 
17537 
17538 /*
17539  *    Function: sd_handle_mchange
17540  *
17541  * Description: Perform geometry validation & other recovery when CDROM
17542  *		has been removed from drive.
17543  *
17544  * Return Code: 0 for success
17545  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
17546  *		sd_send_scsi_READ_CAPACITY()
17547  *
17548  *     Context: Executes in a taskq() thread context
17549  */
17550 
17551 static int
17552 sd_handle_mchange(struct sd_lun *un)
17553 {
17554 	uint64_t	capacity;
17555 	uint32_t	lbasize;
17556 	int		rval;
17557 
17558 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17559 	ASSERT(un->un_f_monitor_media_state);
17560 
17561 	if ((rval = sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
17562 	    SD_PATH_DIRECT_PRIORITY)) != 0) {
17563 		return (rval);
17564 	}
17565 
17566 	mutex_enter(SD_MUTEX(un));
17567 	sd_update_block_info(un, lbasize, capacity);
17568 
17569 	if (un->un_errstats != NULL) {
17570 		struct	sd_errstats *stp =
17571 		    (struct sd_errstats *)un->un_errstats->ks_data;
17572 		stp->sd_capacity.value.ui64 = (uint64_t)
17573 		    ((uint64_t)un->un_blockcount *
17574 		    (uint64_t)un->un_tgt_blocksize);
17575 	}
17576 
17577 
17578 	/*
17579 	 * Check if the media in the device is writable or not
17580 	 */
17581 	if (ISCD(un))
17582 		sd_check_for_writable_cd(un, SD_PATH_DIRECT_PRIORITY);
17583 
17584 	/*
17585 	 * Note: Maybe let the strategy/partitioning chain worry about getting
17586 	 * valid geometry.
17587 	 */
17588 	mutex_exit(SD_MUTEX(un));
17589 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
17590 
17591 
17592 	if (cmlb_validate(un->un_cmlbhandle, 0,
17593 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
17594 		return (EIO);
17595 	} else {
17596 		if (un->un_f_pkstats_enabled) {
17597 			sd_set_pstats(un);
17598 			SD_TRACE(SD_LOG_IO_PARTITION, un,
17599 			    "sd_handle_mchange: un:0x%p pstats created and "
17600 			    "set\n", un);
17601 		}
17602 	}
17603 
17604 
17605 	/*
17606 	 * Try to lock the door
17607 	 */
17608 	return (sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
17609 	    SD_PATH_DIRECT_PRIORITY));
17610 }
17611 
17612 
17613 /*
17614  *    Function: sd_send_scsi_DOORLOCK
17615  *
17616  * Description: Issue the scsi DOOR LOCK command
17617  *
17618  *   Arguments: un    - pointer to driver soft state (unit) structure for
17619  *			this target.
17620  *		flag  - SD_REMOVAL_ALLOW
17621  *			SD_REMOVAL_PREVENT
17622  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17623  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17624  *			to use the USCSI "direct" chain and bypass the normal
17625  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17626  *			command is issued as part of an error recovery action.
17627  *
17628  * Return Code: 0   - Success
17629  *		errno return code from sd_send_scsi_cmd()
17630  *
17631  *     Context: Can sleep.
17632  */
17633 
17634 static int
17635 sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag)
17636 {
17637 	union scsi_cdb		cdb;
17638 	struct uscsi_cmd	ucmd_buf;
17639 	struct scsi_extended_sense	sense_buf;
17640 	int			status;
17641 
17642 	ASSERT(un != NULL);
17643 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17644 
17645 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
17646 
17647 	/* already determined doorlock is not supported, fake success */
17648 	if (un->un_f_doorlock_supported == FALSE) {
17649 		return (0);
17650 	}
17651 
17652 	/*
17653 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
17654 	 * ignore the command so we can complete the eject
17655 	 * operation.
17656 	 */
17657 	if (flag == SD_REMOVAL_PREVENT) {
17658 		mutex_enter(SD_MUTEX(un));
17659 		if (un->un_f_ejecting == TRUE) {
17660 			mutex_exit(SD_MUTEX(un));
17661 			return (EAGAIN);
17662 		}
17663 		mutex_exit(SD_MUTEX(un));
17664 	}
17665 
17666 	bzero(&cdb, sizeof (cdb));
17667 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17668 
17669 	cdb.scc_cmd = SCMD_DOORLOCK;
17670 	cdb.cdb_opaque[4] = (uchar_t)flag;
17671 
17672 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17673 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
17674 	ucmd_buf.uscsi_bufaddr	= NULL;
17675 	ucmd_buf.uscsi_buflen	= 0;
17676 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17677 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17678 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
17679 	ucmd_buf.uscsi_timeout	= 15;
17680 
17681 	SD_TRACE(SD_LOG_IO, un,
17682 	    "sd_send_scsi_DOORLOCK: returning sd_send_scsi_cmd()\n");
17683 
17684 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17685 	    UIO_SYSSPACE, path_flag);
17686 
17687 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
17688 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17689 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
17690 		/* fake success and skip subsequent doorlock commands */
17691 		un->un_f_doorlock_supported = FALSE;
17692 		return (0);
17693 	}
17694 
17695 	return (status);
17696 }
17697 
17698 /*
17699  *    Function: sd_send_scsi_READ_CAPACITY
17700  *
17701  * Description: This routine uses the scsi READ CAPACITY command to determine
17702  *		the device capacity in number of blocks and the device native
17703  *		block size. If this function returns a failure, then the
17704  *		values in *capp and *lbap are undefined.  If the capacity
17705  *		returned is 0xffffffff then the lun is too large for a
17706  *		normal READ CAPACITY command and the results of a
17707  *		READ CAPACITY 16 will be used instead.
17708  *
17709  *   Arguments: un   - ptr to soft state struct for the target
17710  *		capp - ptr to unsigned 64-bit variable to receive the
17711  *			capacity value from the command.
17712  *		lbap - ptr to unsigned 32-bit varaible to receive the
17713  *			block size value from the command
17714  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17715  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17716  *			to use the USCSI "direct" chain and bypass the normal
17717  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17718  *			command is issued as part of an error recovery action.
17719  *
17720  * Return Code: 0   - Success
17721  *		EIO - IO error
17722  *		EACCES - Reservation conflict detected
17723  *		EAGAIN - Device is becoming ready
17724  *		errno return code from sd_send_scsi_cmd()
17725  *
17726  *     Context: Can sleep.  Blocks until command completes.
17727  */
17728 
17729 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
17730 
17731 static int
17732 sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp, uint32_t *lbap,
17733 	int path_flag)
17734 {
17735 	struct	scsi_extended_sense	sense_buf;
17736 	struct	uscsi_cmd	ucmd_buf;
17737 	union	scsi_cdb	cdb;
17738 	uint32_t		*capacity_buf;
17739 	uint64_t		capacity;
17740 	uint32_t		lbasize;
17741 	int			status;
17742 
17743 	ASSERT(un != NULL);
17744 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17745 	ASSERT(capp != NULL);
17746 	ASSERT(lbap != NULL);
17747 
17748 	SD_TRACE(SD_LOG_IO, un,
17749 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
17750 
17751 	/*
17752 	 * First send a READ_CAPACITY command to the target.
17753 	 * (This command is mandatory under SCSI-2.)
17754 	 *
17755 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
17756 	 * Medium Indicator bit is cleared.  The address field must be
17757 	 * zero if the PMI bit is zero.
17758 	 */
17759 	bzero(&cdb, sizeof (cdb));
17760 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17761 
17762 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
17763 
17764 	cdb.scc_cmd = SCMD_READ_CAPACITY;
17765 
17766 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17767 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
17768 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
17769 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
17770 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17771 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17772 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
17773 	ucmd_buf.uscsi_timeout	= 60;
17774 
17775 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17776 	    UIO_SYSSPACE, path_flag);
17777 
17778 	switch (status) {
17779 	case 0:
17780 		/* Return failure if we did not get valid capacity data. */
17781 		if (ucmd_buf.uscsi_resid != 0) {
17782 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17783 			return (EIO);
17784 		}
17785 
17786 		/*
17787 		 * Read capacity and block size from the READ CAPACITY 10 data.
17788 		 * This data may be adjusted later due to device specific
17789 		 * issues.
17790 		 *
17791 		 * According to the SCSI spec, the READ CAPACITY 10
17792 		 * command returns the following:
17793 		 *
17794 		 *  bytes 0-3: Maximum logical block address available.
17795 		 *		(MSB in byte:0 & LSB in byte:3)
17796 		 *
17797 		 *  bytes 4-7: Block length in bytes
17798 		 *		(MSB in byte:4 & LSB in byte:7)
17799 		 *
17800 		 */
17801 		capacity = BE_32(capacity_buf[0]);
17802 		lbasize = BE_32(capacity_buf[1]);
17803 
17804 		/*
17805 		 * Done with capacity_buf
17806 		 */
17807 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17808 
17809 		/*
17810 		 * if the reported capacity is set to all 0xf's, then
17811 		 * this disk is too large and requires SBC-2 commands.
17812 		 * Reissue the request using READ CAPACITY 16.
17813 		 */
17814 		if (capacity == 0xffffffff) {
17815 			status = sd_send_scsi_READ_CAPACITY_16(un, &capacity,
17816 			    &lbasize, path_flag);
17817 			if (status != 0) {
17818 				return (status);
17819 			}
17820 		}
17821 		break;	/* Success! */
17822 	case EIO:
17823 		switch (ucmd_buf.uscsi_status) {
17824 		case STATUS_RESERVATION_CONFLICT:
17825 			status = EACCES;
17826 			break;
17827 		case STATUS_CHECK:
17828 			/*
17829 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
17830 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
17831 			 */
17832 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17833 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
17834 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
17835 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17836 				return (EAGAIN);
17837 			}
17838 			break;
17839 		default:
17840 			break;
17841 		}
17842 		/* FALLTHRU */
17843 	default:
17844 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17845 		return (status);
17846 	}
17847 
17848 	/*
17849 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
17850 	 * (2352 and 0 are common) so for these devices always force the value
17851 	 * to 2048 as required by the ATAPI specs.
17852 	 */
17853 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
17854 		lbasize = 2048;
17855 	}
17856 
17857 	/*
17858 	 * Get the maximum LBA value from the READ CAPACITY data.
17859 	 * Here we assume that the Partial Medium Indicator (PMI) bit
17860 	 * was cleared when issuing the command. This means that the LBA
17861 	 * returned from the device is the LBA of the last logical block
17862 	 * on the logical unit.  The actual logical block count will be
17863 	 * this value plus one.
17864 	 *
17865 	 * Currently the capacity is saved in terms of un->un_sys_blocksize,
17866 	 * so scale the capacity value to reflect this.
17867 	 */
17868 	capacity = (capacity + 1) * (lbasize / un->un_sys_blocksize);
17869 
17870 	/*
17871 	 * Copy the values from the READ CAPACITY command into the space
17872 	 * provided by the caller.
17873 	 */
17874 	*capp = capacity;
17875 	*lbap = lbasize;
17876 
17877 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
17878 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
17879 
17880 	/*
17881 	 * Both the lbasize and capacity from the device must be nonzero,
17882 	 * otherwise we assume that the values are not valid and return
17883 	 * failure to the caller. (4203735)
17884 	 */
17885 	if ((capacity == 0) || (lbasize == 0)) {
17886 		return (EIO);
17887 	}
17888 
17889 	return (0);
17890 }
17891 
17892 /*
17893  *    Function: sd_send_scsi_READ_CAPACITY_16
17894  *
17895  * Description: This routine uses the scsi READ CAPACITY 16 command to
17896  *		determine the device capacity in number of blocks and the
17897  *		device native block size.  If this function returns a failure,
17898  *		then the values in *capp and *lbap are undefined.
17899  *		This routine should always be called by
17900  *		sd_send_scsi_READ_CAPACITY which will appy any device
17901  *		specific adjustments to capacity and lbasize.
17902  *
17903  *   Arguments: un   - ptr to soft state struct for the target
17904  *		capp - ptr to unsigned 64-bit variable to receive the
17905  *			capacity value from the command.
17906  *		lbap - ptr to unsigned 32-bit varaible to receive the
17907  *			block size value from the command
17908  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17909  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17910  *			to use the USCSI "direct" chain and bypass the normal
17911  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
17912  *			this command is issued as part of an error recovery
17913  *			action.
17914  *
17915  * Return Code: 0   - Success
17916  *		EIO - IO error
17917  *		EACCES - Reservation conflict detected
17918  *		EAGAIN - Device is becoming ready
17919  *		errno return code from sd_send_scsi_cmd()
17920  *
17921  *     Context: Can sleep.  Blocks until command completes.
17922  */
17923 
17924 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
17925 
17926 static int
17927 sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
17928 	uint32_t *lbap, int path_flag)
17929 {
17930 	struct	scsi_extended_sense	sense_buf;
17931 	struct	uscsi_cmd	ucmd_buf;
17932 	union	scsi_cdb	cdb;
17933 	uint64_t		*capacity16_buf;
17934 	uint64_t		capacity;
17935 	uint32_t		lbasize;
17936 	int			status;
17937 
17938 	ASSERT(un != NULL);
17939 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17940 	ASSERT(capp != NULL);
17941 	ASSERT(lbap != NULL);
17942 
17943 	SD_TRACE(SD_LOG_IO, un,
17944 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
17945 
17946 	/*
17947 	 * First send a READ_CAPACITY_16 command to the target.
17948 	 *
17949 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
17950 	 * Medium Indicator bit is cleared.  The address field must be
17951 	 * zero if the PMI bit is zero.
17952 	 */
17953 	bzero(&cdb, sizeof (cdb));
17954 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17955 
17956 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
17957 
17958 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17959 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
17960 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
17961 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
17962 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17963 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17964 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
17965 	ucmd_buf.uscsi_timeout	= 60;
17966 
17967 	/*
17968 	 * Read Capacity (16) is a Service Action In command.  One
17969 	 * command byte (0x9E) is overloaded for multiple operations,
17970 	 * with the second CDB byte specifying the desired operation
17971 	 */
17972 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
17973 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
17974 
17975 	/*
17976 	 * Fill in allocation length field
17977 	 */
17978 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
17979 
17980 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17981 	    UIO_SYSSPACE, path_flag);
17982 
17983 	switch (status) {
17984 	case 0:
17985 		/* Return failure if we did not get valid capacity data. */
17986 		if (ucmd_buf.uscsi_resid > 20) {
17987 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17988 			return (EIO);
17989 		}
17990 
17991 		/*
17992 		 * Read capacity and block size from the READ CAPACITY 10 data.
17993 		 * This data may be adjusted later due to device specific
17994 		 * issues.
17995 		 *
17996 		 * According to the SCSI spec, the READ CAPACITY 10
17997 		 * command returns the following:
17998 		 *
17999 		 *  bytes 0-7: Maximum logical block address available.
18000 		 *		(MSB in byte:0 & LSB in byte:7)
18001 		 *
18002 		 *  bytes 8-11: Block length in bytes
18003 		 *		(MSB in byte:8 & LSB in byte:11)
18004 		 *
18005 		 */
18006 		capacity = BE_64(capacity16_buf[0]);
18007 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
18008 
18009 		/*
18010 		 * Done with capacity16_buf
18011 		 */
18012 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
18013 
18014 		/*
18015 		 * if the reported capacity is set to all 0xf's, then
18016 		 * this disk is too large.  This could only happen with
18017 		 * a device that supports LBAs larger than 64 bits which
18018 		 * are not defined by any current T10 standards.
18019 		 */
18020 		if (capacity == 0xffffffffffffffff) {
18021 			return (EIO);
18022 		}
18023 		break;	/* Success! */
18024 	case EIO:
18025 		switch (ucmd_buf.uscsi_status) {
18026 		case STATUS_RESERVATION_CONFLICT:
18027 			status = EACCES;
18028 			break;
18029 		case STATUS_CHECK:
18030 			/*
18031 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
18032 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
18033 			 */
18034 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18035 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
18036 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
18037 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
18038 				return (EAGAIN);
18039 			}
18040 			break;
18041 		default:
18042 			break;
18043 		}
18044 		/* FALLTHRU */
18045 	default:
18046 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
18047 		return (status);
18048 	}
18049 
18050 	*capp = capacity;
18051 	*lbap = lbasize;
18052 
18053 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
18054 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
18055 
18056 	return (0);
18057 }
18058 
18059 
18060 /*
18061  *    Function: sd_send_scsi_START_STOP_UNIT
18062  *
18063  * Description: Issue a scsi START STOP UNIT command to the target.
18064  *
18065  *   Arguments: un    - pointer to driver soft state (unit) structure for
18066  *			this target.
18067  *		flag  - SD_TARGET_START
18068  *			SD_TARGET_STOP
18069  *			SD_TARGET_EJECT
18070  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
18071  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
18072  *			to use the USCSI "direct" chain and bypass the normal
18073  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
18074  *			command is issued as part of an error recovery action.
18075  *
18076  * Return Code: 0   - Success
18077  *		EIO - IO error
18078  *		EACCES - Reservation conflict detected
18079  *		ENXIO  - Not Ready, medium not present
18080  *		errno return code from sd_send_scsi_cmd()
18081  *
18082  *     Context: Can sleep.
18083  */
18084 
18085 static int
18086 sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag, int path_flag)
18087 {
18088 	struct	scsi_extended_sense	sense_buf;
18089 	union scsi_cdb		cdb;
18090 	struct uscsi_cmd	ucmd_buf;
18091 	int			status;
18092 
18093 	ASSERT(un != NULL);
18094 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18095 
18096 	SD_TRACE(SD_LOG_IO, un,
18097 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
18098 
18099 	if (un->un_f_check_start_stop &&
18100 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
18101 	    (un->un_f_start_stop_supported != TRUE)) {
18102 		return (0);
18103 	}
18104 
18105 	/*
18106 	 * If we are performing an eject operation and
18107 	 * we receive any command other than SD_TARGET_EJECT
18108 	 * we should immediately return.
18109 	 */
18110 	if (flag != SD_TARGET_EJECT) {
18111 		mutex_enter(SD_MUTEX(un));
18112 		if (un->un_f_ejecting == TRUE) {
18113 			mutex_exit(SD_MUTEX(un));
18114 			return (EAGAIN);
18115 		}
18116 		mutex_exit(SD_MUTEX(un));
18117 	}
18118 
18119 	bzero(&cdb, sizeof (cdb));
18120 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18121 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18122 
18123 	cdb.scc_cmd = SCMD_START_STOP;
18124 	cdb.cdb_opaque[4] = (uchar_t)flag;
18125 
18126 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18127 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18128 	ucmd_buf.uscsi_bufaddr	= NULL;
18129 	ucmd_buf.uscsi_buflen	= 0;
18130 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18131 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18132 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18133 	ucmd_buf.uscsi_timeout	= 200;
18134 
18135 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18136 	    UIO_SYSSPACE, path_flag);
18137 
18138 	switch (status) {
18139 	case 0:
18140 		break;	/* Success! */
18141 	case EIO:
18142 		switch (ucmd_buf.uscsi_status) {
18143 		case STATUS_RESERVATION_CONFLICT:
18144 			status = EACCES;
18145 			break;
18146 		case STATUS_CHECK:
18147 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
18148 				switch (scsi_sense_key(
18149 				    (uint8_t *)&sense_buf)) {
18150 				case KEY_ILLEGAL_REQUEST:
18151 					status = ENOTSUP;
18152 					break;
18153 				case KEY_NOT_READY:
18154 					if (scsi_sense_asc(
18155 					    (uint8_t *)&sense_buf)
18156 					    == 0x3A) {
18157 						status = ENXIO;
18158 					}
18159 					break;
18160 				default:
18161 					break;
18162 				}
18163 			}
18164 			break;
18165 		default:
18166 			break;
18167 		}
18168 		break;
18169 	default:
18170 		break;
18171 	}
18172 
18173 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
18174 
18175 	return (status);
18176 }
18177 
18178 
18179 /*
18180  *    Function: sd_start_stop_unit_callback
18181  *
18182  * Description: timeout(9F) callback to begin recovery process for a
18183  *		device that has spun down.
18184  *
18185  *   Arguments: arg - pointer to associated softstate struct.
18186  *
18187  *     Context: Executes in a timeout(9F) thread context
18188  */
18189 
18190 static void
18191 sd_start_stop_unit_callback(void *arg)
18192 {
18193 	struct sd_lun	*un = arg;
18194 	ASSERT(un != NULL);
18195 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18196 
18197 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
18198 
18199 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
18200 }
18201 
18202 
18203 /*
18204  *    Function: sd_start_stop_unit_task
18205  *
18206  * Description: Recovery procedure when a drive is spun down.
18207  *
18208  *   Arguments: arg - pointer to associated softstate struct.
18209  *
18210  *     Context: Executes in a taskq() thread context
18211  */
18212 
18213 static void
18214 sd_start_stop_unit_task(void *arg)
18215 {
18216 	struct sd_lun	*un = arg;
18217 
18218 	ASSERT(un != NULL);
18219 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18220 
18221 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
18222 
18223 	/*
18224 	 * Some unformatted drives report not ready error, no need to
18225 	 * restart if format has been initiated.
18226 	 */
18227 	mutex_enter(SD_MUTEX(un));
18228 	if (un->un_f_format_in_progress == TRUE) {
18229 		mutex_exit(SD_MUTEX(un));
18230 		return;
18231 	}
18232 	mutex_exit(SD_MUTEX(un));
18233 
18234 	/*
18235 	 * When a START STOP command is issued from here, it is part of a
18236 	 * failure recovery operation and must be issued before any other
18237 	 * commands, including any pending retries. Thus it must be sent
18238 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
18239 	 * succeeds or not, we will start I/O after the attempt.
18240 	 */
18241 	(void) sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
18242 	    SD_PATH_DIRECT_PRIORITY);
18243 
18244 	/*
18245 	 * The above call blocks until the START_STOP_UNIT command completes.
18246 	 * Now that it has completed, we must re-try the original IO that
18247 	 * received the NOT READY condition in the first place. There are
18248 	 * three possible conditions here:
18249 	 *
18250 	 *  (1) The original IO is on un_retry_bp.
18251 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
18252 	 *	is NULL.
18253 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
18254 	 *	points to some other, unrelated bp.
18255 	 *
18256 	 * For each case, we must call sd_start_cmds() with un_retry_bp
18257 	 * as the argument. If un_retry_bp is NULL, this will initiate
18258 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
18259 	 * then this will process the bp on un_retry_bp. That may or may not
18260 	 * be the original IO, but that does not matter: the important thing
18261 	 * is to keep the IO processing going at this point.
18262 	 *
18263 	 * Note: This is a very specific error recovery sequence associated
18264 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
18265 	 * serialize the I/O with completion of the spin-up.
18266 	 */
18267 	mutex_enter(SD_MUTEX(un));
18268 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18269 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
18270 	    un, un->un_retry_bp);
18271 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
18272 	sd_start_cmds(un, un->un_retry_bp);
18273 	mutex_exit(SD_MUTEX(un));
18274 
18275 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
18276 }
18277 
18278 
18279 /*
18280  *    Function: sd_send_scsi_INQUIRY
18281  *
18282  * Description: Issue the scsi INQUIRY command.
18283  *
18284  *   Arguments: un
18285  *		bufaddr
18286  *		buflen
18287  *		evpd
18288  *		page_code
18289  *		page_length
18290  *
18291  * Return Code: 0   - Success
18292  *		errno return code from sd_send_scsi_cmd()
18293  *
18294  *     Context: Can sleep. Does not return until command is completed.
18295  */
18296 
18297 static int
18298 sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr, size_t buflen,
18299 	uchar_t evpd, uchar_t page_code, size_t *residp)
18300 {
18301 	union scsi_cdb		cdb;
18302 	struct uscsi_cmd	ucmd_buf;
18303 	int			status;
18304 
18305 	ASSERT(un != NULL);
18306 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18307 	ASSERT(bufaddr != NULL);
18308 
18309 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
18310 
18311 	bzero(&cdb, sizeof (cdb));
18312 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18313 	bzero(bufaddr, buflen);
18314 
18315 	cdb.scc_cmd = SCMD_INQUIRY;
18316 	cdb.cdb_opaque[1] = evpd;
18317 	cdb.cdb_opaque[2] = page_code;
18318 	FORMG0COUNT(&cdb, buflen);
18319 
18320 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18321 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18322 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
18323 	ucmd_buf.uscsi_buflen	= buflen;
18324 	ucmd_buf.uscsi_rqbuf	= NULL;
18325 	ucmd_buf.uscsi_rqlen	= 0;
18326 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
18327 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
18328 
18329 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18330 	    UIO_SYSSPACE, SD_PATH_DIRECT);
18331 
18332 	if ((status == 0) && (residp != NULL)) {
18333 		*residp = ucmd_buf.uscsi_resid;
18334 	}
18335 
18336 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
18337 
18338 	return (status);
18339 }
18340 
18341 
18342 /*
18343  *    Function: sd_send_scsi_TEST_UNIT_READY
18344  *
18345  * Description: Issue the scsi TEST UNIT READY command.
18346  *		This routine can be told to set the flag USCSI_DIAGNOSE to
18347  *		prevent retrying failed commands. Use this when the intent
18348  *		is either to check for device readiness, to clear a Unit
18349  *		Attention, or to clear any outstanding sense data.
18350  *		However under specific conditions the expected behavior
18351  *		is for retries to bring a device ready, so use the flag
18352  *		with caution.
18353  *
18354  *   Arguments: un
18355  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
18356  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
18357  *			0: dont check for media present, do retries on cmd.
18358  *
18359  * Return Code: 0   - Success
18360  *		EIO - IO error
18361  *		EACCES - Reservation conflict detected
18362  *		ENXIO  - Not Ready, medium not present
18363  *		errno return code from sd_send_scsi_cmd()
18364  *
18365  *     Context: Can sleep. Does not return until command is completed.
18366  */
18367 
18368 static int
18369 sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag)
18370 {
18371 	struct	scsi_extended_sense	sense_buf;
18372 	union scsi_cdb		cdb;
18373 	struct uscsi_cmd	ucmd_buf;
18374 	int			status;
18375 
18376 	ASSERT(un != NULL);
18377 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18378 
18379 	SD_TRACE(SD_LOG_IO, un,
18380 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
18381 
18382 	/*
18383 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
18384 	 * timeouts when they receive a TUR and the queue is not empty. Check
18385 	 * the configuration flag set during attach (indicating the drive has
18386 	 * this firmware bug) and un_ncmds_in_transport before issuing the
18387 	 * TUR. If there are
18388 	 * pending commands return success, this is a bit arbitrary but is ok
18389 	 * for non-removables (i.e. the eliteI disks) and non-clustering
18390 	 * configurations.
18391 	 */
18392 	if (un->un_f_cfg_tur_check == TRUE) {
18393 		mutex_enter(SD_MUTEX(un));
18394 		if (un->un_ncmds_in_transport != 0) {
18395 			mutex_exit(SD_MUTEX(un));
18396 			return (0);
18397 		}
18398 		mutex_exit(SD_MUTEX(un));
18399 	}
18400 
18401 	bzero(&cdb, sizeof (cdb));
18402 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18403 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18404 
18405 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
18406 
18407 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18408 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18409 	ucmd_buf.uscsi_bufaddr	= NULL;
18410 	ucmd_buf.uscsi_buflen	= 0;
18411 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18412 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18413 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18414 
18415 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
18416 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
18417 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
18418 	}
18419 	ucmd_buf.uscsi_timeout	= 60;
18420 
18421 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18422 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
18423 	    SD_PATH_STANDARD));
18424 
18425 	switch (status) {
18426 	case 0:
18427 		break;	/* Success! */
18428 	case EIO:
18429 		switch (ucmd_buf.uscsi_status) {
18430 		case STATUS_RESERVATION_CONFLICT:
18431 			status = EACCES;
18432 			break;
18433 		case STATUS_CHECK:
18434 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
18435 				break;
18436 			}
18437 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18438 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18439 			    KEY_NOT_READY) &&
18440 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
18441 				status = ENXIO;
18442 			}
18443 			break;
18444 		default:
18445 			break;
18446 		}
18447 		break;
18448 	default:
18449 		break;
18450 	}
18451 
18452 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
18453 
18454 	return (status);
18455 }
18456 
18457 
18458 /*
18459  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
18460  *
18461  * Description: Issue the scsi PERSISTENT RESERVE IN command.
18462  *
18463  *   Arguments: un
18464  *
18465  * Return Code: 0   - Success
18466  *		EACCES
18467  *		ENOTSUP
18468  *		errno return code from sd_send_scsi_cmd()
18469  *
18470  *     Context: Can sleep. Does not return until command is completed.
18471  */
18472 
18473 static int
18474 sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un, uchar_t  usr_cmd,
18475 	uint16_t data_len, uchar_t *data_bufp)
18476 {
18477 	struct scsi_extended_sense	sense_buf;
18478 	union scsi_cdb		cdb;
18479 	struct uscsi_cmd	ucmd_buf;
18480 	int			status;
18481 	int			no_caller_buf = FALSE;
18482 
18483 	ASSERT(un != NULL);
18484 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18485 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
18486 
18487 	SD_TRACE(SD_LOG_IO, un,
18488 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
18489 
18490 	bzero(&cdb, sizeof (cdb));
18491 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18492 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18493 	if (data_bufp == NULL) {
18494 		/* Allocate a default buf if the caller did not give one */
18495 		ASSERT(data_len == 0);
18496 		data_len  = MHIOC_RESV_KEY_SIZE;
18497 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
18498 		no_caller_buf = TRUE;
18499 	}
18500 
18501 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
18502 	cdb.cdb_opaque[1] = usr_cmd;
18503 	FORMG1COUNT(&cdb, data_len);
18504 
18505 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18506 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18507 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
18508 	ucmd_buf.uscsi_buflen	= data_len;
18509 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18510 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18511 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
18512 	ucmd_buf.uscsi_timeout	= 60;
18513 
18514 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18515 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18516 
18517 	switch (status) {
18518 	case 0:
18519 		break;	/* Success! */
18520 	case EIO:
18521 		switch (ucmd_buf.uscsi_status) {
18522 		case STATUS_RESERVATION_CONFLICT:
18523 			status = EACCES;
18524 			break;
18525 		case STATUS_CHECK:
18526 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18527 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18528 			    KEY_ILLEGAL_REQUEST)) {
18529 				status = ENOTSUP;
18530 			}
18531 			break;
18532 		default:
18533 			break;
18534 		}
18535 		break;
18536 	default:
18537 		break;
18538 	}
18539 
18540 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
18541 
18542 	if (no_caller_buf == TRUE) {
18543 		kmem_free(data_bufp, data_len);
18544 	}
18545 
18546 	return (status);
18547 }
18548 
18549 
18550 /*
18551  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
18552  *
18553  * Description: This routine is the driver entry point for handling CD-ROM
18554  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
18555  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
18556  *		device.
18557  *
18558  *   Arguments: un  -   Pointer to soft state struct for the target.
18559  *		usr_cmd SCSI-3 reservation facility command (one of
18560  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
18561  *			SD_SCSI3_PREEMPTANDABORT)
18562  *		usr_bufp - user provided pointer register, reserve descriptor or
18563  *			preempt and abort structure (mhioc_register_t,
18564  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
18565  *
18566  * Return Code: 0   - Success
18567  *		EACCES
18568  *		ENOTSUP
18569  *		errno return code from sd_send_scsi_cmd()
18570  *
18571  *     Context: Can sleep. Does not return until command is completed.
18572  */
18573 
18574 static int
18575 sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un, uchar_t usr_cmd,
18576 	uchar_t	*usr_bufp)
18577 {
18578 	struct scsi_extended_sense	sense_buf;
18579 	union scsi_cdb		cdb;
18580 	struct uscsi_cmd	ucmd_buf;
18581 	int			status;
18582 	uchar_t			data_len = sizeof (sd_prout_t);
18583 	sd_prout_t		*prp;
18584 
18585 	ASSERT(un != NULL);
18586 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18587 	ASSERT(data_len == 24);	/* required by scsi spec */
18588 
18589 	SD_TRACE(SD_LOG_IO, un,
18590 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
18591 
18592 	if (usr_bufp == NULL) {
18593 		return (EINVAL);
18594 	}
18595 
18596 	bzero(&cdb, sizeof (cdb));
18597 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18598 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18599 	prp = kmem_zalloc(data_len, KM_SLEEP);
18600 
18601 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
18602 	cdb.cdb_opaque[1] = usr_cmd;
18603 	FORMG1COUNT(&cdb, data_len);
18604 
18605 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18606 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18607 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
18608 	ucmd_buf.uscsi_buflen	= data_len;
18609 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18610 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18611 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
18612 	ucmd_buf.uscsi_timeout	= 60;
18613 
18614 	switch (usr_cmd) {
18615 	case SD_SCSI3_REGISTER: {
18616 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
18617 
18618 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18619 		bcopy(ptr->newkey.key, prp->service_key,
18620 		    MHIOC_RESV_KEY_SIZE);
18621 		prp->aptpl = ptr->aptpl;
18622 		break;
18623 	}
18624 	case SD_SCSI3_RESERVE:
18625 	case SD_SCSI3_RELEASE: {
18626 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
18627 
18628 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18629 		prp->scope_address = BE_32(ptr->scope_specific_addr);
18630 		cdb.cdb_opaque[2] = ptr->type;
18631 		break;
18632 	}
18633 	case SD_SCSI3_PREEMPTANDABORT: {
18634 		mhioc_preemptandabort_t *ptr =
18635 		    (mhioc_preemptandabort_t *)usr_bufp;
18636 
18637 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18638 		bcopy(ptr->victim_key.key, prp->service_key,
18639 		    MHIOC_RESV_KEY_SIZE);
18640 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
18641 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
18642 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
18643 		break;
18644 	}
18645 	case SD_SCSI3_REGISTERANDIGNOREKEY:
18646 	{
18647 		mhioc_registerandignorekey_t *ptr;
18648 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
18649 		bcopy(ptr->newkey.key,
18650 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
18651 		prp->aptpl = ptr->aptpl;
18652 		break;
18653 	}
18654 	default:
18655 		ASSERT(FALSE);
18656 		break;
18657 	}
18658 
18659 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18660 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18661 
18662 	switch (status) {
18663 	case 0:
18664 		break;	/* Success! */
18665 	case EIO:
18666 		switch (ucmd_buf.uscsi_status) {
18667 		case STATUS_RESERVATION_CONFLICT:
18668 			status = EACCES;
18669 			break;
18670 		case STATUS_CHECK:
18671 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18672 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18673 			    KEY_ILLEGAL_REQUEST)) {
18674 				status = ENOTSUP;
18675 			}
18676 			break;
18677 		default:
18678 			break;
18679 		}
18680 		break;
18681 	default:
18682 		break;
18683 	}
18684 
18685 	kmem_free(prp, data_len);
18686 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
18687 	return (status);
18688 }
18689 
18690 
18691 /*
18692  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
18693  *
18694  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
18695  *
18696  *   Arguments: un - pointer to the target's soft state struct
18697  *              dkc - pointer to the callback structure
18698  *
18699  * Return Code: 0 - success
18700  *		errno-type error code
18701  *
18702  *     Context: kernel thread context only.
18703  *
18704  *  _______________________________________________________________
18705  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
18706  * |FLUSH_VOLATILE|              | operation                       |
18707  * |______________|______________|_________________________________|
18708  * | 0            | NULL         | Synchronous flush on both       |
18709  * |              |              | volatile and non-volatile cache |
18710  * |______________|______________|_________________________________|
18711  * | 1            | NULL         | Synchronous flush on volatile   |
18712  * |              |              | cache; disk drivers may suppress|
18713  * |              |              | flush if disk table indicates   |
18714  * |              |              | non-volatile cache              |
18715  * |______________|______________|_________________________________|
18716  * | 0            | !NULL        | Asynchronous flush on both      |
18717  * |              |              | volatile and non-volatile cache;|
18718  * |______________|______________|_________________________________|
18719  * | 1            | !NULL        | Asynchronous flush on volatile  |
18720  * |              |              | cache; disk drivers may suppress|
18721  * |              |              | flush if disk table indicates   |
18722  * |              |              | non-volatile cache              |
18723  * |______________|______________|_________________________________|
18724  *
18725  */
18726 
18727 static int
18728 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
18729 {
18730 	struct sd_uscsi_info	*uip;
18731 	struct uscsi_cmd	*uscmd;
18732 	union scsi_cdb		*cdb;
18733 	struct buf		*bp;
18734 	int			rval = 0;
18735 	int			is_async;
18736 
18737 	SD_TRACE(SD_LOG_IO, un,
18738 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
18739 
18740 	ASSERT(un != NULL);
18741 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18742 
18743 	if (dkc == NULL || dkc->dkc_callback == NULL) {
18744 		is_async = FALSE;
18745 	} else {
18746 		is_async = TRUE;
18747 	}
18748 
18749 	mutex_enter(SD_MUTEX(un));
18750 	/* check whether cache flush should be suppressed */
18751 	if (un->un_f_suppress_cache_flush == TRUE) {
18752 		mutex_exit(SD_MUTEX(un));
18753 		/*
18754 		 * suppress the cache flush if the device is told to do
18755 		 * so by sd.conf or disk table
18756 		 */
18757 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
18758 		    skip the cache flush since suppress_cache_flush is %d!\n",
18759 		    un->un_f_suppress_cache_flush);
18760 
18761 		if (is_async == TRUE) {
18762 			/* invoke callback for asynchronous flush */
18763 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
18764 		}
18765 		return (rval);
18766 	}
18767 	mutex_exit(SD_MUTEX(un));
18768 
18769 	/*
18770 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
18771 	 * set properly
18772 	 */
18773 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
18774 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
18775 
18776 	mutex_enter(SD_MUTEX(un));
18777 	if (dkc != NULL && un->un_f_sync_nv_supported &&
18778 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
18779 		/*
18780 		 * if the device supports SYNC_NV bit, turn on
18781 		 * the SYNC_NV bit to only flush volatile cache
18782 		 */
18783 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
18784 	}
18785 	mutex_exit(SD_MUTEX(un));
18786 
18787 	/*
18788 	 * First get some memory for the uscsi_cmd struct and cdb
18789 	 * and initialize for SYNCHRONIZE_CACHE cmd.
18790 	 */
18791 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
18792 	uscmd->uscsi_cdblen = CDB_GROUP1;
18793 	uscmd->uscsi_cdb = (caddr_t)cdb;
18794 	uscmd->uscsi_bufaddr = NULL;
18795 	uscmd->uscsi_buflen = 0;
18796 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
18797 	uscmd->uscsi_rqlen = SENSE_LENGTH;
18798 	uscmd->uscsi_rqresid = SENSE_LENGTH;
18799 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
18800 	uscmd->uscsi_timeout = sd_io_time;
18801 
18802 	/*
18803 	 * Allocate an sd_uscsi_info struct and fill it with the info
18804 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
18805 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
18806 	 * since we allocate the buf here in this function, we do not
18807 	 * need to preserve the prior contents of b_private.
18808 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
18809 	 */
18810 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
18811 	uip->ui_flags = SD_PATH_DIRECT;
18812 	uip->ui_cmdp  = uscmd;
18813 
18814 	bp = getrbuf(KM_SLEEP);
18815 	bp->b_private = uip;
18816 
18817 	/*
18818 	 * Setup buffer to carry uscsi request.
18819 	 */
18820 	bp->b_flags  = B_BUSY;
18821 	bp->b_bcount = 0;
18822 	bp->b_blkno  = 0;
18823 
18824 	if (is_async == TRUE) {
18825 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
18826 		uip->ui_dkc = *dkc;
18827 	}
18828 
18829 	bp->b_edev = SD_GET_DEV(un);
18830 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
18831 
18832 	(void) sd_uscsi_strategy(bp);
18833 
18834 	/*
18835 	 * If synchronous request, wait for completion
18836 	 * If async just return and let b_iodone callback
18837 	 * cleanup.
18838 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
18839 	 * but it was also incremented in sd_uscsi_strategy(), so
18840 	 * we should be ok.
18841 	 */
18842 	if (is_async == FALSE) {
18843 		(void) biowait(bp);
18844 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
18845 	}
18846 
18847 	return (rval);
18848 }
18849 
18850 
18851 static int
18852 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
18853 {
18854 	struct sd_uscsi_info *uip;
18855 	struct uscsi_cmd *uscmd;
18856 	uint8_t *sense_buf;
18857 	struct sd_lun *un;
18858 	int status;
18859 	union scsi_cdb *cdb;
18860 
18861 	uip = (struct sd_uscsi_info *)(bp->b_private);
18862 	ASSERT(uip != NULL);
18863 
18864 	uscmd = uip->ui_cmdp;
18865 	ASSERT(uscmd != NULL);
18866 
18867 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
18868 	ASSERT(sense_buf != NULL);
18869 
18870 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
18871 	ASSERT(un != NULL);
18872 
18873 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
18874 
18875 	status = geterror(bp);
18876 	switch (status) {
18877 	case 0:
18878 		break;	/* Success! */
18879 	case EIO:
18880 		switch (uscmd->uscsi_status) {
18881 		case STATUS_RESERVATION_CONFLICT:
18882 			/* Ignore reservation conflict */
18883 			status = 0;
18884 			goto done;
18885 
18886 		case STATUS_CHECK:
18887 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
18888 			    (scsi_sense_key(sense_buf) ==
18889 			    KEY_ILLEGAL_REQUEST)) {
18890 				/* Ignore Illegal Request error */
18891 				if (cdb->cdb_un.tag|SD_SYNC_NV_BIT) {
18892 					mutex_enter(SD_MUTEX(un));
18893 					un->un_f_sync_nv_supported = FALSE;
18894 					mutex_exit(SD_MUTEX(un));
18895 					status = 0;
18896 					SD_TRACE(SD_LOG_IO, un,
18897 					    "un_f_sync_nv_supported \
18898 					    is set to false.\n");
18899 					goto done;
18900 				}
18901 
18902 				mutex_enter(SD_MUTEX(un));
18903 				un->un_f_sync_cache_supported = FALSE;
18904 				mutex_exit(SD_MUTEX(un));
18905 				SD_TRACE(SD_LOG_IO, un,
18906 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
18907 				    un_f_sync_cache_supported set to false \
18908 				    with asc = %x, ascq = %x\n",
18909 				    scsi_sense_asc(sense_buf),
18910 				    scsi_sense_ascq(sense_buf));
18911 				status = ENOTSUP;
18912 				goto done;
18913 			}
18914 			break;
18915 		default:
18916 			break;
18917 		}
18918 		/* FALLTHRU */
18919 	default:
18920 		/*
18921 		 * Don't log an error message if this device
18922 		 * has removable media.
18923 		 */
18924 		if (!un->un_f_has_removable_media) {
18925 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18926 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
18927 		}
18928 		break;
18929 	}
18930 
18931 done:
18932 	if (uip->ui_dkc.dkc_callback != NULL) {
18933 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
18934 	}
18935 
18936 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
18937 	freerbuf(bp);
18938 	kmem_free(uip, sizeof (struct sd_uscsi_info));
18939 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
18940 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
18941 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
18942 
18943 	return (status);
18944 }
18945 
18946 
18947 /*
18948  *    Function: sd_send_scsi_GET_CONFIGURATION
18949  *
18950  * Description: Issues the get configuration command to the device.
18951  *		Called from sd_check_for_writable_cd & sd_get_media_info
18952  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
18953  *   Arguments: un
18954  *		ucmdbuf
18955  *		rqbuf
18956  *		rqbuflen
18957  *		bufaddr
18958  *		buflen
18959  *		path_flag
18960  *
18961  * Return Code: 0   - Success
18962  *		errno return code from sd_send_scsi_cmd()
18963  *
18964  *     Context: Can sleep. Does not return until command is completed.
18965  *
18966  */
18967 
18968 static int
18969 sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un, struct uscsi_cmd *ucmdbuf,
18970 	uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
18971 	int path_flag)
18972 {
18973 	char	cdb[CDB_GROUP1];
18974 	int	status;
18975 
18976 	ASSERT(un != NULL);
18977 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18978 	ASSERT(bufaddr != NULL);
18979 	ASSERT(ucmdbuf != NULL);
18980 	ASSERT(rqbuf != NULL);
18981 
18982 	SD_TRACE(SD_LOG_IO, un,
18983 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
18984 
18985 	bzero(cdb, sizeof (cdb));
18986 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
18987 	bzero(rqbuf, rqbuflen);
18988 	bzero(bufaddr, buflen);
18989 
18990 	/*
18991 	 * Set up cdb field for the get configuration command.
18992 	 */
18993 	cdb[0] = SCMD_GET_CONFIGURATION;
18994 	cdb[1] = 0x02;  /* Requested Type */
18995 	cdb[8] = SD_PROFILE_HEADER_LEN;
18996 	ucmdbuf->uscsi_cdb = cdb;
18997 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
18998 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
18999 	ucmdbuf->uscsi_buflen = buflen;
19000 	ucmdbuf->uscsi_timeout = sd_io_time;
19001 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
19002 	ucmdbuf->uscsi_rqlen = rqbuflen;
19003 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
19004 
19005 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, FKIOCTL,
19006 	    UIO_SYSSPACE, path_flag);
19007 
19008 	switch (status) {
19009 	case 0:
19010 		break;  /* Success! */
19011 	case EIO:
19012 		switch (ucmdbuf->uscsi_status) {
19013 		case STATUS_RESERVATION_CONFLICT:
19014 			status = EACCES;
19015 			break;
19016 		default:
19017 			break;
19018 		}
19019 		break;
19020 	default:
19021 		break;
19022 	}
19023 
19024 	if (status == 0) {
19025 		SD_DUMP_MEMORY(un, SD_LOG_IO,
19026 		    "sd_send_scsi_GET_CONFIGURATION: data",
19027 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
19028 	}
19029 
19030 	SD_TRACE(SD_LOG_IO, un,
19031 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
19032 
19033 	return (status);
19034 }
19035 
19036 /*
19037  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
19038  *
19039  * Description: Issues the get configuration command to the device to
19040  *              retrieve a specific feature. Called from
19041  *		sd_check_for_writable_cd & sd_set_mmc_caps.
19042  *   Arguments: un
19043  *              ucmdbuf
19044  *              rqbuf
19045  *              rqbuflen
19046  *              bufaddr
19047  *              buflen
19048  *		feature
19049  *
19050  * Return Code: 0   - Success
19051  *              errno return code from sd_send_scsi_cmd()
19052  *
19053  *     Context: Can sleep. Does not return until command is completed.
19054  *
19055  */
19056 static int
19057 sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
19058 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
19059 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag)
19060 {
19061 	char    cdb[CDB_GROUP1];
19062 	int	status;
19063 
19064 	ASSERT(un != NULL);
19065 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19066 	ASSERT(bufaddr != NULL);
19067 	ASSERT(ucmdbuf != NULL);
19068 	ASSERT(rqbuf != NULL);
19069 
19070 	SD_TRACE(SD_LOG_IO, un,
19071 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
19072 
19073 	bzero(cdb, sizeof (cdb));
19074 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
19075 	bzero(rqbuf, rqbuflen);
19076 	bzero(bufaddr, buflen);
19077 
19078 	/*
19079 	 * Set up cdb field for the get configuration command.
19080 	 */
19081 	cdb[0] = SCMD_GET_CONFIGURATION;
19082 	cdb[1] = 0x02;  /* Requested Type */
19083 	cdb[3] = feature;
19084 	cdb[8] = buflen;
19085 	ucmdbuf->uscsi_cdb = cdb;
19086 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
19087 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
19088 	ucmdbuf->uscsi_buflen = buflen;
19089 	ucmdbuf->uscsi_timeout = sd_io_time;
19090 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
19091 	ucmdbuf->uscsi_rqlen = rqbuflen;
19092 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
19093 
19094 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, FKIOCTL,
19095 	    UIO_SYSSPACE, path_flag);
19096 
19097 	switch (status) {
19098 	case 0:
19099 		break;  /* Success! */
19100 	case EIO:
19101 		switch (ucmdbuf->uscsi_status) {
19102 		case STATUS_RESERVATION_CONFLICT:
19103 			status = EACCES;
19104 			break;
19105 		default:
19106 			break;
19107 		}
19108 		break;
19109 	default:
19110 		break;
19111 	}
19112 
19113 	if (status == 0) {
19114 		SD_DUMP_MEMORY(un, SD_LOG_IO,
19115 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
19116 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
19117 	}
19118 
19119 	SD_TRACE(SD_LOG_IO, un,
19120 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
19121 
19122 	return (status);
19123 }
19124 
19125 
19126 /*
19127  *    Function: sd_send_scsi_MODE_SENSE
19128  *
19129  * Description: Utility function for issuing a scsi MODE SENSE command.
19130  *		Note: This routine uses a consistent implementation for Group0,
19131  *		Group1, and Group2 commands across all platforms. ATAPI devices
19132  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
19133  *
19134  *   Arguments: un - pointer to the softstate struct for the target.
19135  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
19136  *			  CDB_GROUP[1|2] (10 byte).
19137  *		bufaddr - buffer for page data retrieved from the target.
19138  *		buflen - size of page to be retrieved.
19139  *		page_code - page code of data to be retrieved from the target.
19140  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19141  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19142  *			to use the USCSI "direct" chain and bypass the normal
19143  *			command waitq.
19144  *
19145  * Return Code: 0   - Success
19146  *		errno return code from sd_send_scsi_cmd()
19147  *
19148  *     Context: Can sleep. Does not return until command is completed.
19149  */
19150 
19151 static int
19152 sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
19153 	size_t buflen,  uchar_t page_code, int path_flag)
19154 {
19155 	struct	scsi_extended_sense	sense_buf;
19156 	union scsi_cdb		cdb;
19157 	struct uscsi_cmd	ucmd_buf;
19158 	int			status;
19159 	int			headlen;
19160 
19161 	ASSERT(un != NULL);
19162 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19163 	ASSERT(bufaddr != NULL);
19164 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
19165 	    (cdbsize == CDB_GROUP2));
19166 
19167 	SD_TRACE(SD_LOG_IO, un,
19168 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
19169 
19170 	bzero(&cdb, sizeof (cdb));
19171 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19172 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19173 	bzero(bufaddr, buflen);
19174 
19175 	if (cdbsize == CDB_GROUP0) {
19176 		cdb.scc_cmd = SCMD_MODE_SENSE;
19177 		cdb.cdb_opaque[2] = page_code;
19178 		FORMG0COUNT(&cdb, buflen);
19179 		headlen = MODE_HEADER_LENGTH;
19180 	} else {
19181 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
19182 		cdb.cdb_opaque[2] = page_code;
19183 		FORMG1COUNT(&cdb, buflen);
19184 		headlen = MODE_HEADER_LENGTH_GRP2;
19185 	}
19186 
19187 	ASSERT(headlen <= buflen);
19188 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19189 
19190 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19191 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19192 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19193 	ucmd_buf.uscsi_buflen	= buflen;
19194 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19195 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19196 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19197 	ucmd_buf.uscsi_timeout	= 60;
19198 
19199 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19200 	    UIO_SYSSPACE, path_flag);
19201 
19202 	switch (status) {
19203 	case 0:
19204 		/*
19205 		 * sr_check_wp() uses 0x3f page code and check the header of
19206 		 * mode page to determine if target device is write-protected.
19207 		 * But some USB devices return 0 bytes for 0x3f page code. For
19208 		 * this case, make sure that mode page header is returned at
19209 		 * least.
19210 		 */
19211 		if (buflen - ucmd_buf.uscsi_resid <  headlen)
19212 			status = EIO;
19213 		break;	/* Success! */
19214 	case EIO:
19215 		switch (ucmd_buf.uscsi_status) {
19216 		case STATUS_RESERVATION_CONFLICT:
19217 			status = EACCES;
19218 			break;
19219 		default:
19220 			break;
19221 		}
19222 		break;
19223 	default:
19224 		break;
19225 	}
19226 
19227 	if (status == 0) {
19228 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
19229 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19230 	}
19231 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
19232 
19233 	return (status);
19234 }
19235 
19236 
19237 /*
19238  *    Function: sd_send_scsi_MODE_SELECT
19239  *
19240  * Description: Utility function for issuing a scsi MODE SELECT command.
19241  *		Note: This routine uses a consistent implementation for Group0,
19242  *		Group1, and Group2 commands across all platforms. ATAPI devices
19243  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
19244  *
19245  *   Arguments: un - pointer to the softstate struct for the target.
19246  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
19247  *			  CDB_GROUP[1|2] (10 byte).
19248  *		bufaddr - buffer for page data retrieved from the target.
19249  *		buflen - size of page to be retrieved.
19250  *		save_page - boolean to determin if SP bit should be set.
19251  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19252  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19253  *			to use the USCSI "direct" chain and bypass the normal
19254  *			command waitq.
19255  *
19256  * Return Code: 0   - Success
19257  *		errno return code from sd_send_scsi_cmd()
19258  *
19259  *     Context: Can sleep. Does not return until command is completed.
19260  */
19261 
19262 static int
19263 sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
19264 	size_t buflen,  uchar_t save_page, int path_flag)
19265 {
19266 	struct	scsi_extended_sense	sense_buf;
19267 	union scsi_cdb		cdb;
19268 	struct uscsi_cmd	ucmd_buf;
19269 	int			status;
19270 
19271 	ASSERT(un != NULL);
19272 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19273 	ASSERT(bufaddr != NULL);
19274 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
19275 	    (cdbsize == CDB_GROUP2));
19276 
19277 	SD_TRACE(SD_LOG_IO, un,
19278 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
19279 
19280 	bzero(&cdb, sizeof (cdb));
19281 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19282 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19283 
19284 	/* Set the PF bit for many third party drives */
19285 	cdb.cdb_opaque[1] = 0x10;
19286 
19287 	/* Set the savepage(SP) bit if given */
19288 	if (save_page == SD_SAVE_PAGE) {
19289 		cdb.cdb_opaque[1] |= 0x01;
19290 	}
19291 
19292 	if (cdbsize == CDB_GROUP0) {
19293 		cdb.scc_cmd = SCMD_MODE_SELECT;
19294 		FORMG0COUNT(&cdb, buflen);
19295 	} else {
19296 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
19297 		FORMG1COUNT(&cdb, buflen);
19298 	}
19299 
19300 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19301 
19302 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19303 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19304 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19305 	ucmd_buf.uscsi_buflen	= buflen;
19306 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19307 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19308 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
19309 	ucmd_buf.uscsi_timeout	= 60;
19310 
19311 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19312 	    UIO_SYSSPACE, path_flag);
19313 
19314 	switch (status) {
19315 	case 0:
19316 		break;	/* Success! */
19317 	case EIO:
19318 		switch (ucmd_buf.uscsi_status) {
19319 		case STATUS_RESERVATION_CONFLICT:
19320 			status = EACCES;
19321 			break;
19322 		default:
19323 			break;
19324 		}
19325 		break;
19326 	default:
19327 		break;
19328 	}
19329 
19330 	if (status == 0) {
19331 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
19332 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19333 	}
19334 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
19335 
19336 	return (status);
19337 }
19338 
19339 
19340 /*
19341  *    Function: sd_send_scsi_RDWR
19342  *
19343  * Description: Issue a scsi READ or WRITE command with the given parameters.
19344  *
19345  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19346  *		cmd:	 SCMD_READ or SCMD_WRITE
19347  *		bufaddr: Address of caller's buffer to receive the RDWR data
19348  *		buflen:  Length of caller's buffer receive the RDWR data.
19349  *		start_block: Block number for the start of the RDWR operation.
19350  *			 (Assumes target-native block size.)
19351  *		residp:  Pointer to variable to receive the redisual of the
19352  *			 RDWR operation (may be NULL of no residual requested).
19353  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19354  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19355  *			to use the USCSI "direct" chain and bypass the normal
19356  *			command waitq.
19357  *
19358  * Return Code: 0   - Success
19359  *		errno return code from sd_send_scsi_cmd()
19360  *
19361  *     Context: Can sleep. Does not return until command is completed.
19362  */
19363 
19364 static int
19365 sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
19366 	size_t buflen, daddr_t start_block, int path_flag)
19367 {
19368 	struct	scsi_extended_sense	sense_buf;
19369 	union scsi_cdb		cdb;
19370 	struct uscsi_cmd	ucmd_buf;
19371 	uint32_t		block_count;
19372 	int			status;
19373 	int			cdbsize;
19374 	uchar_t			flag;
19375 
19376 	ASSERT(un != NULL);
19377 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19378 	ASSERT(bufaddr != NULL);
19379 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
19380 
19381 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
19382 
19383 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
19384 		return (EINVAL);
19385 	}
19386 
19387 	mutex_enter(SD_MUTEX(un));
19388 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
19389 	mutex_exit(SD_MUTEX(un));
19390 
19391 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
19392 
19393 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
19394 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
19395 	    bufaddr, buflen, start_block, block_count);
19396 
19397 	bzero(&cdb, sizeof (cdb));
19398 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19399 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19400 
19401 	/* Compute CDB size to use */
19402 	if (start_block > 0xffffffff)
19403 		cdbsize = CDB_GROUP4;
19404 	else if ((start_block & 0xFFE00000) ||
19405 	    (un->un_f_cfg_is_atapi == TRUE))
19406 		cdbsize = CDB_GROUP1;
19407 	else
19408 		cdbsize = CDB_GROUP0;
19409 
19410 	switch (cdbsize) {
19411 	case CDB_GROUP0:	/* 6-byte CDBs */
19412 		cdb.scc_cmd = cmd;
19413 		FORMG0ADDR(&cdb, start_block);
19414 		FORMG0COUNT(&cdb, block_count);
19415 		break;
19416 	case CDB_GROUP1:	/* 10-byte CDBs */
19417 		cdb.scc_cmd = cmd | SCMD_GROUP1;
19418 		FORMG1ADDR(&cdb, start_block);
19419 		FORMG1COUNT(&cdb, block_count);
19420 		break;
19421 	case CDB_GROUP4:	/* 16-byte CDBs */
19422 		cdb.scc_cmd = cmd | SCMD_GROUP4;
19423 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
19424 		FORMG4COUNT(&cdb, block_count);
19425 		break;
19426 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
19427 	default:
19428 		/* All others reserved */
19429 		return (EINVAL);
19430 	}
19431 
19432 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
19433 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19434 
19435 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19436 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19437 	ucmd_buf.uscsi_bufaddr	= bufaddr;
19438 	ucmd_buf.uscsi_buflen	= buflen;
19439 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19440 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19441 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
19442 	ucmd_buf.uscsi_timeout	= 60;
19443 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19444 	    UIO_SYSSPACE, path_flag);
19445 	switch (status) {
19446 	case 0:
19447 		break;	/* Success! */
19448 	case EIO:
19449 		switch (ucmd_buf.uscsi_status) {
19450 		case STATUS_RESERVATION_CONFLICT:
19451 			status = EACCES;
19452 			break;
19453 		default:
19454 			break;
19455 		}
19456 		break;
19457 	default:
19458 		break;
19459 	}
19460 
19461 	if (status == 0) {
19462 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
19463 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19464 	}
19465 
19466 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
19467 
19468 	return (status);
19469 }
19470 
19471 
19472 /*
19473  *    Function: sd_send_scsi_LOG_SENSE
19474  *
19475  * Description: Issue a scsi LOG_SENSE command with the given parameters.
19476  *
19477  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19478  *
19479  * Return Code: 0   - Success
19480  *		errno return code from sd_send_scsi_cmd()
19481  *
19482  *     Context: Can sleep. Does not return until command is completed.
19483  */
19484 
19485 static int
19486 sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr, uint16_t buflen,
19487 	uchar_t page_code, uchar_t page_control, uint16_t param_ptr,
19488 	int path_flag)
19489 
19490 {
19491 	struct	scsi_extended_sense	sense_buf;
19492 	union scsi_cdb		cdb;
19493 	struct uscsi_cmd	ucmd_buf;
19494 	int			status;
19495 
19496 	ASSERT(un != NULL);
19497 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19498 
19499 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
19500 
19501 	bzero(&cdb, sizeof (cdb));
19502 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19503 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19504 
19505 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
19506 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
19507 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
19508 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
19509 	FORMG1COUNT(&cdb, buflen);
19510 
19511 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19512 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19513 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19514 	ucmd_buf.uscsi_buflen	= buflen;
19515 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19516 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19517 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19518 	ucmd_buf.uscsi_timeout	= 60;
19519 
19520 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19521 	    UIO_SYSSPACE, path_flag);
19522 
19523 	switch (status) {
19524 	case 0:
19525 		break;
19526 	case EIO:
19527 		switch (ucmd_buf.uscsi_status) {
19528 		case STATUS_RESERVATION_CONFLICT:
19529 			status = EACCES;
19530 			break;
19531 		case STATUS_CHECK:
19532 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19533 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
19534 				KEY_ILLEGAL_REQUEST) &&
19535 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
19536 				/*
19537 				 * ASC 0x24: INVALID FIELD IN CDB
19538 				 */
19539 				switch (page_code) {
19540 				case START_STOP_CYCLE_PAGE:
19541 					/*
19542 					 * The start stop cycle counter is
19543 					 * implemented as page 0x31 in earlier
19544 					 * generation disks. In new generation
19545 					 * disks the start stop cycle counter is
19546 					 * implemented as page 0xE. To properly
19547 					 * handle this case if an attempt for
19548 					 * log page 0xE is made and fails we
19549 					 * will try again using page 0x31.
19550 					 *
19551 					 * Network storage BU committed to
19552 					 * maintain the page 0x31 for this
19553 					 * purpose and will not have any other
19554 					 * page implemented with page code 0x31
19555 					 * until all disks transition to the
19556 					 * standard page.
19557 					 */
19558 					mutex_enter(SD_MUTEX(un));
19559 					un->un_start_stop_cycle_page =
19560 					    START_STOP_CYCLE_VU_PAGE;
19561 					cdb.cdb_opaque[2] =
19562 					    (char)(page_control << 6) |
19563 					    un->un_start_stop_cycle_page;
19564 					mutex_exit(SD_MUTEX(un));
19565 					status = sd_send_scsi_cmd(
19566 					    SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19567 					    UIO_SYSSPACE, path_flag);
19568 
19569 					break;
19570 				case TEMPERATURE_PAGE:
19571 					status = ENOTTY;
19572 					break;
19573 				default:
19574 					break;
19575 				}
19576 			}
19577 			break;
19578 		default:
19579 			break;
19580 		}
19581 		break;
19582 	default:
19583 		break;
19584 	}
19585 
19586 	if (status == 0) {
19587 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
19588 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19589 	}
19590 
19591 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
19592 
19593 	return (status);
19594 }
19595 
19596 
19597 /*
19598  *    Function: sdioctl
19599  *
19600  * Description: Driver's ioctl(9e) entry point function.
19601  *
19602  *   Arguments: dev     - device number
19603  *		cmd     - ioctl operation to be performed
19604  *		arg     - user argument, contains data to be set or reference
19605  *			  parameter for get
19606  *		flag    - bit flag, indicating open settings, 32/64 bit type
19607  *		cred_p  - user credential pointer
19608  *		rval_p  - calling process return value (OPT)
19609  *
19610  * Return Code: EINVAL
19611  *		ENOTTY
19612  *		ENXIO
19613  *		EIO
19614  *		EFAULT
19615  *		ENOTSUP
19616  *		EPERM
19617  *
19618  *     Context: Called from the device switch at normal priority.
19619  */
19620 
19621 static int
19622 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
19623 {
19624 	struct sd_lun	*un = NULL;
19625 	int		err = 0;
19626 	int		i = 0;
19627 	cred_t		*cr;
19628 	int		tmprval = EINVAL;
19629 	int 		is_valid;
19630 
19631 	/*
19632 	 * All device accesses go thru sdstrategy where we check on suspend
19633 	 * status
19634 	 */
19635 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
19636 		return (ENXIO);
19637 	}
19638 
19639 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19640 
19641 
19642 	is_valid = SD_IS_VALID_LABEL(un);
19643 
19644 	/*
19645 	 * Moved this wait from sd_uscsi_strategy to here for
19646 	 * reasons of deadlock prevention. Internal driver commands,
19647 	 * specifically those to change a devices power level, result
19648 	 * in a call to sd_uscsi_strategy.
19649 	 */
19650 	mutex_enter(SD_MUTEX(un));
19651 	while ((un->un_state == SD_STATE_SUSPENDED) ||
19652 	    (un->un_state == SD_STATE_PM_CHANGING)) {
19653 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
19654 	}
19655 	/*
19656 	 * Twiddling the counter here protects commands from now
19657 	 * through to the top of sd_uscsi_strategy. Without the
19658 	 * counter inc. a power down, for example, could get in
19659 	 * after the above check for state is made and before
19660 	 * execution gets to the top of sd_uscsi_strategy.
19661 	 * That would cause problems.
19662 	 */
19663 	un->un_ncmds_in_driver++;
19664 
19665 	if (!is_valid &&
19666 	    (flag & (FNDELAY | FNONBLOCK))) {
19667 		switch (cmd) {
19668 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
19669 		case DKIOCGVTOC:
19670 		case DKIOCGAPART:
19671 		case DKIOCPARTINFO:
19672 		case DKIOCSGEOM:
19673 		case DKIOCSAPART:
19674 		case DKIOCGETEFI:
19675 		case DKIOCPARTITION:
19676 		case DKIOCSVTOC:
19677 		case DKIOCSETEFI:
19678 		case DKIOCGMBOOT:
19679 		case DKIOCSMBOOT:
19680 		case DKIOCG_PHYGEOM:
19681 		case DKIOCG_VIRTGEOM:
19682 			/* let cmlb handle it */
19683 			goto skip_ready_valid;
19684 
19685 		case CDROMPAUSE:
19686 		case CDROMRESUME:
19687 		case CDROMPLAYMSF:
19688 		case CDROMPLAYTRKIND:
19689 		case CDROMREADTOCHDR:
19690 		case CDROMREADTOCENTRY:
19691 		case CDROMSTOP:
19692 		case CDROMSTART:
19693 		case CDROMVOLCTRL:
19694 		case CDROMSUBCHNL:
19695 		case CDROMREADMODE2:
19696 		case CDROMREADMODE1:
19697 		case CDROMREADOFFSET:
19698 		case CDROMSBLKMODE:
19699 		case CDROMGBLKMODE:
19700 		case CDROMGDRVSPEED:
19701 		case CDROMSDRVSPEED:
19702 		case CDROMCDDA:
19703 		case CDROMCDXA:
19704 		case CDROMSUBCODE:
19705 			if (!ISCD(un)) {
19706 				un->un_ncmds_in_driver--;
19707 				ASSERT(un->un_ncmds_in_driver >= 0);
19708 				mutex_exit(SD_MUTEX(un));
19709 				return (ENOTTY);
19710 			}
19711 			break;
19712 		case FDEJECT:
19713 		case DKIOCEJECT:
19714 		case CDROMEJECT:
19715 			if (!un->un_f_eject_media_supported) {
19716 				un->un_ncmds_in_driver--;
19717 				ASSERT(un->un_ncmds_in_driver >= 0);
19718 				mutex_exit(SD_MUTEX(un));
19719 				return (ENOTTY);
19720 			}
19721 			break;
19722 		case DKIOCFLUSHWRITECACHE:
19723 			mutex_exit(SD_MUTEX(un));
19724 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
19725 			if (err != 0) {
19726 				mutex_enter(SD_MUTEX(un));
19727 				un->un_ncmds_in_driver--;
19728 				ASSERT(un->un_ncmds_in_driver >= 0);
19729 				mutex_exit(SD_MUTEX(un));
19730 				return (EIO);
19731 			}
19732 			mutex_enter(SD_MUTEX(un));
19733 			/* FALLTHROUGH */
19734 		case DKIOCREMOVABLE:
19735 		case DKIOCHOTPLUGGABLE:
19736 		case DKIOCINFO:
19737 		case DKIOCGMEDIAINFO:
19738 		case MHIOCENFAILFAST:
19739 		case MHIOCSTATUS:
19740 		case MHIOCTKOWN:
19741 		case MHIOCRELEASE:
19742 		case MHIOCGRP_INKEYS:
19743 		case MHIOCGRP_INRESV:
19744 		case MHIOCGRP_REGISTER:
19745 		case MHIOCGRP_RESERVE:
19746 		case MHIOCGRP_PREEMPTANDABORT:
19747 		case MHIOCGRP_REGISTERANDIGNOREKEY:
19748 		case CDROMCLOSETRAY:
19749 		case USCSICMD:
19750 			goto skip_ready_valid;
19751 		default:
19752 			break;
19753 		}
19754 
19755 		mutex_exit(SD_MUTEX(un));
19756 		err = sd_ready_and_valid(un);
19757 		mutex_enter(SD_MUTEX(un));
19758 
19759 		if (err != SD_READY_VALID) {
19760 			switch (cmd) {
19761 			case DKIOCSTATE:
19762 			case CDROMGDRVSPEED:
19763 			case CDROMSDRVSPEED:
19764 			case FDEJECT:	/* for eject command */
19765 			case DKIOCEJECT:
19766 			case CDROMEJECT:
19767 			case DKIOCREMOVABLE:
19768 			case DKIOCHOTPLUGGABLE:
19769 				break;
19770 			default:
19771 				if (un->un_f_has_removable_media) {
19772 					err = ENXIO;
19773 				} else {
19774 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
19775 					if (err == SD_RESERVED_BY_OTHERS) {
19776 						err = EACCES;
19777 					} else {
19778 						err = EIO;
19779 					}
19780 				}
19781 				un->un_ncmds_in_driver--;
19782 				ASSERT(un->un_ncmds_in_driver >= 0);
19783 				mutex_exit(SD_MUTEX(un));
19784 				return (err);
19785 			}
19786 		}
19787 	}
19788 
19789 skip_ready_valid:
19790 	mutex_exit(SD_MUTEX(un));
19791 
19792 	switch (cmd) {
19793 	case DKIOCINFO:
19794 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
19795 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
19796 		break;
19797 
19798 	case DKIOCGMEDIAINFO:
19799 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
19800 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
19801 		break;
19802 
19803 	case DKIOCGGEOM:
19804 	case DKIOCGVTOC:
19805 	case DKIOCGAPART:
19806 	case DKIOCPARTINFO:
19807 	case DKIOCSGEOM:
19808 	case DKIOCSAPART:
19809 	case DKIOCGETEFI:
19810 	case DKIOCPARTITION:
19811 	case DKIOCSVTOC:
19812 	case DKIOCSETEFI:
19813 	case DKIOCGMBOOT:
19814 	case DKIOCSMBOOT:
19815 	case DKIOCG_PHYGEOM:
19816 	case DKIOCG_VIRTGEOM:
19817 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
19818 
19819 		/* TUR should spin up */
19820 
19821 		if (un->un_f_has_removable_media)
19822 			err = sd_send_scsi_TEST_UNIT_READY(un,
19823 			    SD_CHECK_FOR_MEDIA);
19824 		else
19825 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
19826 
19827 		if (err != 0)
19828 			break;
19829 
19830 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
19831 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
19832 
19833 		if ((err == 0) &&
19834 		    ((cmd == DKIOCSETEFI) ||
19835 		    (un->un_f_pkstats_enabled) &&
19836 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC))) {
19837 
19838 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
19839 			    (void *)SD_PATH_DIRECT);
19840 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
19841 				sd_set_pstats(un);
19842 				SD_TRACE(SD_LOG_IO_PARTITION, un,
19843 				    "sd_ioctl: un:0x%p pstats created and "
19844 				    "set\n", un);
19845 			}
19846 		}
19847 
19848 		if ((cmd == DKIOCSVTOC) ||
19849 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
19850 
19851 			mutex_enter(SD_MUTEX(un));
19852 			if (un->un_f_devid_supported &&
19853 			    (un->un_f_opt_fab_devid == TRUE)) {
19854 				if (un->un_devid == NULL) {
19855 					sd_register_devid(un, SD_DEVINFO(un),
19856 					    SD_TARGET_IS_UNRESERVED);
19857 				} else {
19858 					/*
19859 					 * The device id for this disk
19860 					 * has been fabricated. The
19861 					 * device id must be preserved
19862 					 * by writing it back out to
19863 					 * disk.
19864 					 */
19865 					if (sd_write_deviceid(un) != 0) {
19866 						ddi_devid_free(un->un_devid);
19867 						un->un_devid = NULL;
19868 					}
19869 				}
19870 			}
19871 			mutex_exit(SD_MUTEX(un));
19872 		}
19873 
19874 		break;
19875 
19876 	case DKIOCLOCK:
19877 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
19878 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
19879 		    SD_PATH_STANDARD);
19880 		break;
19881 
19882 	case DKIOCUNLOCK:
19883 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
19884 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
19885 		    SD_PATH_STANDARD);
19886 		break;
19887 
19888 	case DKIOCSTATE: {
19889 		enum dkio_state		state;
19890 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
19891 
19892 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
19893 			err = EFAULT;
19894 		} else {
19895 			err = sd_check_media(dev, state);
19896 			if (err == 0) {
19897 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
19898 				    sizeof (int), flag) != 0)
19899 					err = EFAULT;
19900 			}
19901 		}
19902 		break;
19903 	}
19904 
19905 	case DKIOCREMOVABLE:
19906 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
19907 		i = un->un_f_has_removable_media ? 1 : 0;
19908 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
19909 			err = EFAULT;
19910 		} else {
19911 			err = 0;
19912 		}
19913 		break;
19914 
19915 	case DKIOCHOTPLUGGABLE:
19916 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
19917 		i = un->un_f_is_hotpluggable ? 1 : 0;
19918 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
19919 			err = EFAULT;
19920 		} else {
19921 			err = 0;
19922 		}
19923 		break;
19924 
19925 	case DKIOCGTEMPERATURE:
19926 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
19927 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
19928 		break;
19929 
19930 	case MHIOCENFAILFAST:
19931 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
19932 		if ((err = drv_priv(cred_p)) == 0) {
19933 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
19934 		}
19935 		break;
19936 
19937 	case MHIOCTKOWN:
19938 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
19939 		if ((err = drv_priv(cred_p)) == 0) {
19940 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
19941 		}
19942 		break;
19943 
19944 	case MHIOCRELEASE:
19945 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
19946 		if ((err = drv_priv(cred_p)) == 0) {
19947 			err = sd_mhdioc_release(dev);
19948 		}
19949 		break;
19950 
19951 	case MHIOCSTATUS:
19952 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
19953 		if ((err = drv_priv(cred_p)) == 0) {
19954 			switch (sd_send_scsi_TEST_UNIT_READY(un, 0)) {
19955 			case 0:
19956 				err = 0;
19957 				break;
19958 			case EACCES:
19959 				*rval_p = 1;
19960 				err = 0;
19961 				break;
19962 			default:
19963 				err = EIO;
19964 				break;
19965 			}
19966 		}
19967 		break;
19968 
19969 	case MHIOCQRESERVE:
19970 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
19971 		if ((err = drv_priv(cred_p)) == 0) {
19972 			err = sd_reserve_release(dev, SD_RESERVE);
19973 		}
19974 		break;
19975 
19976 	case MHIOCREREGISTERDEVID:
19977 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
19978 		if (drv_priv(cred_p) == EPERM) {
19979 			err = EPERM;
19980 		} else if (!un->un_f_devid_supported) {
19981 			err = ENOTTY;
19982 		} else {
19983 			err = sd_mhdioc_register_devid(dev);
19984 		}
19985 		break;
19986 
19987 	case MHIOCGRP_INKEYS:
19988 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
19989 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
19990 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19991 				err = ENOTSUP;
19992 			} else {
19993 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
19994 				    flag);
19995 			}
19996 		}
19997 		break;
19998 
19999 	case MHIOCGRP_INRESV:
20000 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
20001 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
20002 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20003 				err = ENOTSUP;
20004 			} else {
20005 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
20006 			}
20007 		}
20008 		break;
20009 
20010 	case MHIOCGRP_REGISTER:
20011 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
20012 		if ((err = drv_priv(cred_p)) != EPERM) {
20013 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20014 				err = ENOTSUP;
20015 			} else if (arg != NULL) {
20016 				mhioc_register_t reg;
20017 				if (ddi_copyin((void *)arg, &reg,
20018 				    sizeof (mhioc_register_t), flag) != 0) {
20019 					err = EFAULT;
20020 				} else {
20021 					err =
20022 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20023 					    un, SD_SCSI3_REGISTER,
20024 					    (uchar_t *)&reg);
20025 				}
20026 			}
20027 		}
20028 		break;
20029 
20030 	case MHIOCGRP_RESERVE:
20031 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
20032 		if ((err = drv_priv(cred_p)) != EPERM) {
20033 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20034 				err = ENOTSUP;
20035 			} else if (arg != NULL) {
20036 				mhioc_resv_desc_t resv_desc;
20037 				if (ddi_copyin((void *)arg, &resv_desc,
20038 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
20039 					err = EFAULT;
20040 				} else {
20041 					err =
20042 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20043 					    un, SD_SCSI3_RESERVE,
20044 					    (uchar_t *)&resv_desc);
20045 				}
20046 			}
20047 		}
20048 		break;
20049 
20050 	case MHIOCGRP_PREEMPTANDABORT:
20051 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
20052 		if ((err = drv_priv(cred_p)) != EPERM) {
20053 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20054 				err = ENOTSUP;
20055 			} else if (arg != NULL) {
20056 				mhioc_preemptandabort_t preempt_abort;
20057 				if (ddi_copyin((void *)arg, &preempt_abort,
20058 				    sizeof (mhioc_preemptandabort_t),
20059 				    flag) != 0) {
20060 					err = EFAULT;
20061 				} else {
20062 					err =
20063 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20064 					    un, SD_SCSI3_PREEMPTANDABORT,
20065 					    (uchar_t *)&preempt_abort);
20066 				}
20067 			}
20068 		}
20069 		break;
20070 
20071 	case MHIOCGRP_REGISTERANDIGNOREKEY:
20072 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
20073 		if ((err = drv_priv(cred_p)) != EPERM) {
20074 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20075 				err = ENOTSUP;
20076 			} else if (arg != NULL) {
20077 				mhioc_registerandignorekey_t r_and_i;
20078 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
20079 				    sizeof (mhioc_registerandignorekey_t),
20080 				    flag) != 0) {
20081 					err = EFAULT;
20082 				} else {
20083 					err =
20084 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20085 					    un, SD_SCSI3_REGISTERANDIGNOREKEY,
20086 					    (uchar_t *)&r_and_i);
20087 				}
20088 			}
20089 		}
20090 		break;
20091 
20092 	case USCSICMD:
20093 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
20094 		cr = ddi_get_cred();
20095 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
20096 			err = EPERM;
20097 		} else {
20098 			enum uio_seg	uioseg;
20099 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
20100 			    UIO_USERSPACE;
20101 			if (un->un_f_format_in_progress == TRUE) {
20102 				err = EAGAIN;
20103 				break;
20104 			}
20105 			err = sd_send_scsi_cmd(dev, (struct uscsi_cmd *)arg,
20106 			    flag, uioseg, SD_PATH_STANDARD);
20107 		}
20108 		break;
20109 
20110 	case CDROMPAUSE:
20111 	case CDROMRESUME:
20112 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
20113 		if (!ISCD(un)) {
20114 			err = ENOTTY;
20115 		} else {
20116 			err = sr_pause_resume(dev, cmd);
20117 		}
20118 		break;
20119 
20120 	case CDROMPLAYMSF:
20121 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
20122 		if (!ISCD(un)) {
20123 			err = ENOTTY;
20124 		} else {
20125 			err = sr_play_msf(dev, (caddr_t)arg, flag);
20126 		}
20127 		break;
20128 
20129 	case CDROMPLAYTRKIND:
20130 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
20131 #if defined(__i386) || defined(__amd64)
20132 		/*
20133 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
20134 		 */
20135 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
20136 #else
20137 		if (!ISCD(un)) {
20138 #endif
20139 			err = ENOTTY;
20140 		} else {
20141 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
20142 		}
20143 		break;
20144 
20145 	case CDROMREADTOCHDR:
20146 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
20147 		if (!ISCD(un)) {
20148 			err = ENOTTY;
20149 		} else {
20150 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
20151 		}
20152 		break;
20153 
20154 	case CDROMREADTOCENTRY:
20155 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
20156 		if (!ISCD(un)) {
20157 			err = ENOTTY;
20158 		} else {
20159 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
20160 		}
20161 		break;
20162 
20163 	case CDROMSTOP:
20164 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
20165 		if (!ISCD(un)) {
20166 			err = ENOTTY;
20167 		} else {
20168 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_STOP,
20169 			    SD_PATH_STANDARD);
20170 		}
20171 		break;
20172 
20173 	case CDROMSTART:
20174 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
20175 		if (!ISCD(un)) {
20176 			err = ENOTTY;
20177 		} else {
20178 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
20179 			    SD_PATH_STANDARD);
20180 		}
20181 		break;
20182 
20183 	case CDROMCLOSETRAY:
20184 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
20185 		if (!ISCD(un)) {
20186 			err = ENOTTY;
20187 		} else {
20188 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_CLOSE,
20189 			    SD_PATH_STANDARD);
20190 		}
20191 		break;
20192 
20193 	case FDEJECT:	/* for eject command */
20194 	case DKIOCEJECT:
20195 	case CDROMEJECT:
20196 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
20197 		if (!un->un_f_eject_media_supported) {
20198 			err = ENOTTY;
20199 		} else {
20200 			err = sr_eject(dev);
20201 		}
20202 		break;
20203 
20204 	case CDROMVOLCTRL:
20205 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
20206 		if (!ISCD(un)) {
20207 			err = ENOTTY;
20208 		} else {
20209 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
20210 		}
20211 		break;
20212 
20213 	case CDROMSUBCHNL:
20214 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
20215 		if (!ISCD(un)) {
20216 			err = ENOTTY;
20217 		} else {
20218 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
20219 		}
20220 		break;
20221 
20222 	case CDROMREADMODE2:
20223 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
20224 		if (!ISCD(un)) {
20225 			err = ENOTTY;
20226 		} else if (un->un_f_cfg_is_atapi == TRUE) {
20227 			/*
20228 			 * If the drive supports READ CD, use that instead of
20229 			 * switching the LBA size via a MODE SELECT
20230 			 * Block Descriptor
20231 			 */
20232 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
20233 		} else {
20234 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
20235 		}
20236 		break;
20237 
20238 	case CDROMREADMODE1:
20239 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
20240 		if (!ISCD(un)) {
20241 			err = ENOTTY;
20242 		} else {
20243 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
20244 		}
20245 		break;
20246 
20247 	case CDROMREADOFFSET:
20248 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
20249 		if (!ISCD(un)) {
20250 			err = ENOTTY;
20251 		} else {
20252 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
20253 			    flag);
20254 		}
20255 		break;
20256 
20257 	case CDROMSBLKMODE:
20258 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
20259 		/*
20260 		 * There is no means of changing block size in case of atapi
20261 		 * drives, thus return ENOTTY if drive type is atapi
20262 		 */
20263 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
20264 			err = ENOTTY;
20265 		} else if (un->un_f_mmc_cap == TRUE) {
20266 
20267 			/*
20268 			 * MMC Devices do not support changing the
20269 			 * logical block size
20270 			 *
20271 			 * Note: EINVAL is being returned instead of ENOTTY to
20272 			 * maintain consistancy with the original mmc
20273 			 * driver update.
20274 			 */
20275 			err = EINVAL;
20276 		} else {
20277 			mutex_enter(SD_MUTEX(un));
20278 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
20279 			    (un->un_ncmds_in_transport > 0)) {
20280 				mutex_exit(SD_MUTEX(un));
20281 				err = EINVAL;
20282 			} else {
20283 				mutex_exit(SD_MUTEX(un));
20284 				err = sr_change_blkmode(dev, cmd, arg, flag);
20285 			}
20286 		}
20287 		break;
20288 
20289 	case CDROMGBLKMODE:
20290 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
20291 		if (!ISCD(un)) {
20292 			err = ENOTTY;
20293 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
20294 		    (un->un_f_blockcount_is_valid != FALSE)) {
20295 			/*
20296 			 * Drive is an ATAPI drive so return target block
20297 			 * size for ATAPI drives since we cannot change the
20298 			 * blocksize on ATAPI drives. Used primarily to detect
20299 			 * if an ATAPI cdrom is present.
20300 			 */
20301 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
20302 			    sizeof (int), flag) != 0) {
20303 				err = EFAULT;
20304 			} else {
20305 				err = 0;
20306 			}
20307 
20308 		} else {
20309 			/*
20310 			 * Drive supports changing block sizes via a Mode
20311 			 * Select.
20312 			 */
20313 			err = sr_change_blkmode(dev, cmd, arg, flag);
20314 		}
20315 		break;
20316 
20317 	case CDROMGDRVSPEED:
20318 	case CDROMSDRVSPEED:
20319 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
20320 		if (!ISCD(un)) {
20321 			err = ENOTTY;
20322 		} else if (un->un_f_mmc_cap == TRUE) {
20323 			/*
20324 			 * Note: In the future the driver implementation
20325 			 * for getting and
20326 			 * setting cd speed should entail:
20327 			 * 1) If non-mmc try the Toshiba mode page
20328 			 *    (sr_change_speed)
20329 			 * 2) If mmc but no support for Real Time Streaming try
20330 			 *    the SET CD SPEED (0xBB) command
20331 			 *   (sr_atapi_change_speed)
20332 			 * 3) If mmc and support for Real Time Streaming
20333 			 *    try the GET PERFORMANCE and SET STREAMING
20334 			 *    commands (not yet implemented, 4380808)
20335 			 */
20336 			/*
20337 			 * As per recent MMC spec, CD-ROM speed is variable
20338 			 * and changes with LBA. Since there is no such
20339 			 * things as drive speed now, fail this ioctl.
20340 			 *
20341 			 * Note: EINVAL is returned for consistancy of original
20342 			 * implementation which included support for getting
20343 			 * the drive speed of mmc devices but not setting
20344 			 * the drive speed. Thus EINVAL would be returned
20345 			 * if a set request was made for an mmc device.
20346 			 * We no longer support get or set speed for
20347 			 * mmc but need to remain consistent with regard
20348 			 * to the error code returned.
20349 			 */
20350 			err = EINVAL;
20351 		} else if (un->un_f_cfg_is_atapi == TRUE) {
20352 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
20353 		} else {
20354 			err = sr_change_speed(dev, cmd, arg, flag);
20355 		}
20356 		break;
20357 
20358 	case CDROMCDDA:
20359 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
20360 		if (!ISCD(un)) {
20361 			err = ENOTTY;
20362 		} else {
20363 			err = sr_read_cdda(dev, (void *)arg, flag);
20364 		}
20365 		break;
20366 
20367 	case CDROMCDXA:
20368 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
20369 		if (!ISCD(un)) {
20370 			err = ENOTTY;
20371 		} else {
20372 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
20373 		}
20374 		break;
20375 
20376 	case CDROMSUBCODE:
20377 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
20378 		if (!ISCD(un)) {
20379 			err = ENOTTY;
20380 		} else {
20381 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
20382 		}
20383 		break;
20384 
20385 
20386 #ifdef SDDEBUG
20387 /* RESET/ABORTS testing ioctls */
20388 	case DKIOCRESET: {
20389 		int	reset_level;
20390 
20391 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
20392 			err = EFAULT;
20393 		} else {
20394 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
20395 			    "reset_level = 0x%lx\n", reset_level);
20396 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
20397 				err = 0;
20398 			} else {
20399 				err = EIO;
20400 			}
20401 		}
20402 		break;
20403 	}
20404 
20405 	case DKIOCABORT:
20406 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
20407 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
20408 			err = 0;
20409 		} else {
20410 			err = EIO;
20411 		}
20412 		break;
20413 #endif
20414 
20415 #ifdef SD_FAULT_INJECTION
20416 /* SDIOC FaultInjection testing ioctls */
20417 	case SDIOCSTART:
20418 	case SDIOCSTOP:
20419 	case SDIOCINSERTPKT:
20420 	case SDIOCINSERTXB:
20421 	case SDIOCINSERTUN:
20422 	case SDIOCINSERTARQ:
20423 	case SDIOCPUSH:
20424 	case SDIOCRETRIEVE:
20425 	case SDIOCRUN:
20426 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
20427 		    "SDIOC detected cmd:0x%X:\n", cmd);
20428 		/* call error generator */
20429 		sd_faultinjection_ioctl(cmd, arg, un);
20430 		err = 0;
20431 		break;
20432 
20433 #endif /* SD_FAULT_INJECTION */
20434 
20435 	case DKIOCFLUSHWRITECACHE:
20436 		{
20437 			struct dk_callback *dkc = (struct dk_callback *)arg;
20438 
20439 			mutex_enter(SD_MUTEX(un));
20440 			if (!un->un_f_sync_cache_supported ||
20441 			    !un->un_f_write_cache_enabled) {
20442 				err = un->un_f_sync_cache_supported ?
20443 				    0 : ENOTSUP;
20444 				mutex_exit(SD_MUTEX(un));
20445 				if ((flag & FKIOCTL) && dkc != NULL &&
20446 				    dkc->dkc_callback != NULL) {
20447 					(*dkc->dkc_callback)(dkc->dkc_cookie,
20448 					    err);
20449 					/*
20450 					 * Did callback and reported error.
20451 					 * Since we did a callback, ioctl
20452 					 * should return 0.
20453 					 */
20454 					err = 0;
20455 				}
20456 				break;
20457 			}
20458 			mutex_exit(SD_MUTEX(un));
20459 
20460 			if ((flag & FKIOCTL) && dkc != NULL &&
20461 			    dkc->dkc_callback != NULL) {
20462 				/* async SYNC CACHE request */
20463 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
20464 			} else {
20465 				/* synchronous SYNC CACHE request */
20466 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
20467 			}
20468 		}
20469 		break;
20470 
20471 	case DKIOCGETWCE: {
20472 
20473 		int wce;
20474 
20475 		if ((err = sd_get_write_cache_enabled(un, &wce)) != 0) {
20476 			break;
20477 		}
20478 
20479 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
20480 			err = EFAULT;
20481 		}
20482 		break;
20483 	}
20484 
20485 	case DKIOCSETWCE: {
20486 
20487 		int wce, sync_supported;
20488 
20489 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
20490 			err = EFAULT;
20491 			break;
20492 		}
20493 
20494 		/*
20495 		 * Synchronize multiple threads trying to enable
20496 		 * or disable the cache via the un_f_wcc_cv
20497 		 * condition variable.
20498 		 */
20499 		mutex_enter(SD_MUTEX(un));
20500 
20501 		/*
20502 		 * Don't allow the cache to be enabled if the
20503 		 * config file has it disabled.
20504 		 */
20505 		if (un->un_f_opt_disable_cache && wce) {
20506 			mutex_exit(SD_MUTEX(un));
20507 			err = EINVAL;
20508 			break;
20509 		}
20510 
20511 		/*
20512 		 * Wait for write cache change in progress
20513 		 * bit to be clear before proceeding.
20514 		 */
20515 		while (un->un_f_wcc_inprog)
20516 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
20517 
20518 		un->un_f_wcc_inprog = 1;
20519 
20520 		if (un->un_f_write_cache_enabled && wce == 0) {
20521 			/*
20522 			 * Disable the write cache.  Don't clear
20523 			 * un_f_write_cache_enabled until after
20524 			 * the mode select and flush are complete.
20525 			 */
20526 			sync_supported = un->un_f_sync_cache_supported;
20527 
20528 			/*
20529 			 * If cache flush is suppressed, we assume that the
20530 			 * controller firmware will take care of managing the
20531 			 * write cache for us: no need to explicitly
20532 			 * disable it.
20533 			 */
20534 			if (!un->un_f_suppress_cache_flush) {
20535 				mutex_exit(SD_MUTEX(un));
20536 				if ((err = sd_cache_control(un,
20537 				    SD_CACHE_NOCHANGE,
20538 				    SD_CACHE_DISABLE)) == 0 &&
20539 				    sync_supported) {
20540 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
20541 					    NULL);
20542 				}
20543 			} else {
20544 				mutex_exit(SD_MUTEX(un));
20545 			}
20546 
20547 			mutex_enter(SD_MUTEX(un));
20548 			if (err == 0) {
20549 				un->un_f_write_cache_enabled = 0;
20550 			}
20551 
20552 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
20553 			/*
20554 			 * Set un_f_write_cache_enabled first, so there is
20555 			 * no window where the cache is enabled, but the
20556 			 * bit says it isn't.
20557 			 */
20558 			un->un_f_write_cache_enabled = 1;
20559 
20560 			/*
20561 			 * If cache flush is suppressed, we assume that the
20562 			 * controller firmware will take care of managing the
20563 			 * write cache for us: no need to explicitly
20564 			 * enable it.
20565 			 */
20566 			if (!un->un_f_suppress_cache_flush) {
20567 				mutex_exit(SD_MUTEX(un));
20568 				err = sd_cache_control(un, SD_CACHE_NOCHANGE,
20569 				    SD_CACHE_ENABLE);
20570 			} else {
20571 				mutex_exit(SD_MUTEX(un));
20572 			}
20573 
20574 			mutex_enter(SD_MUTEX(un));
20575 
20576 			if (err) {
20577 				un->un_f_write_cache_enabled = 0;
20578 			}
20579 		}
20580 
20581 		un->un_f_wcc_inprog = 0;
20582 		cv_broadcast(&un->un_wcc_cv);
20583 		mutex_exit(SD_MUTEX(un));
20584 		break;
20585 	}
20586 
20587 	default:
20588 		err = ENOTTY;
20589 		break;
20590 	}
20591 	mutex_enter(SD_MUTEX(un));
20592 	un->un_ncmds_in_driver--;
20593 	ASSERT(un->un_ncmds_in_driver >= 0);
20594 	mutex_exit(SD_MUTEX(un));
20595 
20596 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
20597 	return (err);
20598 }
20599 
20600 
20601 /*
20602  *    Function: sd_dkio_ctrl_info
20603  *
20604  * Description: This routine is the driver entry point for handling controller
20605  *		information ioctl requests (DKIOCINFO).
20606  *
20607  *   Arguments: dev  - the device number
20608  *		arg  - pointer to user provided dk_cinfo structure
20609  *		       specifying the controller type and attributes.
20610  *		flag - this argument is a pass through to ddi_copyxxx()
20611  *		       directly from the mode argument of ioctl().
20612  *
20613  * Return Code: 0
20614  *		EFAULT
20615  *		ENXIO
20616  */
20617 
20618 static int
20619 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
20620 {
20621 	struct sd_lun	*un = NULL;
20622 	struct dk_cinfo	*info;
20623 	dev_info_t	*pdip;
20624 	int		lun, tgt;
20625 
20626 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20627 		return (ENXIO);
20628 	}
20629 
20630 	info = (struct dk_cinfo *)
20631 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
20632 
20633 	switch (un->un_ctype) {
20634 	case CTYPE_CDROM:
20635 		info->dki_ctype = DKC_CDROM;
20636 		break;
20637 	default:
20638 		info->dki_ctype = DKC_SCSI_CCS;
20639 		break;
20640 	}
20641 	pdip = ddi_get_parent(SD_DEVINFO(un));
20642 	info->dki_cnum = ddi_get_instance(pdip);
20643 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
20644 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
20645 	} else {
20646 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
20647 		    DK_DEVLEN - 1);
20648 	}
20649 
20650 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20651 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
20652 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20653 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
20654 
20655 	/* Unit Information */
20656 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
20657 	info->dki_slave = ((tgt << 3) | lun);
20658 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
20659 	    DK_DEVLEN - 1);
20660 	info->dki_flags = DKI_FMTVOL;
20661 	info->dki_partition = SDPART(dev);
20662 
20663 	/* Max Transfer size of this device in blocks */
20664 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
20665 	info->dki_addr = 0;
20666 	info->dki_space = 0;
20667 	info->dki_prio = 0;
20668 	info->dki_vec = 0;
20669 
20670 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
20671 		kmem_free(info, sizeof (struct dk_cinfo));
20672 		return (EFAULT);
20673 	} else {
20674 		kmem_free(info, sizeof (struct dk_cinfo));
20675 		return (0);
20676 	}
20677 }
20678 
20679 
20680 /*
20681  *    Function: sd_get_media_info
20682  *
20683  * Description: This routine is the driver entry point for handling ioctl
20684  *		requests for the media type or command set profile used by the
20685  *		drive to operate on the media (DKIOCGMEDIAINFO).
20686  *
20687  *   Arguments: dev	- the device number
20688  *		arg	- pointer to user provided dk_minfo structure
20689  *			  specifying the media type, logical block size and
20690  *			  drive capacity.
20691  *		flag	- this argument is a pass through to ddi_copyxxx()
20692  *			  directly from the mode argument of ioctl().
20693  *
20694  * Return Code: 0
20695  *		EACCESS
20696  *		EFAULT
20697  *		ENXIO
20698  *		EIO
20699  */
20700 
20701 static int
20702 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
20703 {
20704 	struct sd_lun		*un = NULL;
20705 	struct uscsi_cmd	com;
20706 	struct scsi_inquiry	*sinq;
20707 	struct dk_minfo		media_info;
20708 	u_longlong_t		media_capacity;
20709 	uint64_t		capacity;
20710 	uint_t			lbasize;
20711 	uchar_t			*out_data;
20712 	uchar_t			*rqbuf;
20713 	int			rval = 0;
20714 	int			rtn;
20715 
20716 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
20717 	    (un->un_state == SD_STATE_OFFLINE)) {
20718 		return (ENXIO);
20719 	}
20720 
20721 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info: entry\n");
20722 
20723 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
20724 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
20725 
20726 	/* Issue a TUR to determine if the drive is ready with media present */
20727 	rval = sd_send_scsi_TEST_UNIT_READY(un, SD_CHECK_FOR_MEDIA);
20728 	if (rval == ENXIO) {
20729 		goto done;
20730 	}
20731 
20732 	/* Now get configuration data */
20733 	if (ISCD(un)) {
20734 		media_info.dki_media_type = DK_CDROM;
20735 
20736 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
20737 		if (un->un_f_mmc_cap == TRUE) {
20738 			rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf,
20739 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
20740 			    SD_PATH_STANDARD);
20741 
20742 			if (rtn) {
20743 				/*
20744 				 * Failed for other than an illegal request
20745 				 * or command not supported
20746 				 */
20747 				if ((com.uscsi_status == STATUS_CHECK) &&
20748 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
20749 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
20750 					    (rqbuf[12] != 0x20)) {
20751 						rval = EIO;
20752 						goto done;
20753 					}
20754 				}
20755 			} else {
20756 				/*
20757 				 * The GET CONFIGURATION command succeeded
20758 				 * so set the media type according to the
20759 				 * returned data
20760 				 */
20761 				media_info.dki_media_type = out_data[6];
20762 				media_info.dki_media_type <<= 8;
20763 				media_info.dki_media_type |= out_data[7];
20764 			}
20765 		}
20766 	} else {
20767 		/*
20768 		 * The profile list is not available, so we attempt to identify
20769 		 * the media type based on the inquiry data
20770 		 */
20771 		sinq = un->un_sd->sd_inq;
20772 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
20773 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
20774 			/* This is a direct access device  or optical disk */
20775 			media_info.dki_media_type = DK_FIXED_DISK;
20776 
20777 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
20778 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
20779 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
20780 					media_info.dki_media_type = DK_ZIP;
20781 				} else if (
20782 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
20783 					media_info.dki_media_type = DK_JAZ;
20784 				}
20785 			}
20786 		} else {
20787 			/*
20788 			 * Not a CD, direct access or optical disk so return
20789 			 * unknown media
20790 			 */
20791 			media_info.dki_media_type = DK_UNKNOWN;
20792 		}
20793 	}
20794 
20795 	/* Now read the capacity so we can provide the lbasize and capacity */
20796 	switch (sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
20797 	    SD_PATH_DIRECT)) {
20798 	case 0:
20799 		break;
20800 	case EACCES:
20801 		rval = EACCES;
20802 		goto done;
20803 	default:
20804 		rval = EIO;
20805 		goto done;
20806 	}
20807 
20808 	media_info.dki_lbsize = lbasize;
20809 	media_capacity = capacity;
20810 
20811 	/*
20812 	 * sd_send_scsi_READ_CAPACITY() reports capacity in
20813 	 * un->un_sys_blocksize chunks. So we need to convert it into
20814 	 * cap.lbasize chunks.
20815 	 */
20816 	media_capacity *= un->un_sys_blocksize;
20817 	media_capacity /= lbasize;
20818 	media_info.dki_capacity = media_capacity;
20819 
20820 	if (ddi_copyout(&media_info, arg, sizeof (struct dk_minfo), flag)) {
20821 		rval = EFAULT;
20822 		/* Put goto. Anybody might add some code below in future */
20823 		goto done;
20824 	}
20825 done:
20826 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
20827 	kmem_free(rqbuf, SENSE_LENGTH);
20828 	return (rval);
20829 }
20830 
20831 
20832 /*
20833  *    Function: sd_check_media
20834  *
20835  * Description: This utility routine implements the functionality for the
20836  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
20837  *		driver state changes from that specified by the user
20838  *		(inserted or ejected). For example, if the user specifies
20839  *		DKIO_EJECTED and the current media state is inserted this
20840  *		routine will immediately return DKIO_INSERTED. However, if the
20841  *		current media state is not inserted the user thread will be
20842  *		blocked until the drive state changes. If DKIO_NONE is specified
20843  *		the user thread will block until a drive state change occurs.
20844  *
20845  *   Arguments: dev  - the device number
20846  *		state  - user pointer to a dkio_state, updated with the current
20847  *			drive state at return.
20848  *
20849  * Return Code: ENXIO
20850  *		EIO
20851  *		EAGAIN
20852  *		EINTR
20853  */
20854 
20855 static int
20856 sd_check_media(dev_t dev, enum dkio_state state)
20857 {
20858 	struct sd_lun		*un = NULL;
20859 	enum dkio_state		prev_state;
20860 	opaque_t		token = NULL;
20861 	int			rval = 0;
20862 
20863 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20864 		return (ENXIO);
20865 	}
20866 
20867 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
20868 
20869 	mutex_enter(SD_MUTEX(un));
20870 
20871 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
20872 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
20873 
20874 	prev_state = un->un_mediastate;
20875 
20876 	/* is there anything to do? */
20877 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
20878 		/*
20879 		 * submit the request to the scsi_watch service;
20880 		 * scsi_media_watch_cb() does the real work
20881 		 */
20882 		mutex_exit(SD_MUTEX(un));
20883 
20884 		/*
20885 		 * This change handles the case where a scsi watch request is
20886 		 * added to a device that is powered down. To accomplish this
20887 		 * we power up the device before adding the scsi watch request,
20888 		 * since the scsi watch sends a TUR directly to the device
20889 		 * which the device cannot handle if it is powered down.
20890 		 */
20891 		if (sd_pm_entry(un) != DDI_SUCCESS) {
20892 			mutex_enter(SD_MUTEX(un));
20893 			goto done;
20894 		}
20895 
20896 		token = scsi_watch_request_submit(SD_SCSI_DEVP(un),
20897 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
20898 		    (caddr_t)dev);
20899 
20900 		sd_pm_exit(un);
20901 
20902 		mutex_enter(SD_MUTEX(un));
20903 		if (token == NULL) {
20904 			rval = EAGAIN;
20905 			goto done;
20906 		}
20907 
20908 		/*
20909 		 * This is a special case IOCTL that doesn't return
20910 		 * until the media state changes. Routine sdpower
20911 		 * knows about and handles this so don't count it
20912 		 * as an active cmd in the driver, which would
20913 		 * keep the device busy to the pm framework.
20914 		 * If the count isn't decremented the device can't
20915 		 * be powered down.
20916 		 */
20917 		un->un_ncmds_in_driver--;
20918 		ASSERT(un->un_ncmds_in_driver >= 0);
20919 
20920 		/*
20921 		 * if a prior request had been made, this will be the same
20922 		 * token, as scsi_watch was designed that way.
20923 		 */
20924 		un->un_swr_token = token;
20925 		un->un_specified_mediastate = state;
20926 
20927 		/*
20928 		 * now wait for media change
20929 		 * we will not be signalled unless mediastate == state but it is
20930 		 * still better to test for this condition, since there is a
20931 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
20932 		 */
20933 		SD_TRACE(SD_LOG_COMMON, un,
20934 		    "sd_check_media: waiting for media state change\n");
20935 		while (un->un_mediastate == state) {
20936 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
20937 				SD_TRACE(SD_LOG_COMMON, un,
20938 				    "sd_check_media: waiting for media state "
20939 				    "was interrupted\n");
20940 				un->un_ncmds_in_driver++;
20941 				rval = EINTR;
20942 				goto done;
20943 			}
20944 			SD_TRACE(SD_LOG_COMMON, un,
20945 			    "sd_check_media: received signal, state=%x\n",
20946 			    un->un_mediastate);
20947 		}
20948 		/*
20949 		 * Inc the counter to indicate the device once again
20950 		 * has an active outstanding cmd.
20951 		 */
20952 		un->un_ncmds_in_driver++;
20953 	}
20954 
20955 	/* invalidate geometry */
20956 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
20957 		sr_ejected(un);
20958 	}
20959 
20960 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
20961 		uint64_t	capacity;
20962 		uint_t		lbasize;
20963 
20964 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
20965 		mutex_exit(SD_MUTEX(un));
20966 		/*
20967 		 * Since the following routines use SD_PATH_DIRECT, we must
20968 		 * call PM directly before the upcoming disk accesses. This
20969 		 * may cause the disk to be power/spin up.
20970 		 */
20971 
20972 		if (sd_pm_entry(un) == DDI_SUCCESS) {
20973 			rval = sd_send_scsi_READ_CAPACITY(un,
20974 			    &capacity,
20975 			    &lbasize, SD_PATH_DIRECT);
20976 			if (rval != 0) {
20977 				sd_pm_exit(un);
20978 				mutex_enter(SD_MUTEX(un));
20979 				goto done;
20980 			}
20981 		} else {
20982 			rval = EIO;
20983 			mutex_enter(SD_MUTEX(un));
20984 			goto done;
20985 		}
20986 		mutex_enter(SD_MUTEX(un));
20987 
20988 		sd_update_block_info(un, lbasize, capacity);
20989 
20990 		/*
20991 		 *  Check if the media in the device is writable or not
20992 		 */
20993 		if (ISCD(un))
20994 			sd_check_for_writable_cd(un, SD_PATH_DIRECT);
20995 
20996 		mutex_exit(SD_MUTEX(un));
20997 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
20998 		if ((cmlb_validate(un->un_cmlbhandle, 0,
20999 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
21000 			sd_set_pstats(un);
21001 			SD_TRACE(SD_LOG_IO_PARTITION, un,
21002 			    "sd_check_media: un:0x%p pstats created and "
21003 			    "set\n", un);
21004 		}
21005 
21006 		rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
21007 		    SD_PATH_DIRECT);
21008 		sd_pm_exit(un);
21009 
21010 		mutex_enter(SD_MUTEX(un));
21011 	}
21012 done:
21013 	un->un_f_watcht_stopped = FALSE;
21014 	if (un->un_swr_token) {
21015 		/*
21016 		 * Use of this local token and the mutex ensures that we avoid
21017 		 * some race conditions associated with terminating the
21018 		 * scsi watch.
21019 		 */
21020 		token = un->un_swr_token;
21021 		un->un_swr_token = (opaque_t)NULL;
21022 		mutex_exit(SD_MUTEX(un));
21023 		(void) scsi_watch_request_terminate(token,
21024 		    SCSI_WATCH_TERMINATE_WAIT);
21025 		mutex_enter(SD_MUTEX(un));
21026 	}
21027 
21028 	/*
21029 	 * Update the capacity kstat value, if no media previously
21030 	 * (capacity kstat is 0) and a media has been inserted
21031 	 * (un_f_blockcount_is_valid == TRUE)
21032 	 */
21033 	if (un->un_errstats) {
21034 		struct sd_errstats	*stp = NULL;
21035 
21036 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
21037 		if ((stp->sd_capacity.value.ui64 == 0) &&
21038 		    (un->un_f_blockcount_is_valid == TRUE)) {
21039 			stp->sd_capacity.value.ui64 =
21040 			    (uint64_t)((uint64_t)un->un_blockcount *
21041 			    un->un_sys_blocksize);
21042 		}
21043 	}
21044 	mutex_exit(SD_MUTEX(un));
21045 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
21046 	return (rval);
21047 }
21048 
21049 
21050 /*
21051  *    Function: sd_delayed_cv_broadcast
21052  *
21053  * Description: Delayed cv_broadcast to allow for target to recover from media
21054  *		insertion.
21055  *
21056  *   Arguments: arg - driver soft state (unit) structure
21057  */
21058 
21059 static void
21060 sd_delayed_cv_broadcast(void *arg)
21061 {
21062 	struct sd_lun *un = arg;
21063 
21064 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
21065 
21066 	mutex_enter(SD_MUTEX(un));
21067 	un->un_dcvb_timeid = NULL;
21068 	cv_broadcast(&un->un_state_cv);
21069 	mutex_exit(SD_MUTEX(un));
21070 }
21071 
21072 
21073 /*
21074  *    Function: sd_media_watch_cb
21075  *
21076  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
21077  *		routine processes the TUR sense data and updates the driver
21078  *		state if a transition has occurred. The user thread
21079  *		(sd_check_media) is then signalled.
21080  *
21081  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
21082  *			among multiple watches that share this callback function
21083  *		resultp - scsi watch facility result packet containing scsi
21084  *			  packet, status byte and sense data
21085  *
21086  * Return Code: 0 for success, -1 for failure
21087  */
21088 
21089 static int
21090 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
21091 {
21092 	struct sd_lun			*un;
21093 	struct scsi_status		*statusp = resultp->statusp;
21094 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
21095 	enum dkio_state			state = DKIO_NONE;
21096 	dev_t				dev = (dev_t)arg;
21097 	uchar_t				actual_sense_length;
21098 	uint8_t				skey, asc, ascq;
21099 
21100 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21101 		return (-1);
21102 	}
21103 	actual_sense_length = resultp->actual_sense_length;
21104 
21105 	mutex_enter(SD_MUTEX(un));
21106 	SD_TRACE(SD_LOG_COMMON, un,
21107 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
21108 	    *((char *)statusp), (void *)sensep, actual_sense_length);
21109 
21110 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
21111 		un->un_mediastate = DKIO_DEV_GONE;
21112 		cv_broadcast(&un->un_state_cv);
21113 		mutex_exit(SD_MUTEX(un));
21114 
21115 		return (0);
21116 	}
21117 
21118 	/*
21119 	 * If there was a check condition then sensep points to valid sense data
21120 	 * If status was not a check condition but a reservation or busy status
21121 	 * then the new state is DKIO_NONE
21122 	 */
21123 	if (sensep != NULL) {
21124 		skey = scsi_sense_key(sensep);
21125 		asc = scsi_sense_asc(sensep);
21126 		ascq = scsi_sense_ascq(sensep);
21127 
21128 		SD_INFO(SD_LOG_COMMON, un,
21129 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
21130 		    skey, asc, ascq);
21131 		/* This routine only uses up to 13 bytes of sense data. */
21132 		if (actual_sense_length >= 13) {
21133 			if (skey == KEY_UNIT_ATTENTION) {
21134 				if (asc == 0x28) {
21135 					state = DKIO_INSERTED;
21136 				}
21137 			} else if (skey == KEY_NOT_READY) {
21138 				/*
21139 				 * if 02/04/02  means that the host
21140 				 * should send start command. Explicitly
21141 				 * leave the media state as is
21142 				 * (inserted) as the media is inserted
21143 				 * and host has stopped device for PM
21144 				 * reasons. Upon next true read/write
21145 				 * to this media will bring the
21146 				 * device to the right state good for
21147 				 * media access.
21148 				 */
21149 				if (asc == 0x3a) {
21150 					state = DKIO_EJECTED;
21151 				} else {
21152 					/*
21153 					 * If the drive is busy with an
21154 					 * operation or long write, keep the
21155 					 * media in an inserted state.
21156 					 */
21157 
21158 					if ((asc == 0x04) &&
21159 					    ((ascq == 0x02) ||
21160 					    (ascq == 0x07) ||
21161 					    (ascq == 0x08))) {
21162 						state = DKIO_INSERTED;
21163 					}
21164 				}
21165 			} else if (skey == KEY_NO_SENSE) {
21166 				if ((asc == 0x00) && (ascq == 0x00)) {
21167 					/*
21168 					 * Sense Data 00/00/00 does not provide
21169 					 * any information about the state of
21170 					 * the media. Ignore it.
21171 					 */
21172 					mutex_exit(SD_MUTEX(un));
21173 					return (0);
21174 				}
21175 			}
21176 		}
21177 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
21178 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
21179 		state = DKIO_INSERTED;
21180 	}
21181 
21182 	SD_TRACE(SD_LOG_COMMON, un,
21183 	    "sd_media_watch_cb: state=%x, specified=%x\n",
21184 	    state, un->un_specified_mediastate);
21185 
21186 	/*
21187 	 * now signal the waiting thread if this is *not* the specified state;
21188 	 * delay the signal if the state is DKIO_INSERTED to allow the target
21189 	 * to recover
21190 	 */
21191 	if (state != un->un_specified_mediastate) {
21192 		un->un_mediastate = state;
21193 		if (state == DKIO_INSERTED) {
21194 			/*
21195 			 * delay the signal to give the drive a chance
21196 			 * to do what it apparently needs to do
21197 			 */
21198 			SD_TRACE(SD_LOG_COMMON, un,
21199 			    "sd_media_watch_cb: delayed cv_broadcast\n");
21200 			if (un->un_dcvb_timeid == NULL) {
21201 				un->un_dcvb_timeid =
21202 				    timeout(sd_delayed_cv_broadcast, un,
21203 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
21204 			}
21205 		} else {
21206 			SD_TRACE(SD_LOG_COMMON, un,
21207 			    "sd_media_watch_cb: immediate cv_broadcast\n");
21208 			cv_broadcast(&un->un_state_cv);
21209 		}
21210 	}
21211 	mutex_exit(SD_MUTEX(un));
21212 	return (0);
21213 }
21214 
21215 
21216 /*
21217  *    Function: sd_dkio_get_temp
21218  *
21219  * Description: This routine is the driver entry point for handling ioctl
21220  *		requests to get the disk temperature.
21221  *
21222  *   Arguments: dev  - the device number
21223  *		arg  - pointer to user provided dk_temperature structure.
21224  *		flag - this argument is a pass through to ddi_copyxxx()
21225  *		       directly from the mode argument of ioctl().
21226  *
21227  * Return Code: 0
21228  *		EFAULT
21229  *		ENXIO
21230  *		EAGAIN
21231  */
21232 
21233 static int
21234 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
21235 {
21236 	struct sd_lun		*un = NULL;
21237 	struct dk_temperature	*dktemp = NULL;
21238 	uchar_t			*temperature_page;
21239 	int			rval = 0;
21240 	int			path_flag = SD_PATH_STANDARD;
21241 
21242 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21243 		return (ENXIO);
21244 	}
21245 
21246 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
21247 
21248 	/* copyin the disk temp argument to get the user flags */
21249 	if (ddi_copyin((void *)arg, dktemp,
21250 	    sizeof (struct dk_temperature), flag) != 0) {
21251 		rval = EFAULT;
21252 		goto done;
21253 	}
21254 
21255 	/* Initialize the temperature to invalid. */
21256 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
21257 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
21258 
21259 	/*
21260 	 * Note: Investigate removing the "bypass pm" semantic.
21261 	 * Can we just bypass PM always?
21262 	 */
21263 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
21264 		path_flag = SD_PATH_DIRECT;
21265 		ASSERT(!mutex_owned(&un->un_pm_mutex));
21266 		mutex_enter(&un->un_pm_mutex);
21267 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
21268 			/*
21269 			 * If DKT_BYPASS_PM is set, and the drive happens to be
21270 			 * in low power mode, we can not wake it up, Need to
21271 			 * return EAGAIN.
21272 			 */
21273 			mutex_exit(&un->un_pm_mutex);
21274 			rval = EAGAIN;
21275 			goto done;
21276 		} else {
21277 			/*
21278 			 * Indicate to PM the device is busy. This is required
21279 			 * to avoid a race - i.e. the ioctl is issuing a
21280 			 * command and the pm framework brings down the device
21281 			 * to low power mode (possible power cut-off on some
21282 			 * platforms).
21283 			 */
21284 			mutex_exit(&un->un_pm_mutex);
21285 			if (sd_pm_entry(un) != DDI_SUCCESS) {
21286 				rval = EAGAIN;
21287 				goto done;
21288 			}
21289 		}
21290 	}
21291 
21292 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
21293 
21294 	if ((rval = sd_send_scsi_LOG_SENSE(un, temperature_page,
21295 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag)) != 0) {
21296 		goto done2;
21297 	}
21298 
21299 	/*
21300 	 * For the current temperature verify that the parameter length is 0x02
21301 	 * and the parameter code is 0x00
21302 	 */
21303 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
21304 	    (temperature_page[5] == 0x00)) {
21305 		if (temperature_page[9] == 0xFF) {
21306 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
21307 		} else {
21308 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
21309 		}
21310 	}
21311 
21312 	/*
21313 	 * For the reference temperature verify that the parameter
21314 	 * length is 0x02 and the parameter code is 0x01
21315 	 */
21316 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
21317 	    (temperature_page[11] == 0x01)) {
21318 		if (temperature_page[15] == 0xFF) {
21319 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
21320 		} else {
21321 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
21322 		}
21323 	}
21324 
21325 	/* Do the copyout regardless of the temperature commands status. */
21326 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
21327 	    flag) != 0) {
21328 		rval = EFAULT;
21329 	}
21330 
21331 done2:
21332 	if (path_flag == SD_PATH_DIRECT) {
21333 		sd_pm_exit(un);
21334 	}
21335 
21336 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
21337 done:
21338 	if (dktemp != NULL) {
21339 		kmem_free(dktemp, sizeof (struct dk_temperature));
21340 	}
21341 
21342 	return (rval);
21343 }
21344 
21345 
21346 /*
21347  *    Function: sd_log_page_supported
21348  *
21349  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
21350  *		supported log pages.
21351  *
21352  *   Arguments: un -
21353  *		log_page -
21354  *
21355  * Return Code: -1 - on error (log sense is optional and may not be supported).
21356  *		0  - log page not found.
21357  *  		1  - log page found.
21358  */
21359 
21360 static int
21361 sd_log_page_supported(struct sd_lun *un, int log_page)
21362 {
21363 	uchar_t *log_page_data;
21364 	int	i;
21365 	int	match = 0;
21366 	int	log_size;
21367 
21368 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
21369 
21370 	if (sd_send_scsi_LOG_SENSE(un, log_page_data, 0xFF, 0, 0x01, 0,
21371 	    SD_PATH_DIRECT) != 0) {
21372 		SD_ERROR(SD_LOG_COMMON, un,
21373 		    "sd_log_page_supported: failed log page retrieval\n");
21374 		kmem_free(log_page_data, 0xFF);
21375 		return (-1);
21376 	}
21377 	log_size = log_page_data[3];
21378 
21379 	/*
21380 	 * The list of supported log pages start from the fourth byte. Check
21381 	 * until we run out of log pages or a match is found.
21382 	 */
21383 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
21384 		if (log_page_data[i] == log_page) {
21385 			match++;
21386 		}
21387 	}
21388 	kmem_free(log_page_data, 0xFF);
21389 	return (match);
21390 }
21391 
21392 
21393 /*
21394  *    Function: sd_mhdioc_failfast
21395  *
21396  * Description: This routine is the driver entry point for handling ioctl
21397  *		requests to enable/disable the multihost failfast option.
21398  *		(MHIOCENFAILFAST)
21399  *
21400  *   Arguments: dev	- the device number
21401  *		arg	- user specified probing interval.
21402  *		flag	- this argument is a pass through to ddi_copyxxx()
21403  *			  directly from the mode argument of ioctl().
21404  *
21405  * Return Code: 0
21406  *		EFAULT
21407  *		ENXIO
21408  */
21409 
21410 static int
21411 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
21412 {
21413 	struct sd_lun	*un = NULL;
21414 	int		mh_time;
21415 	int		rval = 0;
21416 
21417 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21418 		return (ENXIO);
21419 	}
21420 
21421 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
21422 		return (EFAULT);
21423 
21424 	if (mh_time) {
21425 		mutex_enter(SD_MUTEX(un));
21426 		un->un_resvd_status |= SD_FAILFAST;
21427 		mutex_exit(SD_MUTEX(un));
21428 		/*
21429 		 * If mh_time is INT_MAX, then this ioctl is being used for
21430 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
21431 		 */
21432 		if (mh_time != INT_MAX) {
21433 			rval = sd_check_mhd(dev, mh_time);
21434 		}
21435 	} else {
21436 		(void) sd_check_mhd(dev, 0);
21437 		mutex_enter(SD_MUTEX(un));
21438 		un->un_resvd_status &= ~SD_FAILFAST;
21439 		mutex_exit(SD_MUTEX(un));
21440 	}
21441 	return (rval);
21442 }
21443 
21444 
21445 /*
21446  *    Function: sd_mhdioc_takeown
21447  *
21448  * Description: This routine is the driver entry point for handling ioctl
21449  *		requests to forcefully acquire exclusive access rights to the
21450  *		multihost disk (MHIOCTKOWN).
21451  *
21452  *   Arguments: dev	- the device number
21453  *		arg	- user provided structure specifying the delay
21454  *			  parameters in milliseconds
21455  *		flag	- this argument is a pass through to ddi_copyxxx()
21456  *			  directly from the mode argument of ioctl().
21457  *
21458  * Return Code: 0
21459  *		EFAULT
21460  *		ENXIO
21461  */
21462 
21463 static int
21464 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
21465 {
21466 	struct sd_lun		*un = NULL;
21467 	struct mhioctkown	*tkown = NULL;
21468 	int			rval = 0;
21469 
21470 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21471 		return (ENXIO);
21472 	}
21473 
21474 	if (arg != NULL) {
21475 		tkown = (struct mhioctkown *)
21476 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
21477 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
21478 		if (rval != 0) {
21479 			rval = EFAULT;
21480 			goto error;
21481 		}
21482 	}
21483 
21484 	rval = sd_take_ownership(dev, tkown);
21485 	mutex_enter(SD_MUTEX(un));
21486 	if (rval == 0) {
21487 		un->un_resvd_status |= SD_RESERVE;
21488 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
21489 			sd_reinstate_resv_delay =
21490 			    tkown->reinstate_resv_delay * 1000;
21491 		} else {
21492 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
21493 		}
21494 		/*
21495 		 * Give the scsi_watch routine interval set by
21496 		 * the MHIOCENFAILFAST ioctl precedence here.
21497 		 */
21498 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
21499 			mutex_exit(SD_MUTEX(un));
21500 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
21501 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
21502 			    "sd_mhdioc_takeown : %d\n",
21503 			    sd_reinstate_resv_delay);
21504 		} else {
21505 			mutex_exit(SD_MUTEX(un));
21506 		}
21507 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
21508 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21509 	} else {
21510 		un->un_resvd_status &= ~SD_RESERVE;
21511 		mutex_exit(SD_MUTEX(un));
21512 	}
21513 
21514 error:
21515 	if (tkown != NULL) {
21516 		kmem_free(tkown, sizeof (struct mhioctkown));
21517 	}
21518 	return (rval);
21519 }
21520 
21521 
21522 /*
21523  *    Function: sd_mhdioc_release
21524  *
21525  * Description: This routine is the driver entry point for handling ioctl
21526  *		requests to release exclusive access rights to the multihost
21527  *		disk (MHIOCRELEASE).
21528  *
21529  *   Arguments: dev	- the device number
21530  *
21531  * Return Code: 0
21532  *		ENXIO
21533  */
21534 
21535 static int
21536 sd_mhdioc_release(dev_t dev)
21537 {
21538 	struct sd_lun		*un = NULL;
21539 	timeout_id_t		resvd_timeid_save;
21540 	int			resvd_status_save;
21541 	int			rval = 0;
21542 
21543 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21544 		return (ENXIO);
21545 	}
21546 
21547 	mutex_enter(SD_MUTEX(un));
21548 	resvd_status_save = un->un_resvd_status;
21549 	un->un_resvd_status &=
21550 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
21551 	if (un->un_resvd_timeid) {
21552 		resvd_timeid_save = un->un_resvd_timeid;
21553 		un->un_resvd_timeid = NULL;
21554 		mutex_exit(SD_MUTEX(un));
21555 		(void) untimeout(resvd_timeid_save);
21556 	} else {
21557 		mutex_exit(SD_MUTEX(un));
21558 	}
21559 
21560 	/*
21561 	 * destroy any pending timeout thread that may be attempting to
21562 	 * reinstate reservation on this device.
21563 	 */
21564 	sd_rmv_resv_reclaim_req(dev);
21565 
21566 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
21567 		mutex_enter(SD_MUTEX(un));
21568 		if ((un->un_mhd_token) &&
21569 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
21570 			mutex_exit(SD_MUTEX(un));
21571 			(void) sd_check_mhd(dev, 0);
21572 		} else {
21573 			mutex_exit(SD_MUTEX(un));
21574 		}
21575 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
21576 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21577 	} else {
21578 		/*
21579 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
21580 		 */
21581 		mutex_enter(SD_MUTEX(un));
21582 		un->un_resvd_status = resvd_status_save;
21583 		mutex_exit(SD_MUTEX(un));
21584 	}
21585 	return (rval);
21586 }
21587 
21588 
21589 /*
21590  *    Function: sd_mhdioc_register_devid
21591  *
21592  * Description: This routine is the driver entry point for handling ioctl
21593  *		requests to register the device id (MHIOCREREGISTERDEVID).
21594  *
21595  *		Note: The implementation for this ioctl has been updated to
21596  *		be consistent with the original PSARC case (1999/357)
21597  *		(4375899, 4241671, 4220005)
21598  *
21599  *   Arguments: dev	- the device number
21600  *
21601  * Return Code: 0
21602  *		ENXIO
21603  */
21604 
21605 static int
21606 sd_mhdioc_register_devid(dev_t dev)
21607 {
21608 	struct sd_lun	*un = NULL;
21609 	int		rval = 0;
21610 
21611 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21612 		return (ENXIO);
21613 	}
21614 
21615 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21616 
21617 	mutex_enter(SD_MUTEX(un));
21618 
21619 	/* If a devid already exists, de-register it */
21620 	if (un->un_devid != NULL) {
21621 		ddi_devid_unregister(SD_DEVINFO(un));
21622 		/*
21623 		 * After unregister devid, needs to free devid memory
21624 		 */
21625 		ddi_devid_free(un->un_devid);
21626 		un->un_devid = NULL;
21627 	}
21628 
21629 	/* Check for reservation conflict */
21630 	mutex_exit(SD_MUTEX(un));
21631 	rval = sd_send_scsi_TEST_UNIT_READY(un, 0);
21632 	mutex_enter(SD_MUTEX(un));
21633 
21634 	switch (rval) {
21635 	case 0:
21636 		sd_register_devid(un, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
21637 		break;
21638 	case EACCES:
21639 		break;
21640 	default:
21641 		rval = EIO;
21642 	}
21643 
21644 	mutex_exit(SD_MUTEX(un));
21645 	return (rval);
21646 }
21647 
21648 
21649 /*
21650  *    Function: sd_mhdioc_inkeys
21651  *
21652  * Description: This routine is the driver entry point for handling ioctl
21653  *		requests to issue the SCSI-3 Persistent In Read Keys command
21654  *		to the device (MHIOCGRP_INKEYS).
21655  *
21656  *   Arguments: dev	- the device number
21657  *		arg	- user provided in_keys structure
21658  *		flag	- this argument is a pass through to ddi_copyxxx()
21659  *			  directly from the mode argument of ioctl().
21660  *
21661  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
21662  *		ENXIO
21663  *		EFAULT
21664  */
21665 
21666 static int
21667 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
21668 {
21669 	struct sd_lun		*un;
21670 	mhioc_inkeys_t		inkeys;
21671 	int			rval = 0;
21672 
21673 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21674 		return (ENXIO);
21675 	}
21676 
21677 #ifdef _MULTI_DATAMODEL
21678 	switch (ddi_model_convert_from(flag & FMODELS)) {
21679 	case DDI_MODEL_ILP32: {
21680 		struct mhioc_inkeys32	inkeys32;
21681 
21682 		if (ddi_copyin(arg, &inkeys32,
21683 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
21684 			return (EFAULT);
21685 		}
21686 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
21687 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21688 		    &inkeys, flag)) != 0) {
21689 			return (rval);
21690 		}
21691 		inkeys32.generation = inkeys.generation;
21692 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
21693 		    flag) != 0) {
21694 			return (EFAULT);
21695 		}
21696 		break;
21697 	}
21698 	case DDI_MODEL_NONE:
21699 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
21700 		    flag) != 0) {
21701 			return (EFAULT);
21702 		}
21703 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21704 		    &inkeys, flag)) != 0) {
21705 			return (rval);
21706 		}
21707 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
21708 		    flag) != 0) {
21709 			return (EFAULT);
21710 		}
21711 		break;
21712 	}
21713 
21714 #else /* ! _MULTI_DATAMODEL */
21715 
21716 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
21717 		return (EFAULT);
21718 	}
21719 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
21720 	if (rval != 0) {
21721 		return (rval);
21722 	}
21723 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
21724 		return (EFAULT);
21725 	}
21726 
21727 #endif /* _MULTI_DATAMODEL */
21728 
21729 	return (rval);
21730 }
21731 
21732 
21733 /*
21734  *    Function: sd_mhdioc_inresv
21735  *
21736  * Description: This routine is the driver entry point for handling ioctl
21737  *		requests to issue the SCSI-3 Persistent In Read Reservations
21738  *		command to the device (MHIOCGRP_INKEYS).
21739  *
21740  *   Arguments: dev	- the device number
21741  *		arg	- user provided in_resv structure
21742  *		flag	- this argument is a pass through to ddi_copyxxx()
21743  *			  directly from the mode argument of ioctl().
21744  *
21745  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
21746  *		ENXIO
21747  *		EFAULT
21748  */
21749 
21750 static int
21751 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
21752 {
21753 	struct sd_lun		*un;
21754 	mhioc_inresvs_t		inresvs;
21755 	int			rval = 0;
21756 
21757 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21758 		return (ENXIO);
21759 	}
21760 
21761 #ifdef _MULTI_DATAMODEL
21762 
21763 	switch (ddi_model_convert_from(flag & FMODELS)) {
21764 	case DDI_MODEL_ILP32: {
21765 		struct mhioc_inresvs32	inresvs32;
21766 
21767 		if (ddi_copyin(arg, &inresvs32,
21768 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21769 			return (EFAULT);
21770 		}
21771 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
21772 		if ((rval = sd_persistent_reservation_in_read_resv(un,
21773 		    &inresvs, flag)) != 0) {
21774 			return (rval);
21775 		}
21776 		inresvs32.generation = inresvs.generation;
21777 		if (ddi_copyout(&inresvs32, arg,
21778 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21779 			return (EFAULT);
21780 		}
21781 		break;
21782 	}
21783 	case DDI_MODEL_NONE:
21784 		if (ddi_copyin(arg, &inresvs,
21785 		    sizeof (mhioc_inresvs_t), flag) != 0) {
21786 			return (EFAULT);
21787 		}
21788 		if ((rval = sd_persistent_reservation_in_read_resv(un,
21789 		    &inresvs, flag)) != 0) {
21790 			return (rval);
21791 		}
21792 		if (ddi_copyout(&inresvs, arg,
21793 		    sizeof (mhioc_inresvs_t), flag) != 0) {
21794 			return (EFAULT);
21795 		}
21796 		break;
21797 	}
21798 
21799 #else /* ! _MULTI_DATAMODEL */
21800 
21801 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
21802 		return (EFAULT);
21803 	}
21804 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
21805 	if (rval != 0) {
21806 		return (rval);
21807 	}
21808 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
21809 		return (EFAULT);
21810 	}
21811 
21812 #endif /* ! _MULTI_DATAMODEL */
21813 
21814 	return (rval);
21815 }
21816 
21817 
21818 /*
21819  * The following routines support the clustering functionality described below
21820  * and implement lost reservation reclaim functionality.
21821  *
21822  * Clustering
21823  * ----------
21824  * The clustering code uses two different, independent forms of SCSI
21825  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
21826  * Persistent Group Reservations. For any particular disk, it will use either
21827  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
21828  *
21829  * SCSI-2
21830  * The cluster software takes ownership of a multi-hosted disk by issuing the
21831  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
21832  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
21833  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
21834  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
21835  * driver. The meaning of failfast is that if the driver (on this host) ever
21836  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
21837  * it should immediately panic the host. The motivation for this ioctl is that
21838  * if this host does encounter reservation conflict, the underlying cause is
21839  * that some other host of the cluster has decided that this host is no longer
21840  * in the cluster and has seized control of the disks for itself. Since this
21841  * host is no longer in the cluster, it ought to panic itself. The
21842  * MHIOCENFAILFAST ioctl does two things:
21843  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
21844  *      error to panic the host
21845  *      (b) it sets up a periodic timer to test whether this host still has
21846  *      "access" (in that no other host has reserved the device):  if the
21847  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
21848  *      purpose of that periodic timer is to handle scenarios where the host is
21849  *      otherwise temporarily quiescent, temporarily doing no real i/o.
21850  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
21851  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
21852  * the device itself.
21853  *
21854  * SCSI-3 PGR
21855  * A direct semantic implementation of the SCSI-3 Persistent Reservation
21856  * facility is supported through the shared multihost disk ioctls
21857  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
21858  * MHIOCGRP_PREEMPTANDABORT)
21859  *
21860  * Reservation Reclaim:
21861  * --------------------
21862  * To support the lost reservation reclaim operations this driver creates a
21863  * single thread to handle reinstating reservations on all devices that have
21864  * lost reservations sd_resv_reclaim_requests are logged for all devices that
21865  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
21866  * and the reservation reclaim thread loops through the requests to regain the
21867  * lost reservations.
21868  */
21869 
21870 /*
21871  *    Function: sd_check_mhd()
21872  *
21873  * Description: This function sets up and submits a scsi watch request or
21874  *		terminates an existing watch request. This routine is used in
21875  *		support of reservation reclaim.
21876  *
21877  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
21878  *			 among multiple watches that share the callback function
21879  *		interval - the number of microseconds specifying the watch
21880  *			   interval for issuing TEST UNIT READY commands. If
21881  *			   set to 0 the watch should be terminated. If the
21882  *			   interval is set to 0 and if the device is required
21883  *			   to hold reservation while disabling failfast, the
21884  *			   watch is restarted with an interval of
21885  *			   reinstate_resv_delay.
21886  *
21887  * Return Code: 0	   - Successful submit/terminate of scsi watch request
21888  *		ENXIO      - Indicates an invalid device was specified
21889  *		EAGAIN     - Unable to submit the scsi watch request
21890  */
21891 
21892 static int
21893 sd_check_mhd(dev_t dev, int interval)
21894 {
21895 	struct sd_lun	*un;
21896 	opaque_t	token;
21897 
21898 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21899 		return (ENXIO);
21900 	}
21901 
21902 	/* is this a watch termination request? */
21903 	if (interval == 0) {
21904 		mutex_enter(SD_MUTEX(un));
21905 		/* if there is an existing watch task then terminate it */
21906 		if (un->un_mhd_token) {
21907 			token = un->un_mhd_token;
21908 			un->un_mhd_token = NULL;
21909 			mutex_exit(SD_MUTEX(un));
21910 			(void) scsi_watch_request_terminate(token,
21911 			    SCSI_WATCH_TERMINATE_WAIT);
21912 			mutex_enter(SD_MUTEX(un));
21913 		} else {
21914 			mutex_exit(SD_MUTEX(un));
21915 			/*
21916 			 * Note: If we return here we don't check for the
21917 			 * failfast case. This is the original legacy
21918 			 * implementation but perhaps we should be checking
21919 			 * the failfast case.
21920 			 */
21921 			return (0);
21922 		}
21923 		/*
21924 		 * If the device is required to hold reservation while
21925 		 * disabling failfast, we need to restart the scsi_watch
21926 		 * routine with an interval of reinstate_resv_delay.
21927 		 */
21928 		if (un->un_resvd_status & SD_RESERVE) {
21929 			interval = sd_reinstate_resv_delay/1000;
21930 		} else {
21931 			/* no failfast so bail */
21932 			mutex_exit(SD_MUTEX(un));
21933 			return (0);
21934 		}
21935 		mutex_exit(SD_MUTEX(un));
21936 	}
21937 
21938 	/*
21939 	 * adjust minimum time interval to 1 second,
21940 	 * and convert from msecs to usecs
21941 	 */
21942 	if (interval > 0 && interval < 1000) {
21943 		interval = 1000;
21944 	}
21945 	interval *= 1000;
21946 
21947 	/*
21948 	 * submit the request to the scsi_watch service
21949 	 */
21950 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
21951 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
21952 	if (token == NULL) {
21953 		return (EAGAIN);
21954 	}
21955 
21956 	/*
21957 	 * save token for termination later on
21958 	 */
21959 	mutex_enter(SD_MUTEX(un));
21960 	un->un_mhd_token = token;
21961 	mutex_exit(SD_MUTEX(un));
21962 	return (0);
21963 }
21964 
21965 
21966 /*
21967  *    Function: sd_mhd_watch_cb()
21968  *
21969  * Description: This function is the call back function used by the scsi watch
21970  *		facility. The scsi watch facility sends the "Test Unit Ready"
21971  *		and processes the status. If applicable (i.e. a "Unit Attention"
21972  *		status and automatic "Request Sense" not used) the scsi watch
21973  *		facility will send a "Request Sense" and retrieve the sense data
21974  *		to be passed to this callback function. In either case the
21975  *		automatic "Request Sense" or the facility submitting one, this
21976  *		callback is passed the status and sense data.
21977  *
21978  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
21979  *			among multiple watches that share this callback function
21980  *		resultp - scsi watch facility result packet containing scsi
21981  *			  packet, status byte and sense data
21982  *
21983  * Return Code: 0 - continue the watch task
21984  *		non-zero - terminate the watch task
21985  */
21986 
21987 static int
21988 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
21989 {
21990 	struct sd_lun			*un;
21991 	struct scsi_status		*statusp;
21992 	uint8_t				*sensep;
21993 	struct scsi_pkt			*pkt;
21994 	uchar_t				actual_sense_length;
21995 	dev_t  				dev = (dev_t)arg;
21996 
21997 	ASSERT(resultp != NULL);
21998 	statusp			= resultp->statusp;
21999 	sensep			= (uint8_t *)resultp->sensep;
22000 	pkt			= resultp->pkt;
22001 	actual_sense_length	= resultp->actual_sense_length;
22002 
22003 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22004 		return (ENXIO);
22005 	}
22006 
22007 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
22008 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
22009 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
22010 
22011 	/* Begin processing of the status and/or sense data */
22012 	if (pkt->pkt_reason != CMD_CMPLT) {
22013 		/* Handle the incomplete packet */
22014 		sd_mhd_watch_incomplete(un, pkt);
22015 		return (0);
22016 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
22017 		if (*((unsigned char *)statusp)
22018 		    == STATUS_RESERVATION_CONFLICT) {
22019 			/*
22020 			 * Handle a reservation conflict by panicking if
22021 			 * configured for failfast or by logging the conflict
22022 			 * and updating the reservation status
22023 			 */
22024 			mutex_enter(SD_MUTEX(un));
22025 			if ((un->un_resvd_status & SD_FAILFAST) &&
22026 			    (sd_failfast_enable)) {
22027 				sd_panic_for_res_conflict(un);
22028 				/*NOTREACHED*/
22029 			}
22030 			SD_INFO(SD_LOG_IOCTL_MHD, un,
22031 			    "sd_mhd_watch_cb: Reservation Conflict\n");
22032 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
22033 			mutex_exit(SD_MUTEX(un));
22034 		}
22035 	}
22036 
22037 	if (sensep != NULL) {
22038 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
22039 			mutex_enter(SD_MUTEX(un));
22040 			if ((scsi_sense_asc(sensep) ==
22041 			    SD_SCSI_RESET_SENSE_CODE) &&
22042 			    (un->un_resvd_status & SD_RESERVE)) {
22043 				/*
22044 				 * The additional sense code indicates a power
22045 				 * on or bus device reset has occurred; update
22046 				 * the reservation status.
22047 				 */
22048 				un->un_resvd_status |=
22049 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
22050 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22051 				    "sd_mhd_watch_cb: Lost Reservation\n");
22052 			}
22053 		} else {
22054 			return (0);
22055 		}
22056 	} else {
22057 		mutex_enter(SD_MUTEX(un));
22058 	}
22059 
22060 	if ((un->un_resvd_status & SD_RESERVE) &&
22061 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
22062 		if (un->un_resvd_status & SD_WANT_RESERVE) {
22063 			/*
22064 			 * A reset occurred in between the last probe and this
22065 			 * one so if a timeout is pending cancel it.
22066 			 */
22067 			if (un->un_resvd_timeid) {
22068 				timeout_id_t temp_id = un->un_resvd_timeid;
22069 				un->un_resvd_timeid = NULL;
22070 				mutex_exit(SD_MUTEX(un));
22071 				(void) untimeout(temp_id);
22072 				mutex_enter(SD_MUTEX(un));
22073 			}
22074 			un->un_resvd_status &= ~SD_WANT_RESERVE;
22075 		}
22076 		if (un->un_resvd_timeid == 0) {
22077 			/* Schedule a timeout to handle the lost reservation */
22078 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
22079 			    (void *)dev,
22080 			    drv_usectohz(sd_reinstate_resv_delay));
22081 		}
22082 	}
22083 	mutex_exit(SD_MUTEX(un));
22084 	return (0);
22085 }
22086 
22087 
22088 /*
22089  *    Function: sd_mhd_watch_incomplete()
22090  *
22091  * Description: This function is used to find out why a scsi pkt sent by the
22092  *		scsi watch facility was not completed. Under some scenarios this
22093  *		routine will return. Otherwise it will send a bus reset to see
22094  *		if the drive is still online.
22095  *
22096  *   Arguments: un  - driver soft state (unit) structure
22097  *		pkt - incomplete scsi pkt
22098  */
22099 
22100 static void
22101 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
22102 {
22103 	int	be_chatty;
22104 	int	perr;
22105 
22106 	ASSERT(pkt != NULL);
22107 	ASSERT(un != NULL);
22108 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
22109 	perr		= (pkt->pkt_statistics & STAT_PERR);
22110 
22111 	mutex_enter(SD_MUTEX(un));
22112 	if (un->un_state == SD_STATE_DUMPING) {
22113 		mutex_exit(SD_MUTEX(un));
22114 		return;
22115 	}
22116 
22117 	switch (pkt->pkt_reason) {
22118 	case CMD_UNX_BUS_FREE:
22119 		/*
22120 		 * If we had a parity error that caused the target to drop BSY*,
22121 		 * don't be chatty about it.
22122 		 */
22123 		if (perr && be_chatty) {
22124 			be_chatty = 0;
22125 		}
22126 		break;
22127 	case CMD_TAG_REJECT:
22128 		/*
22129 		 * The SCSI-2 spec states that a tag reject will be sent by the
22130 		 * target if tagged queuing is not supported. A tag reject may
22131 		 * also be sent during certain initialization periods or to
22132 		 * control internal resources. For the latter case the target
22133 		 * may also return Queue Full.
22134 		 *
22135 		 * If this driver receives a tag reject from a target that is
22136 		 * going through an init period or controlling internal
22137 		 * resources tagged queuing will be disabled. This is a less
22138 		 * than optimal behavior but the driver is unable to determine
22139 		 * the target state and assumes tagged queueing is not supported
22140 		 */
22141 		pkt->pkt_flags = 0;
22142 		un->un_tagflags = 0;
22143 
22144 		if (un->un_f_opt_queueing == TRUE) {
22145 			un->un_throttle = min(un->un_throttle, 3);
22146 		} else {
22147 			un->un_throttle = 1;
22148 		}
22149 		mutex_exit(SD_MUTEX(un));
22150 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
22151 		mutex_enter(SD_MUTEX(un));
22152 		break;
22153 	case CMD_INCOMPLETE:
22154 		/*
22155 		 * The transport stopped with an abnormal state, fallthrough and
22156 		 * reset the target and/or bus unless selection did not complete
22157 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
22158 		 * go through a target/bus reset
22159 		 */
22160 		if (pkt->pkt_state == STATE_GOT_BUS) {
22161 			break;
22162 		}
22163 		/*FALLTHROUGH*/
22164 
22165 	case CMD_TIMEOUT:
22166 	default:
22167 		/*
22168 		 * The lun may still be running the command, so a lun reset
22169 		 * should be attempted. If the lun reset fails or cannot be
22170 		 * issued, than try a target reset. Lastly try a bus reset.
22171 		 */
22172 		if ((pkt->pkt_statistics &
22173 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
22174 			int reset_retval = 0;
22175 			mutex_exit(SD_MUTEX(un));
22176 			if (un->un_f_allow_bus_device_reset == TRUE) {
22177 				if (un->un_f_lun_reset_enabled == TRUE) {
22178 					reset_retval =
22179 					    scsi_reset(SD_ADDRESS(un),
22180 					    RESET_LUN);
22181 				}
22182 				if (reset_retval == 0) {
22183 					reset_retval =
22184 					    scsi_reset(SD_ADDRESS(un),
22185 					    RESET_TARGET);
22186 				}
22187 			}
22188 			if (reset_retval == 0) {
22189 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
22190 			}
22191 			mutex_enter(SD_MUTEX(un));
22192 		}
22193 		break;
22194 	}
22195 
22196 	/* A device/bus reset has occurred; update the reservation status. */
22197 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
22198 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
22199 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22200 			un->un_resvd_status |=
22201 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
22202 			SD_INFO(SD_LOG_IOCTL_MHD, un,
22203 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
22204 		}
22205 	}
22206 
22207 	/*
22208 	 * The disk has been turned off; Update the device state.
22209 	 *
22210 	 * Note: Should we be offlining the disk here?
22211 	 */
22212 	if (pkt->pkt_state == STATE_GOT_BUS) {
22213 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
22214 		    "Disk not responding to selection\n");
22215 		if (un->un_state != SD_STATE_OFFLINE) {
22216 			New_state(un, SD_STATE_OFFLINE);
22217 		}
22218 	} else if (be_chatty) {
22219 		/*
22220 		 * suppress messages if they are all the same pkt reason;
22221 		 * with TQ, many (up to 256) are returned with the same
22222 		 * pkt_reason
22223 		 */
22224 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
22225 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
22226 			    "sd_mhd_watch_incomplete: "
22227 			    "SCSI transport failed: reason '%s'\n",
22228 			    scsi_rname(pkt->pkt_reason));
22229 		}
22230 	}
22231 	un->un_last_pkt_reason = pkt->pkt_reason;
22232 	mutex_exit(SD_MUTEX(un));
22233 }
22234 
22235 
22236 /*
22237  *    Function: sd_sname()
22238  *
22239  * Description: This is a simple little routine to return a string containing
22240  *		a printable description of command status byte for use in
22241  *		logging.
22242  *
22243  *   Arguments: status - pointer to a status byte
22244  *
22245  * Return Code: char * - string containing status description.
22246  */
22247 
22248 static char *
22249 sd_sname(uchar_t status)
22250 {
22251 	switch (status & STATUS_MASK) {
22252 	case STATUS_GOOD:
22253 		return ("good status");
22254 	case STATUS_CHECK:
22255 		return ("check condition");
22256 	case STATUS_MET:
22257 		return ("condition met");
22258 	case STATUS_BUSY:
22259 		return ("busy");
22260 	case STATUS_INTERMEDIATE:
22261 		return ("intermediate");
22262 	case STATUS_INTERMEDIATE_MET:
22263 		return ("intermediate - condition met");
22264 	case STATUS_RESERVATION_CONFLICT:
22265 		return ("reservation_conflict");
22266 	case STATUS_TERMINATED:
22267 		return ("command terminated");
22268 	case STATUS_QFULL:
22269 		return ("queue full");
22270 	default:
22271 		return ("<unknown status>");
22272 	}
22273 }
22274 
22275 
22276 /*
22277  *    Function: sd_mhd_resvd_recover()
22278  *
22279  * Description: This function adds a reservation entry to the
22280  *		sd_resv_reclaim_request list and signals the reservation
22281  *		reclaim thread that there is work pending. If the reservation
22282  *		reclaim thread has not been previously created this function
22283  *		will kick it off.
22284  *
22285  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
22286  *			among multiple watches that share this callback function
22287  *
22288  *     Context: This routine is called by timeout() and is run in interrupt
22289  *		context. It must not sleep or call other functions which may
22290  *		sleep.
22291  */
22292 
22293 static void
22294 sd_mhd_resvd_recover(void *arg)
22295 {
22296 	dev_t			dev = (dev_t)arg;
22297 	struct sd_lun		*un;
22298 	struct sd_thr_request	*sd_treq = NULL;
22299 	struct sd_thr_request	*sd_cur = NULL;
22300 	struct sd_thr_request	*sd_prev = NULL;
22301 	int			already_there = 0;
22302 
22303 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22304 		return;
22305 	}
22306 
22307 	mutex_enter(SD_MUTEX(un));
22308 	un->un_resvd_timeid = NULL;
22309 	if (un->un_resvd_status & SD_WANT_RESERVE) {
22310 		/*
22311 		 * There was a reset so don't issue the reserve, allow the
22312 		 * sd_mhd_watch_cb callback function to notice this and
22313 		 * reschedule the timeout for reservation.
22314 		 */
22315 		mutex_exit(SD_MUTEX(un));
22316 		return;
22317 	}
22318 	mutex_exit(SD_MUTEX(un));
22319 
22320 	/*
22321 	 * Add this device to the sd_resv_reclaim_request list and the
22322 	 * sd_resv_reclaim_thread should take care of the rest.
22323 	 *
22324 	 * Note: We can't sleep in this context so if the memory allocation
22325 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
22326 	 * reschedule the timeout for reservation.  (4378460)
22327 	 */
22328 	sd_treq = (struct sd_thr_request *)
22329 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
22330 	if (sd_treq == NULL) {
22331 		return;
22332 	}
22333 
22334 	sd_treq->sd_thr_req_next = NULL;
22335 	sd_treq->dev = dev;
22336 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22337 	if (sd_tr.srq_thr_req_head == NULL) {
22338 		sd_tr.srq_thr_req_head = sd_treq;
22339 	} else {
22340 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
22341 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
22342 			if (sd_cur->dev == dev) {
22343 				/*
22344 				 * already in Queue so don't log
22345 				 * another request for the device
22346 				 */
22347 				already_there = 1;
22348 				break;
22349 			}
22350 			sd_prev = sd_cur;
22351 		}
22352 		if (!already_there) {
22353 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
22354 			    "logging request for %lx\n", dev);
22355 			sd_prev->sd_thr_req_next = sd_treq;
22356 		} else {
22357 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
22358 		}
22359 	}
22360 
22361 	/*
22362 	 * Create a kernel thread to do the reservation reclaim and free up this
22363 	 * thread. We cannot block this thread while we go away to do the
22364 	 * reservation reclaim
22365 	 */
22366 	if (sd_tr.srq_resv_reclaim_thread == NULL)
22367 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
22368 		    sd_resv_reclaim_thread, NULL,
22369 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
22370 
22371 	/* Tell the reservation reclaim thread that it has work to do */
22372 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
22373 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22374 }
22375 
22376 /*
22377  *    Function: sd_resv_reclaim_thread()
22378  *
22379  * Description: This function implements the reservation reclaim operations
22380  *
22381  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
22382  *		      among multiple watches that share this callback function
22383  */
22384 
22385 static void
22386 sd_resv_reclaim_thread()
22387 {
22388 	struct sd_lun		*un;
22389 	struct sd_thr_request	*sd_mhreq;
22390 
22391 	/* Wait for work */
22392 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22393 	if (sd_tr.srq_thr_req_head == NULL) {
22394 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
22395 		    &sd_tr.srq_resv_reclaim_mutex);
22396 	}
22397 
22398 	/* Loop while we have work */
22399 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
22400 		un = ddi_get_soft_state(sd_state,
22401 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
22402 		if (un == NULL) {
22403 			/*
22404 			 * softstate structure is NULL so just
22405 			 * dequeue the request and continue
22406 			 */
22407 			sd_tr.srq_thr_req_head =
22408 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22409 			kmem_free(sd_tr.srq_thr_cur_req,
22410 			    sizeof (struct sd_thr_request));
22411 			continue;
22412 		}
22413 
22414 		/* dequeue the request */
22415 		sd_mhreq = sd_tr.srq_thr_cur_req;
22416 		sd_tr.srq_thr_req_head =
22417 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22418 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22419 
22420 		/*
22421 		 * Reclaim reservation only if SD_RESERVE is still set. There
22422 		 * may have been a call to MHIOCRELEASE before we got here.
22423 		 */
22424 		mutex_enter(SD_MUTEX(un));
22425 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22426 			/*
22427 			 * Note: The SD_LOST_RESERVE flag is cleared before
22428 			 * reclaiming the reservation. If this is done after the
22429 			 * call to sd_reserve_release a reservation loss in the
22430 			 * window between pkt completion of reserve cmd and
22431 			 * mutex_enter below may not be recognized
22432 			 */
22433 			un->un_resvd_status &= ~SD_LOST_RESERVE;
22434 			mutex_exit(SD_MUTEX(un));
22435 
22436 			if (sd_reserve_release(sd_mhreq->dev,
22437 			    SD_RESERVE) == 0) {
22438 				mutex_enter(SD_MUTEX(un));
22439 				un->un_resvd_status |= SD_RESERVE;
22440 				mutex_exit(SD_MUTEX(un));
22441 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22442 				    "sd_resv_reclaim_thread: "
22443 				    "Reservation Recovered\n");
22444 			} else {
22445 				mutex_enter(SD_MUTEX(un));
22446 				un->un_resvd_status |= SD_LOST_RESERVE;
22447 				mutex_exit(SD_MUTEX(un));
22448 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22449 				    "sd_resv_reclaim_thread: Failed "
22450 				    "Reservation Recovery\n");
22451 			}
22452 		} else {
22453 			mutex_exit(SD_MUTEX(un));
22454 		}
22455 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22456 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
22457 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22458 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
22459 		/*
22460 		 * wakeup the destroy thread if anyone is waiting on
22461 		 * us to complete.
22462 		 */
22463 		cv_signal(&sd_tr.srq_inprocess_cv);
22464 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
22465 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
22466 	}
22467 
22468 	/*
22469 	 * cleanup the sd_tr structure now that this thread will not exist
22470 	 */
22471 	ASSERT(sd_tr.srq_thr_req_head == NULL);
22472 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
22473 	sd_tr.srq_resv_reclaim_thread = NULL;
22474 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22475 	thread_exit();
22476 }
22477 
22478 
22479 /*
22480  *    Function: sd_rmv_resv_reclaim_req()
22481  *
22482  * Description: This function removes any pending reservation reclaim requests
22483  *		for the specified device.
22484  *
22485  *   Arguments: dev - the device 'dev_t'
22486  */
22487 
22488 static void
22489 sd_rmv_resv_reclaim_req(dev_t dev)
22490 {
22491 	struct sd_thr_request *sd_mhreq;
22492 	struct sd_thr_request *sd_prev;
22493 
22494 	/* Remove a reservation reclaim request from the list */
22495 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22496 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
22497 		/*
22498 		 * We are attempting to reinstate reservation for
22499 		 * this device. We wait for sd_reserve_release()
22500 		 * to return before we return.
22501 		 */
22502 		cv_wait(&sd_tr.srq_inprocess_cv,
22503 		    &sd_tr.srq_resv_reclaim_mutex);
22504 	} else {
22505 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
22506 		if (sd_mhreq && sd_mhreq->dev == dev) {
22507 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
22508 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22509 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22510 			return;
22511 		}
22512 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
22513 			if (sd_mhreq && sd_mhreq->dev == dev) {
22514 				break;
22515 			}
22516 			sd_prev = sd_mhreq;
22517 		}
22518 		if (sd_mhreq != NULL) {
22519 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
22520 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22521 		}
22522 	}
22523 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22524 }
22525 
22526 
22527 /*
22528  *    Function: sd_mhd_reset_notify_cb()
22529  *
22530  * Description: This is a call back function for scsi_reset_notify. This
22531  *		function updates the softstate reserved status and logs the
22532  *		reset. The driver scsi watch facility callback function
22533  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
22534  *		will reclaim the reservation.
22535  *
22536  *   Arguments: arg  - driver soft state (unit) structure
22537  */
22538 
22539 static void
22540 sd_mhd_reset_notify_cb(caddr_t arg)
22541 {
22542 	struct sd_lun *un = (struct sd_lun *)arg;
22543 
22544 	mutex_enter(SD_MUTEX(un));
22545 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22546 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
22547 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22548 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
22549 	}
22550 	mutex_exit(SD_MUTEX(un));
22551 }
22552 
22553 
22554 /*
22555  *    Function: sd_take_ownership()
22556  *
22557  * Description: This routine implements an algorithm to achieve a stable
22558  *		reservation on disks which don't implement priority reserve,
22559  *		and makes sure that other host lose re-reservation attempts.
22560  *		This algorithm contains of a loop that keeps issuing the RESERVE
22561  *		for some period of time (min_ownership_delay, default 6 seconds)
22562  *		During that loop, it looks to see if there has been a bus device
22563  *		reset or bus reset (both of which cause an existing reservation
22564  *		to be lost). If the reservation is lost issue RESERVE until a
22565  *		period of min_ownership_delay with no resets has gone by, or
22566  *		until max_ownership_delay has expired. This loop ensures that
22567  *		the host really did manage to reserve the device, in spite of
22568  *		resets. The looping for min_ownership_delay (default six
22569  *		seconds) is important to early generation clustering products,
22570  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
22571  *		MHIOCENFAILFAST periodic timer of two seconds. By having
22572  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
22573  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
22574  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
22575  *		have already noticed, via the MHIOCENFAILFAST polling, that it
22576  *		no longer "owns" the disk and will have panicked itself.  Thus,
22577  *		the host issuing the MHIOCTKOWN is assured (with timing
22578  *		dependencies) that by the time it actually starts to use the
22579  *		disk for real work, the old owner is no longer accessing it.
22580  *
22581  *		min_ownership_delay is the minimum amount of time for which the
22582  *		disk must be reserved continuously devoid of resets before the
22583  *		MHIOCTKOWN ioctl will return success.
22584  *
22585  *		max_ownership_delay indicates the amount of time by which the
22586  *		take ownership should succeed or timeout with an error.
22587  *
22588  *   Arguments: dev - the device 'dev_t'
22589  *		*p  - struct containing timing info.
22590  *
22591  * Return Code: 0 for success or error code
22592  */
22593 
22594 static int
22595 sd_take_ownership(dev_t dev, struct mhioctkown *p)
22596 {
22597 	struct sd_lun	*un;
22598 	int		rval;
22599 	int		err;
22600 	int		reservation_count   = 0;
22601 	int		min_ownership_delay =  6000000; /* in usec */
22602 	int		max_ownership_delay = 30000000; /* in usec */
22603 	clock_t		start_time;	/* starting time of this algorithm */
22604 	clock_t		end_time;	/* time limit for giving up */
22605 	clock_t		ownership_time;	/* time limit for stable ownership */
22606 	clock_t		current_time;
22607 	clock_t		previous_current_time;
22608 
22609 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22610 		return (ENXIO);
22611 	}
22612 
22613 	/*
22614 	 * Attempt a device reservation. A priority reservation is requested.
22615 	 */
22616 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
22617 	    != SD_SUCCESS) {
22618 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
22619 		    "sd_take_ownership: return(1)=%d\n", rval);
22620 		return (rval);
22621 	}
22622 
22623 	/* Update the softstate reserved status to indicate the reservation */
22624 	mutex_enter(SD_MUTEX(un));
22625 	un->un_resvd_status |= SD_RESERVE;
22626 	un->un_resvd_status &=
22627 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
22628 	mutex_exit(SD_MUTEX(un));
22629 
22630 	if (p != NULL) {
22631 		if (p->min_ownership_delay != 0) {
22632 			min_ownership_delay = p->min_ownership_delay * 1000;
22633 		}
22634 		if (p->max_ownership_delay != 0) {
22635 			max_ownership_delay = p->max_ownership_delay * 1000;
22636 		}
22637 	}
22638 	SD_INFO(SD_LOG_IOCTL_MHD, un,
22639 	    "sd_take_ownership: min, max delays: %d, %d\n",
22640 	    min_ownership_delay, max_ownership_delay);
22641 
22642 	start_time = ddi_get_lbolt();
22643 	current_time	= start_time;
22644 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
22645 	end_time	= start_time + drv_usectohz(max_ownership_delay);
22646 
22647 	while (current_time - end_time < 0) {
22648 		delay(drv_usectohz(500000));
22649 
22650 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
22651 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
22652 				mutex_enter(SD_MUTEX(un));
22653 				rval = (un->un_resvd_status &
22654 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
22655 				mutex_exit(SD_MUTEX(un));
22656 				break;
22657 			}
22658 		}
22659 		previous_current_time = current_time;
22660 		current_time = ddi_get_lbolt();
22661 		mutex_enter(SD_MUTEX(un));
22662 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
22663 			ownership_time = ddi_get_lbolt() +
22664 			    drv_usectohz(min_ownership_delay);
22665 			reservation_count = 0;
22666 		} else {
22667 			reservation_count++;
22668 		}
22669 		un->un_resvd_status |= SD_RESERVE;
22670 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
22671 		mutex_exit(SD_MUTEX(un));
22672 
22673 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22674 		    "sd_take_ownership: ticks for loop iteration=%ld, "
22675 		    "reservation=%s\n", (current_time - previous_current_time),
22676 		    reservation_count ? "ok" : "reclaimed");
22677 
22678 		if (current_time - ownership_time >= 0 &&
22679 		    reservation_count >= 4) {
22680 			rval = 0; /* Achieved a stable ownership */
22681 			break;
22682 		}
22683 		if (current_time - end_time >= 0) {
22684 			rval = EACCES; /* No ownership in max possible time */
22685 			break;
22686 		}
22687 	}
22688 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
22689 	    "sd_take_ownership: return(2)=%d\n", rval);
22690 	return (rval);
22691 }
22692 
22693 
22694 /*
22695  *    Function: sd_reserve_release()
22696  *
22697  * Description: This function builds and sends scsi RESERVE, RELEASE, and
22698  *		PRIORITY RESERVE commands based on a user specified command type
22699  *
22700  *   Arguments: dev - the device 'dev_t'
22701  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
22702  *		      SD_RESERVE, SD_RELEASE
22703  *
22704  * Return Code: 0 or Error Code
22705  */
22706 
22707 static int
22708 sd_reserve_release(dev_t dev, int cmd)
22709 {
22710 	struct uscsi_cmd	*com = NULL;
22711 	struct sd_lun		*un = NULL;
22712 	char			cdb[CDB_GROUP0];
22713 	int			rval;
22714 
22715 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
22716 	    (cmd == SD_PRIORITY_RESERVE));
22717 
22718 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22719 		return (ENXIO);
22720 	}
22721 
22722 	/* instantiate and initialize the command and cdb */
22723 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
22724 	bzero(cdb, CDB_GROUP0);
22725 	com->uscsi_flags   = USCSI_SILENT;
22726 	com->uscsi_timeout = un->un_reserve_release_time;
22727 	com->uscsi_cdblen  = CDB_GROUP0;
22728 	com->uscsi_cdb	   = cdb;
22729 	if (cmd == SD_RELEASE) {
22730 		cdb[0] = SCMD_RELEASE;
22731 	} else {
22732 		cdb[0] = SCMD_RESERVE;
22733 	}
22734 
22735 	/* Send the command. */
22736 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22737 	    SD_PATH_STANDARD);
22738 
22739 	/*
22740 	 * "break" a reservation that is held by another host, by issuing a
22741 	 * reset if priority reserve is desired, and we could not get the
22742 	 * device.
22743 	 */
22744 	if ((cmd == SD_PRIORITY_RESERVE) &&
22745 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22746 		/*
22747 		 * First try to reset the LUN. If we cannot, then try a target
22748 		 * reset, followed by a bus reset if the target reset fails.
22749 		 */
22750 		int reset_retval = 0;
22751 		if (un->un_f_lun_reset_enabled == TRUE) {
22752 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
22753 		}
22754 		if (reset_retval == 0) {
22755 			/* The LUN reset either failed or was not issued */
22756 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
22757 		}
22758 		if ((reset_retval == 0) &&
22759 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
22760 			rval = EIO;
22761 			kmem_free(com, sizeof (*com));
22762 			return (rval);
22763 		}
22764 
22765 		bzero(com, sizeof (struct uscsi_cmd));
22766 		com->uscsi_flags   = USCSI_SILENT;
22767 		com->uscsi_cdb	   = cdb;
22768 		com->uscsi_cdblen  = CDB_GROUP0;
22769 		com->uscsi_timeout = 5;
22770 
22771 		/*
22772 		 * Reissue the last reserve command, this time without request
22773 		 * sense.  Assume that it is just a regular reserve command.
22774 		 */
22775 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22776 		    SD_PATH_STANDARD);
22777 	}
22778 
22779 	/* Return an error if still getting a reservation conflict. */
22780 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22781 		rval = EACCES;
22782 	}
22783 
22784 	kmem_free(com, sizeof (*com));
22785 	return (rval);
22786 }
22787 
22788 
22789 #define	SD_NDUMP_RETRIES	12
22790 /*
22791  *	System Crash Dump routine
22792  */
22793 
22794 static int
22795 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
22796 {
22797 	int		instance;
22798 	int		partition;
22799 	int		i;
22800 	int		err;
22801 	struct sd_lun	*un;
22802 	struct scsi_pkt *wr_pktp;
22803 	struct buf	*wr_bp;
22804 	struct buf	wr_buf;
22805 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
22806 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
22807 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
22808 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
22809 	size_t		io_start_offset;
22810 	int		doing_rmw = FALSE;
22811 	int		rval;
22812 	ssize_t		dma_resid;
22813 	daddr_t		oblkno;
22814 	diskaddr_t	nblks = 0;
22815 	diskaddr_t	start_block;
22816 
22817 	instance = SDUNIT(dev);
22818 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
22819 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
22820 		return (ENXIO);
22821 	}
22822 
22823 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
22824 
22825 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
22826 
22827 	partition = SDPART(dev);
22828 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
22829 
22830 	/* Validate blocks to dump at against partition size. */
22831 
22832 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
22833 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
22834 
22835 	if ((blkno + nblk) > nblks) {
22836 		SD_TRACE(SD_LOG_DUMP, un,
22837 		    "sddump: dump range larger than partition: "
22838 		    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
22839 		    blkno, nblk, nblks);
22840 		return (EINVAL);
22841 	}
22842 
22843 	mutex_enter(&un->un_pm_mutex);
22844 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
22845 		struct scsi_pkt *start_pktp;
22846 
22847 		mutex_exit(&un->un_pm_mutex);
22848 
22849 		/*
22850 		 * use pm framework to power on HBA 1st
22851 		 */
22852 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
22853 
22854 		/*
22855 		 * Dump no long uses sdpower to power on a device, it's
22856 		 * in-line here so it can be done in polled mode.
22857 		 */
22858 
22859 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
22860 
22861 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
22862 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
22863 
22864 		if (start_pktp == NULL) {
22865 			/* We were not given a SCSI packet, fail. */
22866 			return (EIO);
22867 		}
22868 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
22869 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
22870 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
22871 		start_pktp->pkt_flags = FLAG_NOINTR;
22872 
22873 		mutex_enter(SD_MUTEX(un));
22874 		SD_FILL_SCSI1_LUN(un, start_pktp);
22875 		mutex_exit(SD_MUTEX(un));
22876 		/*
22877 		 * Scsi_poll returns 0 (success) if the command completes and
22878 		 * the status block is STATUS_GOOD.
22879 		 */
22880 		if (sd_scsi_poll(un, start_pktp) != 0) {
22881 			scsi_destroy_pkt(start_pktp);
22882 			return (EIO);
22883 		}
22884 		scsi_destroy_pkt(start_pktp);
22885 		(void) sd_ddi_pm_resume(un);
22886 	} else {
22887 		mutex_exit(&un->un_pm_mutex);
22888 	}
22889 
22890 	mutex_enter(SD_MUTEX(un));
22891 	un->un_throttle = 0;
22892 
22893 	/*
22894 	 * The first time through, reset the specific target device.
22895 	 * However, when cpr calls sddump we know that sd is in a
22896 	 * a good state so no bus reset is required.
22897 	 * Clear sense data via Request Sense cmd.
22898 	 * In sddump we don't care about allow_bus_device_reset anymore
22899 	 */
22900 
22901 	if ((un->un_state != SD_STATE_SUSPENDED) &&
22902 	    (un->un_state != SD_STATE_DUMPING)) {
22903 
22904 		New_state(un, SD_STATE_DUMPING);
22905 
22906 		if (un->un_f_is_fibre == FALSE) {
22907 			mutex_exit(SD_MUTEX(un));
22908 			/*
22909 			 * Attempt a bus reset for parallel scsi.
22910 			 *
22911 			 * Note: A bus reset is required because on some host
22912 			 * systems (i.e. E420R) a bus device reset is
22913 			 * insufficient to reset the state of the target.
22914 			 *
22915 			 * Note: Don't issue the reset for fibre-channel,
22916 			 * because this tends to hang the bus (loop) for
22917 			 * too long while everyone is logging out and in
22918 			 * and the deadman timer for dumping will fire
22919 			 * before the dump is complete.
22920 			 */
22921 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
22922 				mutex_enter(SD_MUTEX(un));
22923 				Restore_state(un);
22924 				mutex_exit(SD_MUTEX(un));
22925 				return (EIO);
22926 			}
22927 
22928 			/* Delay to give the device some recovery time. */
22929 			drv_usecwait(10000);
22930 
22931 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
22932 				SD_INFO(SD_LOG_DUMP, un,
22933 				    "sddump: sd_send_polled_RQS failed\n");
22934 			}
22935 			mutex_enter(SD_MUTEX(un));
22936 		}
22937 	}
22938 
22939 	/*
22940 	 * Convert the partition-relative block number to a
22941 	 * disk physical block number.
22942 	 */
22943 	blkno += start_block;
22944 
22945 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
22946 
22947 
22948 	/*
22949 	 * Check if the device has a non-512 block size.
22950 	 */
22951 	wr_bp = NULL;
22952 	if (NOT_DEVBSIZE(un)) {
22953 		tgt_byte_offset = blkno * un->un_sys_blocksize;
22954 		tgt_byte_count = nblk * un->un_sys_blocksize;
22955 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
22956 		    (tgt_byte_count % un->un_tgt_blocksize)) {
22957 			doing_rmw = TRUE;
22958 			/*
22959 			 * Calculate the block number and number of block
22960 			 * in terms of the media block size.
22961 			 */
22962 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
22963 			tgt_nblk =
22964 			    ((tgt_byte_offset + tgt_byte_count +
22965 			    (un->un_tgt_blocksize - 1)) /
22966 			    un->un_tgt_blocksize) - tgt_blkno;
22967 
22968 			/*
22969 			 * Invoke the routine which is going to do read part
22970 			 * of read-modify-write.
22971 			 * Note that this routine returns a pointer to
22972 			 * a valid bp in wr_bp.
22973 			 */
22974 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
22975 			    &wr_bp);
22976 			if (err) {
22977 				mutex_exit(SD_MUTEX(un));
22978 				return (err);
22979 			}
22980 			/*
22981 			 * Offset is being calculated as -
22982 			 * (original block # * system block size) -
22983 			 * (new block # * target block size)
22984 			 */
22985 			io_start_offset =
22986 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
22987 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
22988 
22989 			ASSERT((io_start_offset >= 0) &&
22990 			    (io_start_offset < un->un_tgt_blocksize));
22991 			/*
22992 			 * Do the modify portion of read modify write.
22993 			 */
22994 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
22995 			    (size_t)nblk * un->un_sys_blocksize);
22996 		} else {
22997 			doing_rmw = FALSE;
22998 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
22999 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
23000 		}
23001 
23002 		/* Convert blkno and nblk to target blocks */
23003 		blkno = tgt_blkno;
23004 		nblk = tgt_nblk;
23005 	} else {
23006 		wr_bp = &wr_buf;
23007 		bzero(wr_bp, sizeof (struct buf));
23008 		wr_bp->b_flags		= B_BUSY;
23009 		wr_bp->b_un.b_addr	= addr;
23010 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
23011 		wr_bp->b_resid		= 0;
23012 	}
23013 
23014 	mutex_exit(SD_MUTEX(un));
23015 
23016 	/*
23017 	 * Obtain a SCSI packet for the write command.
23018 	 * It should be safe to call the allocator here without
23019 	 * worrying about being locked for DVMA mapping because
23020 	 * the address we're passed is already a DVMA mapping
23021 	 *
23022 	 * We are also not going to worry about semaphore ownership
23023 	 * in the dump buffer. Dumping is single threaded at present.
23024 	 */
23025 
23026 	wr_pktp = NULL;
23027 
23028 	dma_resid = wr_bp->b_bcount;
23029 	oblkno = blkno;
23030 
23031 	while (dma_resid != 0) {
23032 
23033 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
23034 		wr_bp->b_flags &= ~B_ERROR;
23035 
23036 		if (un->un_partial_dma_supported == 1) {
23037 			blkno = oblkno +
23038 			    ((wr_bp->b_bcount - dma_resid) /
23039 			    un->un_tgt_blocksize);
23040 			nblk = dma_resid / un->un_tgt_blocksize;
23041 
23042 			if (wr_pktp) {
23043 				/*
23044 				 * Partial DMA transfers after initial transfer
23045 				 */
23046 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
23047 				    blkno, nblk);
23048 			} else {
23049 				/* Initial transfer */
23050 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
23051 				    un->un_pkt_flags, NULL_FUNC, NULL,
23052 				    blkno, nblk);
23053 			}
23054 		} else {
23055 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
23056 			    0, NULL_FUNC, NULL, blkno, nblk);
23057 		}
23058 
23059 		if (rval == 0) {
23060 			/* We were given a SCSI packet, continue. */
23061 			break;
23062 		}
23063 
23064 		if (i == 0) {
23065 			if (wr_bp->b_flags & B_ERROR) {
23066 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23067 				    "no resources for dumping; "
23068 				    "error code: 0x%x, retrying",
23069 				    geterror(wr_bp));
23070 			} else {
23071 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23072 				    "no resources for dumping; retrying");
23073 			}
23074 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
23075 			if (wr_bp->b_flags & B_ERROR) {
23076 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23077 				    "no resources for dumping; error code: "
23078 				    "0x%x, retrying\n", geterror(wr_bp));
23079 			}
23080 		} else {
23081 			if (wr_bp->b_flags & B_ERROR) {
23082 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23083 				    "no resources for dumping; "
23084 				    "error code: 0x%x, retries failed, "
23085 				    "giving up.\n", geterror(wr_bp));
23086 			} else {
23087 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23088 				    "no resources for dumping; "
23089 				    "retries failed, giving up.\n");
23090 			}
23091 			mutex_enter(SD_MUTEX(un));
23092 			Restore_state(un);
23093 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
23094 				mutex_exit(SD_MUTEX(un));
23095 				scsi_free_consistent_buf(wr_bp);
23096 			} else {
23097 				mutex_exit(SD_MUTEX(un));
23098 			}
23099 			return (EIO);
23100 		}
23101 		drv_usecwait(10000);
23102 	}
23103 
23104 	if (un->un_partial_dma_supported == 1) {
23105 		/*
23106 		 * save the resid from PARTIAL_DMA
23107 		 */
23108 		dma_resid = wr_pktp->pkt_resid;
23109 		if (dma_resid != 0)
23110 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
23111 		wr_pktp->pkt_resid = 0;
23112 	} else {
23113 		dma_resid = 0;
23114 	}
23115 
23116 	/* SunBug 1222170 */
23117 	wr_pktp->pkt_flags = FLAG_NOINTR;
23118 
23119 	err = EIO;
23120 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
23121 
23122 		/*
23123 		 * Scsi_poll returns 0 (success) if the command completes and
23124 		 * the status block is STATUS_GOOD.  We should only check
23125 		 * errors if this condition is not true.  Even then we should
23126 		 * send our own request sense packet only if we have a check
23127 		 * condition and auto request sense has not been performed by
23128 		 * the hba.
23129 		 */
23130 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
23131 
23132 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
23133 		    (wr_pktp->pkt_resid == 0)) {
23134 			err = SD_SUCCESS;
23135 			break;
23136 		}
23137 
23138 		/*
23139 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
23140 		 */
23141 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
23142 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23143 			    "Device is gone\n");
23144 			break;
23145 		}
23146 
23147 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
23148 			SD_INFO(SD_LOG_DUMP, un,
23149 			    "sddump: write failed with CHECK, try # %d\n", i);
23150 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
23151 				(void) sd_send_polled_RQS(un);
23152 			}
23153 
23154 			continue;
23155 		}
23156 
23157 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
23158 			int reset_retval = 0;
23159 
23160 			SD_INFO(SD_LOG_DUMP, un,
23161 			    "sddump: write failed with BUSY, try # %d\n", i);
23162 
23163 			if (un->un_f_lun_reset_enabled == TRUE) {
23164 				reset_retval = scsi_reset(SD_ADDRESS(un),
23165 				    RESET_LUN);
23166 			}
23167 			if (reset_retval == 0) {
23168 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
23169 			}
23170 			(void) sd_send_polled_RQS(un);
23171 
23172 		} else {
23173 			SD_INFO(SD_LOG_DUMP, un,
23174 			    "sddump: write failed with 0x%x, try # %d\n",
23175 			    SD_GET_PKT_STATUS(wr_pktp), i);
23176 			mutex_enter(SD_MUTEX(un));
23177 			sd_reset_target(un, wr_pktp);
23178 			mutex_exit(SD_MUTEX(un));
23179 		}
23180 
23181 		/*
23182 		 * If we are not getting anywhere with lun/target resets,
23183 		 * let's reset the bus.
23184 		 */
23185 		if (i == SD_NDUMP_RETRIES/2) {
23186 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
23187 			(void) sd_send_polled_RQS(un);
23188 		}
23189 	}
23190 	}
23191 
23192 	scsi_destroy_pkt(wr_pktp);
23193 	mutex_enter(SD_MUTEX(un));
23194 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
23195 		mutex_exit(SD_MUTEX(un));
23196 		scsi_free_consistent_buf(wr_bp);
23197 	} else {
23198 		mutex_exit(SD_MUTEX(un));
23199 	}
23200 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
23201 	return (err);
23202 }
23203 
23204 /*
23205  *    Function: sd_scsi_poll()
23206  *
23207  * Description: This is a wrapper for the scsi_poll call.
23208  *
23209  *   Arguments: sd_lun - The unit structure
23210  *              scsi_pkt - The scsi packet being sent to the device.
23211  *
23212  * Return Code: 0 - Command completed successfully with good status
23213  *             -1 - Command failed.  This could indicate a check condition
23214  *                  or other status value requiring recovery action.
23215  *
23216  */
23217 
23218 static int
23219 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
23220 {
23221 	int status;
23222 
23223 	ASSERT(un != NULL);
23224 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23225 	ASSERT(pktp != NULL);
23226 
23227 	status = SD_SUCCESS;
23228 
23229 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
23230 		pktp->pkt_flags |= un->un_tagflags;
23231 		pktp->pkt_flags &= ~FLAG_NODISCON;
23232 	}
23233 
23234 	status = sd_ddi_scsi_poll(pktp);
23235 	/*
23236 	 * Scsi_poll returns 0 (success) if the command completes and the
23237 	 * status block is STATUS_GOOD.  We should only check errors if this
23238 	 * condition is not true.  Even then we should send our own request
23239 	 * sense packet only if we have a check condition and auto
23240 	 * request sense has not been performed by the hba.
23241 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
23242 	 */
23243 	if ((status != SD_SUCCESS) &&
23244 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
23245 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
23246 	    (pktp->pkt_reason != CMD_DEV_GONE))
23247 		(void) sd_send_polled_RQS(un);
23248 
23249 	return (status);
23250 }
23251 
23252 /*
23253  *    Function: sd_send_polled_RQS()
23254  *
23255  * Description: This sends the request sense command to a device.
23256  *
23257  *   Arguments: sd_lun - The unit structure
23258  *
23259  * Return Code: 0 - Command completed successfully with good status
23260  *             -1 - Command failed.
23261  *
23262  */
23263 
23264 static int
23265 sd_send_polled_RQS(struct sd_lun *un)
23266 {
23267 	int	ret_val;
23268 	struct	scsi_pkt	*rqs_pktp;
23269 	struct	buf		*rqs_bp;
23270 
23271 	ASSERT(un != NULL);
23272 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23273 
23274 	ret_val = SD_SUCCESS;
23275 
23276 	rqs_pktp = un->un_rqs_pktp;
23277 	rqs_bp	 = un->un_rqs_bp;
23278 
23279 	mutex_enter(SD_MUTEX(un));
23280 
23281 	if (un->un_sense_isbusy) {
23282 		ret_val = SD_FAILURE;
23283 		mutex_exit(SD_MUTEX(un));
23284 		return (ret_val);
23285 	}
23286 
23287 	/*
23288 	 * If the request sense buffer (and packet) is not in use,
23289 	 * let's set the un_sense_isbusy and send our packet
23290 	 */
23291 	un->un_sense_isbusy 	= 1;
23292 	rqs_pktp->pkt_resid  	= 0;
23293 	rqs_pktp->pkt_reason 	= 0;
23294 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
23295 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
23296 
23297 	mutex_exit(SD_MUTEX(un));
23298 
23299 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
23300 	    " 0x%p\n", rqs_bp->b_un.b_addr);
23301 
23302 	/*
23303 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
23304 	 * axle - it has a call into us!
23305 	 */
23306 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
23307 		SD_INFO(SD_LOG_COMMON, un,
23308 		    "sd_send_polled_RQS: RQS failed\n");
23309 	}
23310 
23311 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
23312 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
23313 
23314 	mutex_enter(SD_MUTEX(un));
23315 	un->un_sense_isbusy = 0;
23316 	mutex_exit(SD_MUTEX(un));
23317 
23318 	return (ret_val);
23319 }
23320 
23321 /*
23322  * Defines needed for localized version of the scsi_poll routine.
23323  */
23324 #define	SD_CSEC		10000			/* usecs */
23325 #define	SD_SEC_TO_CSEC	(1000000/SD_CSEC)
23326 
23327 
23328 /*
23329  *    Function: sd_ddi_scsi_poll()
23330  *
23331  * Description: Localized version of the scsi_poll routine.  The purpose is to
23332  *		send a scsi_pkt to a device as a polled command.  This version
23333  *		is to ensure more robust handling of transport errors.
23334  *		Specifically this routine cures not ready, coming ready
23335  *		transition for power up and reset of sonoma's.  This can take
23336  *		up to 45 seconds for power-on and 20 seconds for reset of a
23337  * 		sonoma lun.
23338  *
23339  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
23340  *
23341  * Return Code: 0 - Command completed successfully with good status
23342  *             -1 - Command failed.
23343  *
23344  */
23345 
23346 static int
23347 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
23348 {
23349 	int busy_count;
23350 	int timeout;
23351 	int rval = SD_FAILURE;
23352 	int savef;
23353 	uint8_t *sensep;
23354 	long savet;
23355 	void (*savec)();
23356 	/*
23357 	 * The following is defined in machdep.c and is used in determining if
23358 	 * the scsi transport system will do polled I/O instead of interrupt
23359 	 * I/O when called from xx_dump().
23360 	 */
23361 	extern int do_polled_io;
23362 
23363 	/*
23364 	 * save old flags in pkt, to restore at end
23365 	 */
23366 	savef = pkt->pkt_flags;
23367 	savec = pkt->pkt_comp;
23368 	savet = pkt->pkt_time;
23369 
23370 	pkt->pkt_flags |= FLAG_NOINTR;
23371 
23372 	/*
23373 	 * XXX there is nothing in the SCSA spec that states that we should not
23374 	 * do a callback for polled cmds; however, removing this will break sd
23375 	 * and probably other target drivers
23376 	 */
23377 	pkt->pkt_comp = NULL;
23378 
23379 	/*
23380 	 * we don't like a polled command without timeout.
23381 	 * 60 seconds seems long enough.
23382 	 */
23383 	if (pkt->pkt_time == 0) {
23384 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
23385 	}
23386 
23387 	/*
23388 	 * Send polled cmd.
23389 	 *
23390 	 * We do some error recovery for various errors.  Tran_busy,
23391 	 * queue full, and non-dispatched commands are retried every 10 msec.
23392 	 * as they are typically transient failures.  Busy status and Not
23393 	 * Ready are retried every second as this status takes a while to
23394 	 * change.  Unit attention is retried for pkt_time (60) times
23395 	 * with no delay.
23396 	 */
23397 	timeout = pkt->pkt_time * SD_SEC_TO_CSEC;
23398 
23399 	for (busy_count = 0; busy_count < timeout; busy_count++) {
23400 		int rc;
23401 		int poll_delay;
23402 
23403 		/*
23404 		 * Initialize pkt status variables.
23405 		 */
23406 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
23407 
23408 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
23409 			if (rc != TRAN_BUSY) {
23410 				/* Transport failed - give up. */
23411 				break;
23412 			} else {
23413 				/* Transport busy - try again. */
23414 				poll_delay = 1 * SD_CSEC; /* 10 msec */
23415 			}
23416 		} else {
23417 			/*
23418 			 * Transport accepted - check pkt status.
23419 			 */
23420 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
23421 			if (pkt->pkt_reason == CMD_CMPLT &&
23422 			    rc == STATUS_CHECK &&
23423 			    pkt->pkt_state & STATE_ARQ_DONE) {
23424 				struct scsi_arq_status *arqstat =
23425 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
23426 
23427 				sensep = (uint8_t *)&arqstat->sts_sensedata;
23428 			} else {
23429 				sensep = NULL;
23430 			}
23431 
23432 			if ((pkt->pkt_reason == CMD_CMPLT) &&
23433 			    (rc == STATUS_GOOD)) {
23434 				/* No error - we're done */
23435 				rval = SD_SUCCESS;
23436 				break;
23437 
23438 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
23439 				/* Lost connection - give up */
23440 				break;
23441 
23442 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
23443 			    (pkt->pkt_state == 0)) {
23444 				/* Pkt not dispatched - try again. */
23445 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
23446 
23447 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23448 			    (rc == STATUS_QFULL)) {
23449 				/* Queue full - try again. */
23450 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
23451 
23452 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23453 			    (rc == STATUS_BUSY)) {
23454 				/* Busy - try again. */
23455 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
23456 				busy_count += (SD_SEC_TO_CSEC - 1);
23457 
23458 			} else if ((sensep != NULL) &&
23459 			    (scsi_sense_key(sensep) ==
23460 			    KEY_UNIT_ATTENTION)) {
23461 				/* Unit Attention - try again */
23462 				busy_count += (SD_SEC_TO_CSEC - 1); /* 1 */
23463 				continue;
23464 
23465 			} else if ((sensep != NULL) &&
23466 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
23467 			    (scsi_sense_asc(sensep) == 0x04) &&
23468 			    (scsi_sense_ascq(sensep) == 0x01)) {
23469 				/* Not ready -> ready - try again. */
23470 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
23471 				busy_count += (SD_SEC_TO_CSEC - 1);
23472 
23473 			} else {
23474 				/* BAD status - give up. */
23475 				break;
23476 			}
23477 		}
23478 
23479 		if ((curthread->t_flag & T_INTR_THREAD) == 0 &&
23480 		    !do_polled_io) {
23481 			delay(drv_usectohz(poll_delay));
23482 		} else {
23483 			/* we busy wait during cpr_dump or interrupt threads */
23484 			drv_usecwait(poll_delay);
23485 		}
23486 	}
23487 
23488 	pkt->pkt_flags = savef;
23489 	pkt->pkt_comp = savec;
23490 	pkt->pkt_time = savet;
23491 	return (rval);
23492 }
23493 
23494 
23495 /*
23496  *    Function: sd_persistent_reservation_in_read_keys
23497  *
23498  * Description: This routine is the driver entry point for handling CD-ROM
23499  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
23500  *		by sending the SCSI-3 PRIN commands to the device.
23501  *		Processes the read keys command response by copying the
23502  *		reservation key information into the user provided buffer.
23503  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
23504  *
23505  *   Arguments: un   -  Pointer to soft state struct for the target.
23506  *		usrp -	user provided pointer to multihost Persistent In Read
23507  *			Keys structure (mhioc_inkeys_t)
23508  *		flag -	this argument is a pass through to ddi_copyxxx()
23509  *			directly from the mode argument of ioctl().
23510  *
23511  * Return Code: 0   - Success
23512  *		EACCES
23513  *		ENOTSUP
23514  *		errno return code from sd_send_scsi_cmd()
23515  *
23516  *     Context: Can sleep. Does not return until command is completed.
23517  */
23518 
23519 static int
23520 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
23521     mhioc_inkeys_t *usrp, int flag)
23522 {
23523 #ifdef _MULTI_DATAMODEL
23524 	struct mhioc_key_list32	li32;
23525 #endif
23526 	sd_prin_readkeys_t	*in;
23527 	mhioc_inkeys_t		*ptr;
23528 	mhioc_key_list_t	li;
23529 	uchar_t			*data_bufp;
23530 	int 			data_len;
23531 	int			rval;
23532 	size_t			copysz;
23533 
23534 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
23535 		return (EINVAL);
23536 	}
23537 	bzero(&li, sizeof (mhioc_key_list_t));
23538 
23539 	/*
23540 	 * Get the listsize from user
23541 	 */
23542 #ifdef _MULTI_DATAMODEL
23543 
23544 	switch (ddi_model_convert_from(flag & FMODELS)) {
23545 	case DDI_MODEL_ILP32:
23546 		copysz = sizeof (struct mhioc_key_list32);
23547 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
23548 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23549 			    "sd_persistent_reservation_in_read_keys: "
23550 			    "failed ddi_copyin: mhioc_key_list32_t\n");
23551 			rval = EFAULT;
23552 			goto done;
23553 		}
23554 		li.listsize = li32.listsize;
23555 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
23556 		break;
23557 
23558 	case DDI_MODEL_NONE:
23559 		copysz = sizeof (mhioc_key_list_t);
23560 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23561 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23562 			    "sd_persistent_reservation_in_read_keys: "
23563 			    "failed ddi_copyin: mhioc_key_list_t\n");
23564 			rval = EFAULT;
23565 			goto done;
23566 		}
23567 		break;
23568 	}
23569 
23570 #else /* ! _MULTI_DATAMODEL */
23571 	copysz = sizeof (mhioc_key_list_t);
23572 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23573 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23574 		    "sd_persistent_reservation_in_read_keys: "
23575 		    "failed ddi_copyin: mhioc_key_list_t\n");
23576 		rval = EFAULT;
23577 		goto done;
23578 	}
23579 #endif
23580 
23581 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
23582 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
23583 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23584 
23585 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS,
23586 	    data_len, data_bufp)) != 0) {
23587 		goto done;
23588 	}
23589 	in = (sd_prin_readkeys_t *)data_bufp;
23590 	ptr->generation = BE_32(in->generation);
23591 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
23592 
23593 	/*
23594 	 * Return the min(listsize, listlen) keys
23595 	 */
23596 #ifdef _MULTI_DATAMODEL
23597 
23598 	switch (ddi_model_convert_from(flag & FMODELS)) {
23599 	case DDI_MODEL_ILP32:
23600 		li32.listlen = li.listlen;
23601 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
23602 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23603 			    "sd_persistent_reservation_in_read_keys: "
23604 			    "failed ddi_copyout: mhioc_key_list32_t\n");
23605 			rval = EFAULT;
23606 			goto done;
23607 		}
23608 		break;
23609 
23610 	case DDI_MODEL_NONE:
23611 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23612 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23613 			    "sd_persistent_reservation_in_read_keys: "
23614 			    "failed ddi_copyout: mhioc_key_list_t\n");
23615 			rval = EFAULT;
23616 			goto done;
23617 		}
23618 		break;
23619 	}
23620 
23621 #else /* ! _MULTI_DATAMODEL */
23622 
23623 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23624 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23625 		    "sd_persistent_reservation_in_read_keys: "
23626 		    "failed ddi_copyout: mhioc_key_list_t\n");
23627 		rval = EFAULT;
23628 		goto done;
23629 	}
23630 
23631 #endif /* _MULTI_DATAMODEL */
23632 
23633 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
23634 	    li.listsize * MHIOC_RESV_KEY_SIZE);
23635 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
23636 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23637 		    "sd_persistent_reservation_in_read_keys: "
23638 		    "failed ddi_copyout: keylist\n");
23639 		rval = EFAULT;
23640 	}
23641 done:
23642 	kmem_free(data_bufp, data_len);
23643 	return (rval);
23644 }
23645 
23646 
23647 /*
23648  *    Function: sd_persistent_reservation_in_read_resv
23649  *
23650  * Description: This routine is the driver entry point for handling CD-ROM
23651  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
23652  *		by sending the SCSI-3 PRIN commands to the device.
23653  *		Process the read persistent reservations command response by
23654  *		copying the reservation information into the user provided
23655  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
23656  *
23657  *   Arguments: un   -  Pointer to soft state struct for the target.
23658  *		usrp -	user provided pointer to multihost Persistent In Read
23659  *			Keys structure (mhioc_inkeys_t)
23660  *		flag -	this argument is a pass through to ddi_copyxxx()
23661  *			directly from the mode argument of ioctl().
23662  *
23663  * Return Code: 0   - Success
23664  *		EACCES
23665  *		ENOTSUP
23666  *		errno return code from sd_send_scsi_cmd()
23667  *
23668  *     Context: Can sleep. Does not return until command is completed.
23669  */
23670 
23671 static int
23672 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
23673     mhioc_inresvs_t *usrp, int flag)
23674 {
23675 #ifdef _MULTI_DATAMODEL
23676 	struct mhioc_resv_desc_list32 resvlist32;
23677 #endif
23678 	sd_prin_readresv_t	*in;
23679 	mhioc_inresvs_t		*ptr;
23680 	sd_readresv_desc_t	*readresv_ptr;
23681 	mhioc_resv_desc_list_t	resvlist;
23682 	mhioc_resv_desc_t 	resvdesc;
23683 	uchar_t			*data_bufp;
23684 	int 			data_len;
23685 	int			rval;
23686 	int			i;
23687 	size_t			copysz;
23688 	mhioc_resv_desc_t	*bufp;
23689 
23690 	if ((ptr = usrp) == NULL) {
23691 		return (EINVAL);
23692 	}
23693 
23694 	/*
23695 	 * Get the listsize from user
23696 	 */
23697 #ifdef _MULTI_DATAMODEL
23698 	switch (ddi_model_convert_from(flag & FMODELS)) {
23699 	case DDI_MODEL_ILP32:
23700 		copysz = sizeof (struct mhioc_resv_desc_list32);
23701 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
23702 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23703 			    "sd_persistent_reservation_in_read_resv: "
23704 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23705 			rval = EFAULT;
23706 			goto done;
23707 		}
23708 		resvlist.listsize = resvlist32.listsize;
23709 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
23710 		break;
23711 
23712 	case DDI_MODEL_NONE:
23713 		copysz = sizeof (mhioc_resv_desc_list_t);
23714 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23715 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23716 			    "sd_persistent_reservation_in_read_resv: "
23717 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23718 			rval = EFAULT;
23719 			goto done;
23720 		}
23721 		break;
23722 	}
23723 #else /* ! _MULTI_DATAMODEL */
23724 	copysz = sizeof (mhioc_resv_desc_list_t);
23725 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23726 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23727 		    "sd_persistent_reservation_in_read_resv: "
23728 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23729 		rval = EFAULT;
23730 		goto done;
23731 	}
23732 #endif /* ! _MULTI_DATAMODEL */
23733 
23734 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
23735 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
23736 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23737 
23738 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_RESV,
23739 	    data_len, data_bufp)) != 0) {
23740 		goto done;
23741 	}
23742 	in = (sd_prin_readresv_t *)data_bufp;
23743 	ptr->generation = BE_32(in->generation);
23744 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
23745 
23746 	/*
23747 	 * Return the min(listsize, listlen( keys
23748 	 */
23749 #ifdef _MULTI_DATAMODEL
23750 
23751 	switch (ddi_model_convert_from(flag & FMODELS)) {
23752 	case DDI_MODEL_ILP32:
23753 		resvlist32.listlen = resvlist.listlen;
23754 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
23755 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23756 			    "sd_persistent_reservation_in_read_resv: "
23757 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23758 			rval = EFAULT;
23759 			goto done;
23760 		}
23761 		break;
23762 
23763 	case DDI_MODEL_NONE:
23764 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
23765 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23766 			    "sd_persistent_reservation_in_read_resv: "
23767 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23768 			rval = EFAULT;
23769 			goto done;
23770 		}
23771 		break;
23772 	}
23773 
23774 #else /* ! _MULTI_DATAMODEL */
23775 
23776 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
23777 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23778 		    "sd_persistent_reservation_in_read_resv: "
23779 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23780 		rval = EFAULT;
23781 		goto done;
23782 	}
23783 
23784 #endif /* ! _MULTI_DATAMODEL */
23785 
23786 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
23787 	bufp = resvlist.list;
23788 	copysz = sizeof (mhioc_resv_desc_t);
23789 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
23790 	    i++, readresv_ptr++, bufp++) {
23791 
23792 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
23793 		    MHIOC_RESV_KEY_SIZE);
23794 		resvdesc.type  = readresv_ptr->type;
23795 		resvdesc.scope = readresv_ptr->scope;
23796 		resvdesc.scope_specific_addr =
23797 		    BE_32(readresv_ptr->scope_specific_addr);
23798 
23799 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
23800 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23801 			    "sd_persistent_reservation_in_read_resv: "
23802 			    "failed ddi_copyout: resvlist\n");
23803 			rval = EFAULT;
23804 			goto done;
23805 		}
23806 	}
23807 done:
23808 	kmem_free(data_bufp, data_len);
23809 	return (rval);
23810 }
23811 
23812 
23813 /*
23814  *    Function: sr_change_blkmode()
23815  *
23816  * Description: This routine is the driver entry point for handling CD-ROM
23817  *		block mode ioctl requests. Support for returning and changing
23818  *		the current block size in use by the device is implemented. The
23819  *		LBA size is changed via a MODE SELECT Block Descriptor.
23820  *
23821  *		This routine issues a mode sense with an allocation length of
23822  *		12 bytes for the mode page header and a single block descriptor.
23823  *
23824  *   Arguments: dev - the device 'dev_t'
23825  *		cmd - the request type; one of CDROMGBLKMODE (get) or
23826  *		      CDROMSBLKMODE (set)
23827  *		data - current block size or requested block size
23828  *		flag - this argument is a pass through to ddi_copyxxx() directly
23829  *		       from the mode argument of ioctl().
23830  *
23831  * Return Code: the code returned by sd_send_scsi_cmd()
23832  *		EINVAL if invalid arguments are provided
23833  *		EFAULT if ddi_copyxxx() fails
23834  *		ENXIO if fail ddi_get_soft_state
23835  *		EIO if invalid mode sense block descriptor length
23836  *
23837  */
23838 
23839 static int
23840 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
23841 {
23842 	struct sd_lun			*un = NULL;
23843 	struct mode_header		*sense_mhp, *select_mhp;
23844 	struct block_descriptor		*sense_desc, *select_desc;
23845 	int				current_bsize;
23846 	int				rval = EINVAL;
23847 	uchar_t				*sense = NULL;
23848 	uchar_t				*select = NULL;
23849 
23850 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
23851 
23852 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23853 		return (ENXIO);
23854 	}
23855 
23856 	/*
23857 	 * The block length is changed via the Mode Select block descriptor, the
23858 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
23859 	 * required as part of this routine. Therefore the mode sense allocation
23860 	 * length is specified to be the length of a mode page header and a
23861 	 * block descriptor.
23862 	 */
23863 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
23864 
23865 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
23866 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD)) != 0) {
23867 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23868 		    "sr_change_blkmode: Mode Sense Failed\n");
23869 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23870 		return (rval);
23871 	}
23872 
23873 	/* Check the block descriptor len to handle only 1 block descriptor */
23874 	sense_mhp = (struct mode_header *)sense;
23875 	if ((sense_mhp->bdesc_length == 0) ||
23876 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
23877 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23878 		    "sr_change_blkmode: Mode Sense returned invalid block"
23879 		    " descriptor length\n");
23880 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23881 		return (EIO);
23882 	}
23883 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
23884 	current_bsize = ((sense_desc->blksize_hi << 16) |
23885 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
23886 
23887 	/* Process command */
23888 	switch (cmd) {
23889 	case CDROMGBLKMODE:
23890 		/* Return the block size obtained during the mode sense */
23891 		if (ddi_copyout(&current_bsize, (void *)data,
23892 		    sizeof (int), flag) != 0)
23893 			rval = EFAULT;
23894 		break;
23895 	case CDROMSBLKMODE:
23896 		/* Validate the requested block size */
23897 		switch (data) {
23898 		case CDROM_BLK_512:
23899 		case CDROM_BLK_1024:
23900 		case CDROM_BLK_2048:
23901 		case CDROM_BLK_2056:
23902 		case CDROM_BLK_2336:
23903 		case CDROM_BLK_2340:
23904 		case CDROM_BLK_2352:
23905 		case CDROM_BLK_2368:
23906 		case CDROM_BLK_2448:
23907 		case CDROM_BLK_2646:
23908 		case CDROM_BLK_2647:
23909 			break;
23910 		default:
23911 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23912 			    "sr_change_blkmode: "
23913 			    "Block Size '%ld' Not Supported\n", data);
23914 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23915 			return (EINVAL);
23916 		}
23917 
23918 		/*
23919 		 * The current block size matches the requested block size so
23920 		 * there is no need to send the mode select to change the size
23921 		 */
23922 		if (current_bsize == data) {
23923 			break;
23924 		}
23925 
23926 		/* Build the select data for the requested block size */
23927 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
23928 		select_mhp = (struct mode_header *)select;
23929 		select_desc =
23930 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
23931 		/*
23932 		 * The LBA size is changed via the block descriptor, so the
23933 		 * descriptor is built according to the user data
23934 		 */
23935 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
23936 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
23937 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
23938 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
23939 
23940 		/* Send the mode select for the requested block size */
23941 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
23942 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
23943 		    SD_PATH_STANDARD)) != 0) {
23944 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23945 			    "sr_change_blkmode: Mode Select Failed\n");
23946 			/*
23947 			 * The mode select failed for the requested block size,
23948 			 * so reset the data for the original block size and
23949 			 * send it to the target. The error is indicated by the
23950 			 * return value for the failed mode select.
23951 			 */
23952 			select_desc->blksize_hi  = sense_desc->blksize_hi;
23953 			select_desc->blksize_mid = sense_desc->blksize_mid;
23954 			select_desc->blksize_lo  = sense_desc->blksize_lo;
23955 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
23956 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
23957 			    SD_PATH_STANDARD);
23958 		} else {
23959 			ASSERT(!mutex_owned(SD_MUTEX(un)));
23960 			mutex_enter(SD_MUTEX(un));
23961 			sd_update_block_info(un, (uint32_t)data, 0);
23962 			mutex_exit(SD_MUTEX(un));
23963 		}
23964 		break;
23965 	default:
23966 		/* should not reach here, but check anyway */
23967 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23968 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
23969 		rval = EINVAL;
23970 		break;
23971 	}
23972 
23973 	if (select) {
23974 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
23975 	}
23976 	if (sense) {
23977 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23978 	}
23979 	return (rval);
23980 }
23981 
23982 
23983 /*
23984  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
23985  * implement driver support for getting and setting the CD speed. The command
23986  * set used will be based on the device type. If the device has not been
23987  * identified as MMC the Toshiba vendor specific mode page will be used. If
23988  * the device is MMC but does not support the Real Time Streaming feature
23989  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
23990  * be used to read the speed.
23991  */
23992 
23993 /*
23994  *    Function: sr_change_speed()
23995  *
23996  * Description: This routine is the driver entry point for handling CD-ROM
23997  *		drive speed ioctl requests for devices supporting the Toshiba
23998  *		vendor specific drive speed mode page. Support for returning
23999  *		and changing the current drive speed in use by the device is
24000  *		implemented.
24001  *
24002  *   Arguments: dev - the device 'dev_t'
24003  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
24004  *		      CDROMSDRVSPEED (set)
24005  *		data - current drive speed or requested drive speed
24006  *		flag - this argument is a pass through to ddi_copyxxx() directly
24007  *		       from the mode argument of ioctl().
24008  *
24009  * Return Code: the code returned by sd_send_scsi_cmd()
24010  *		EINVAL if invalid arguments are provided
24011  *		EFAULT if ddi_copyxxx() fails
24012  *		ENXIO if fail ddi_get_soft_state
24013  *		EIO if invalid mode sense block descriptor length
24014  */
24015 
24016 static int
24017 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
24018 {
24019 	struct sd_lun			*un = NULL;
24020 	struct mode_header		*sense_mhp, *select_mhp;
24021 	struct mode_speed		*sense_page, *select_page;
24022 	int				current_speed;
24023 	int				rval = EINVAL;
24024 	int				bd_len;
24025 	uchar_t				*sense = NULL;
24026 	uchar_t				*select = NULL;
24027 
24028 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
24029 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24030 		return (ENXIO);
24031 	}
24032 
24033 	/*
24034 	 * Note: The drive speed is being modified here according to a Toshiba
24035 	 * vendor specific mode page (0x31).
24036 	 */
24037 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
24038 
24039 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
24040 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
24041 	    SD_PATH_STANDARD)) != 0) {
24042 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24043 		    "sr_change_speed: Mode Sense Failed\n");
24044 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24045 		return (rval);
24046 	}
24047 	sense_mhp  = (struct mode_header *)sense;
24048 
24049 	/* Check the block descriptor len to handle only 1 block descriptor */
24050 	bd_len = sense_mhp->bdesc_length;
24051 	if (bd_len > MODE_BLK_DESC_LENGTH) {
24052 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24053 		    "sr_change_speed: Mode Sense returned invalid block "
24054 		    "descriptor length\n");
24055 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24056 		return (EIO);
24057 	}
24058 
24059 	sense_page = (struct mode_speed *)
24060 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
24061 	current_speed = sense_page->speed;
24062 
24063 	/* Process command */
24064 	switch (cmd) {
24065 	case CDROMGDRVSPEED:
24066 		/* Return the drive speed obtained during the mode sense */
24067 		if (current_speed == 0x2) {
24068 			current_speed = CDROM_TWELVE_SPEED;
24069 		}
24070 		if (ddi_copyout(&current_speed, (void *)data,
24071 		    sizeof (int), flag) != 0) {
24072 			rval = EFAULT;
24073 		}
24074 		break;
24075 	case CDROMSDRVSPEED:
24076 		/* Validate the requested drive speed */
24077 		switch ((uchar_t)data) {
24078 		case CDROM_TWELVE_SPEED:
24079 			data = 0x2;
24080 			/*FALLTHROUGH*/
24081 		case CDROM_NORMAL_SPEED:
24082 		case CDROM_DOUBLE_SPEED:
24083 		case CDROM_QUAD_SPEED:
24084 		case CDROM_MAXIMUM_SPEED:
24085 			break;
24086 		default:
24087 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24088 			    "sr_change_speed: "
24089 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
24090 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24091 			return (EINVAL);
24092 		}
24093 
24094 		/*
24095 		 * The current drive speed matches the requested drive speed so
24096 		 * there is no need to send the mode select to change the speed
24097 		 */
24098 		if (current_speed == data) {
24099 			break;
24100 		}
24101 
24102 		/* Build the select data for the requested drive speed */
24103 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
24104 		select_mhp = (struct mode_header *)select;
24105 		select_mhp->bdesc_length = 0;
24106 		select_page =
24107 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
24108 		select_page =
24109 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
24110 		select_page->mode_page.code = CDROM_MODE_SPEED;
24111 		select_page->mode_page.length = 2;
24112 		select_page->speed = (uchar_t)data;
24113 
24114 		/* Send the mode select for the requested block size */
24115 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
24116 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
24117 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
24118 			/*
24119 			 * The mode select failed for the requested drive speed,
24120 			 * so reset the data for the original drive speed and
24121 			 * send it to the target. The error is indicated by the
24122 			 * return value for the failed mode select.
24123 			 */
24124 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24125 			    "sr_drive_speed: Mode Select Failed\n");
24126 			select_page->speed = sense_page->speed;
24127 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
24128 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
24129 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
24130 		}
24131 		break;
24132 	default:
24133 		/* should not reach here, but check anyway */
24134 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24135 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
24136 		rval = EINVAL;
24137 		break;
24138 	}
24139 
24140 	if (select) {
24141 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
24142 	}
24143 	if (sense) {
24144 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24145 	}
24146 
24147 	return (rval);
24148 }
24149 
24150 
24151 /*
24152  *    Function: sr_atapi_change_speed()
24153  *
24154  * Description: This routine is the driver entry point for handling CD-ROM
24155  *		drive speed ioctl requests for MMC devices that do not support
24156  *		the Real Time Streaming feature (0x107).
24157  *
24158  *		Note: This routine will use the SET SPEED command which may not
24159  *		be supported by all devices.
24160  *
24161  *   Arguments: dev- the device 'dev_t'
24162  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
24163  *		     CDROMSDRVSPEED (set)
24164  *		data- current drive speed or requested drive speed
24165  *		flag- this argument is a pass through to ddi_copyxxx() directly
24166  *		      from the mode argument of ioctl().
24167  *
24168  * Return Code: the code returned by sd_send_scsi_cmd()
24169  *		EINVAL if invalid arguments are provided
24170  *		EFAULT if ddi_copyxxx() fails
24171  *		ENXIO if fail ddi_get_soft_state
24172  *		EIO if invalid mode sense block descriptor length
24173  */
24174 
24175 static int
24176 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
24177 {
24178 	struct sd_lun			*un;
24179 	struct uscsi_cmd		*com = NULL;
24180 	struct mode_header_grp2		*sense_mhp;
24181 	uchar_t				*sense_page;
24182 	uchar_t				*sense = NULL;
24183 	char				cdb[CDB_GROUP5];
24184 	int				bd_len;
24185 	int				current_speed = 0;
24186 	int				max_speed = 0;
24187 	int				rval;
24188 
24189 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
24190 
24191 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24192 		return (ENXIO);
24193 	}
24194 
24195 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
24196 
24197 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
24198 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
24199 	    SD_PATH_STANDARD)) != 0) {
24200 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24201 		    "sr_atapi_change_speed: Mode Sense Failed\n");
24202 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24203 		return (rval);
24204 	}
24205 
24206 	/* Check the block descriptor len to handle only 1 block descriptor */
24207 	sense_mhp = (struct mode_header_grp2 *)sense;
24208 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
24209 	if (bd_len > MODE_BLK_DESC_LENGTH) {
24210 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24211 		    "sr_atapi_change_speed: Mode Sense returned invalid "
24212 		    "block descriptor length\n");
24213 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24214 		return (EIO);
24215 	}
24216 
24217 	/* Calculate the current and maximum drive speeds */
24218 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
24219 	current_speed = (sense_page[14] << 8) | sense_page[15];
24220 	max_speed = (sense_page[8] << 8) | sense_page[9];
24221 
24222 	/* Process the command */
24223 	switch (cmd) {
24224 	case CDROMGDRVSPEED:
24225 		current_speed /= SD_SPEED_1X;
24226 		if (ddi_copyout(&current_speed, (void *)data,
24227 		    sizeof (int), flag) != 0)
24228 			rval = EFAULT;
24229 		break;
24230 	case CDROMSDRVSPEED:
24231 		/* Convert the speed code to KB/sec */
24232 		switch ((uchar_t)data) {
24233 		case CDROM_NORMAL_SPEED:
24234 			current_speed = SD_SPEED_1X;
24235 			break;
24236 		case CDROM_DOUBLE_SPEED:
24237 			current_speed = 2 * SD_SPEED_1X;
24238 			break;
24239 		case CDROM_QUAD_SPEED:
24240 			current_speed = 4 * SD_SPEED_1X;
24241 			break;
24242 		case CDROM_TWELVE_SPEED:
24243 			current_speed = 12 * SD_SPEED_1X;
24244 			break;
24245 		case CDROM_MAXIMUM_SPEED:
24246 			current_speed = 0xffff;
24247 			break;
24248 		default:
24249 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24250 			    "sr_atapi_change_speed: invalid drive speed %d\n",
24251 			    (uchar_t)data);
24252 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24253 			return (EINVAL);
24254 		}
24255 
24256 		/* Check the request against the drive's max speed. */
24257 		if (current_speed != 0xffff) {
24258 			if (current_speed > max_speed) {
24259 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24260 				return (EINVAL);
24261 			}
24262 		}
24263 
24264 		/*
24265 		 * Build and send the SET SPEED command
24266 		 *
24267 		 * Note: The SET SPEED (0xBB) command used in this routine is
24268 		 * obsolete per the SCSI MMC spec but still supported in the
24269 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
24270 		 * therefore the command is still implemented in this routine.
24271 		 */
24272 		bzero(cdb, sizeof (cdb));
24273 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
24274 		cdb[2] = (uchar_t)(current_speed >> 8);
24275 		cdb[3] = (uchar_t)current_speed;
24276 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24277 		com->uscsi_cdb	   = (caddr_t)cdb;
24278 		com->uscsi_cdblen  = CDB_GROUP5;
24279 		com->uscsi_bufaddr = NULL;
24280 		com->uscsi_buflen  = 0;
24281 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
24282 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
24283 		break;
24284 	default:
24285 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24286 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
24287 		rval = EINVAL;
24288 	}
24289 
24290 	if (sense) {
24291 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24292 	}
24293 	if (com) {
24294 		kmem_free(com, sizeof (*com));
24295 	}
24296 	return (rval);
24297 }
24298 
24299 
24300 /*
24301  *    Function: sr_pause_resume()
24302  *
24303  * Description: This routine is the driver entry point for handling CD-ROM
24304  *		pause/resume ioctl requests. This only affects the audio play
24305  *		operation.
24306  *
24307  *   Arguments: dev - the device 'dev_t'
24308  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
24309  *		      for setting the resume bit of the cdb.
24310  *
24311  * Return Code: the code returned by sd_send_scsi_cmd()
24312  *		EINVAL if invalid mode specified
24313  *
24314  */
24315 
24316 static int
24317 sr_pause_resume(dev_t dev, int cmd)
24318 {
24319 	struct sd_lun		*un;
24320 	struct uscsi_cmd	*com;
24321 	char			cdb[CDB_GROUP1];
24322 	int			rval;
24323 
24324 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24325 		return (ENXIO);
24326 	}
24327 
24328 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24329 	bzero(cdb, CDB_GROUP1);
24330 	cdb[0] = SCMD_PAUSE_RESUME;
24331 	switch (cmd) {
24332 	case CDROMRESUME:
24333 		cdb[8] = 1;
24334 		break;
24335 	case CDROMPAUSE:
24336 		cdb[8] = 0;
24337 		break;
24338 	default:
24339 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
24340 		    " Command '%x' Not Supported\n", cmd);
24341 		rval = EINVAL;
24342 		goto done;
24343 	}
24344 
24345 	com->uscsi_cdb    = cdb;
24346 	com->uscsi_cdblen = CDB_GROUP1;
24347 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24348 
24349 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24350 	    SD_PATH_STANDARD);
24351 
24352 done:
24353 	kmem_free(com, sizeof (*com));
24354 	return (rval);
24355 }
24356 
24357 
24358 /*
24359  *    Function: sr_play_msf()
24360  *
24361  * Description: This routine is the driver entry point for handling CD-ROM
24362  *		ioctl requests to output the audio signals at the specified
24363  *		starting address and continue the audio play until the specified
24364  *		ending address (CDROMPLAYMSF) The address is in Minute Second
24365  *		Frame (MSF) format.
24366  *
24367  *   Arguments: dev	- the device 'dev_t'
24368  *		data	- pointer to user provided audio msf structure,
24369  *		          specifying start/end addresses.
24370  *		flag	- this argument is a pass through to ddi_copyxxx()
24371  *		          directly from the mode argument of ioctl().
24372  *
24373  * Return Code: the code returned by sd_send_scsi_cmd()
24374  *		EFAULT if ddi_copyxxx() fails
24375  *		ENXIO if fail ddi_get_soft_state
24376  *		EINVAL if data pointer is NULL
24377  */
24378 
24379 static int
24380 sr_play_msf(dev_t dev, caddr_t data, int flag)
24381 {
24382 	struct sd_lun		*un;
24383 	struct uscsi_cmd	*com;
24384 	struct cdrom_msf	msf_struct;
24385 	struct cdrom_msf	*msf = &msf_struct;
24386 	char			cdb[CDB_GROUP1];
24387 	int			rval;
24388 
24389 	if (data == NULL) {
24390 		return (EINVAL);
24391 	}
24392 
24393 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24394 		return (ENXIO);
24395 	}
24396 
24397 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
24398 		return (EFAULT);
24399 	}
24400 
24401 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24402 	bzero(cdb, CDB_GROUP1);
24403 	cdb[0] = SCMD_PLAYAUDIO_MSF;
24404 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
24405 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
24406 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
24407 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
24408 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
24409 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
24410 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
24411 	} else {
24412 		cdb[3] = msf->cdmsf_min0;
24413 		cdb[4] = msf->cdmsf_sec0;
24414 		cdb[5] = msf->cdmsf_frame0;
24415 		cdb[6] = msf->cdmsf_min1;
24416 		cdb[7] = msf->cdmsf_sec1;
24417 		cdb[8] = msf->cdmsf_frame1;
24418 	}
24419 	com->uscsi_cdb    = cdb;
24420 	com->uscsi_cdblen = CDB_GROUP1;
24421 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24422 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24423 	    SD_PATH_STANDARD);
24424 	kmem_free(com, sizeof (*com));
24425 	return (rval);
24426 }
24427 
24428 
24429 /*
24430  *    Function: sr_play_trkind()
24431  *
24432  * Description: This routine is the driver entry point for handling CD-ROM
24433  *		ioctl requests to output the audio signals at the specified
24434  *		starting address and continue the audio play until the specified
24435  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
24436  *		format.
24437  *
24438  *   Arguments: dev	- the device 'dev_t'
24439  *		data	- pointer to user provided audio track/index structure,
24440  *		          specifying start/end addresses.
24441  *		flag	- this argument is a pass through to ddi_copyxxx()
24442  *		          directly from the mode argument of ioctl().
24443  *
24444  * Return Code: the code returned by sd_send_scsi_cmd()
24445  *		EFAULT if ddi_copyxxx() fails
24446  *		ENXIO if fail ddi_get_soft_state
24447  *		EINVAL if data pointer is NULL
24448  */
24449 
24450 static int
24451 sr_play_trkind(dev_t dev, caddr_t data, int flag)
24452 {
24453 	struct cdrom_ti		ti_struct;
24454 	struct cdrom_ti		*ti = &ti_struct;
24455 	struct uscsi_cmd	*com = NULL;
24456 	char			cdb[CDB_GROUP1];
24457 	int			rval;
24458 
24459 	if (data == NULL) {
24460 		return (EINVAL);
24461 	}
24462 
24463 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
24464 		return (EFAULT);
24465 	}
24466 
24467 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24468 	bzero(cdb, CDB_GROUP1);
24469 	cdb[0] = SCMD_PLAYAUDIO_TI;
24470 	cdb[4] = ti->cdti_trk0;
24471 	cdb[5] = ti->cdti_ind0;
24472 	cdb[7] = ti->cdti_trk1;
24473 	cdb[8] = ti->cdti_ind1;
24474 	com->uscsi_cdb    = cdb;
24475 	com->uscsi_cdblen = CDB_GROUP1;
24476 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24477 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24478 	    SD_PATH_STANDARD);
24479 	kmem_free(com, sizeof (*com));
24480 	return (rval);
24481 }
24482 
24483 
24484 /*
24485  *    Function: sr_read_all_subcodes()
24486  *
24487  * Description: This routine is the driver entry point for handling CD-ROM
24488  *		ioctl requests to return raw subcode data while the target is
24489  *		playing audio (CDROMSUBCODE).
24490  *
24491  *   Arguments: dev	- the device 'dev_t'
24492  *		data	- pointer to user provided cdrom subcode structure,
24493  *		          specifying the transfer length and address.
24494  *		flag	- this argument is a pass through to ddi_copyxxx()
24495  *		          directly from the mode argument of ioctl().
24496  *
24497  * Return Code: the code returned by sd_send_scsi_cmd()
24498  *		EFAULT if ddi_copyxxx() fails
24499  *		ENXIO if fail ddi_get_soft_state
24500  *		EINVAL if data pointer is NULL
24501  */
24502 
24503 static int
24504 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
24505 {
24506 	struct sd_lun		*un = NULL;
24507 	struct uscsi_cmd	*com = NULL;
24508 	struct cdrom_subcode	*subcode = NULL;
24509 	int			rval;
24510 	size_t			buflen;
24511 	char			cdb[CDB_GROUP5];
24512 
24513 #ifdef _MULTI_DATAMODEL
24514 	/* To support ILP32 applications in an LP64 world */
24515 	struct cdrom_subcode32		cdrom_subcode32;
24516 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
24517 #endif
24518 	if (data == NULL) {
24519 		return (EINVAL);
24520 	}
24521 
24522 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24523 		return (ENXIO);
24524 	}
24525 
24526 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
24527 
24528 #ifdef _MULTI_DATAMODEL
24529 	switch (ddi_model_convert_from(flag & FMODELS)) {
24530 	case DDI_MODEL_ILP32:
24531 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
24532 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24533 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24534 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24535 			return (EFAULT);
24536 		}
24537 		/* Convert the ILP32 uscsi data from the application to LP64 */
24538 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
24539 		break;
24540 	case DDI_MODEL_NONE:
24541 		if (ddi_copyin(data, subcode,
24542 		    sizeof (struct cdrom_subcode), flag)) {
24543 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24544 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24545 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24546 			return (EFAULT);
24547 		}
24548 		break;
24549 	}
24550 #else /* ! _MULTI_DATAMODEL */
24551 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
24552 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24553 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
24554 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24555 		return (EFAULT);
24556 	}
24557 #endif /* _MULTI_DATAMODEL */
24558 
24559 	/*
24560 	 * Since MMC-2 expects max 3 bytes for length, check if the
24561 	 * length input is greater than 3 bytes
24562 	 */
24563 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
24564 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24565 		    "sr_read_all_subcodes: "
24566 		    "cdrom transfer length too large: %d (limit %d)\n",
24567 		    subcode->cdsc_length, 0xFFFFFF);
24568 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24569 		return (EINVAL);
24570 	}
24571 
24572 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
24573 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24574 	bzero(cdb, CDB_GROUP5);
24575 
24576 	if (un->un_f_mmc_cap == TRUE) {
24577 		cdb[0] = (char)SCMD_READ_CD;
24578 		cdb[2] = (char)0xff;
24579 		cdb[3] = (char)0xff;
24580 		cdb[4] = (char)0xff;
24581 		cdb[5] = (char)0xff;
24582 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24583 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24584 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
24585 		cdb[10] = 1;
24586 	} else {
24587 		/*
24588 		 * Note: A vendor specific command (0xDF) is being used her to
24589 		 * request a read of all subcodes.
24590 		 */
24591 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
24592 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
24593 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24594 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24595 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
24596 	}
24597 	com->uscsi_cdb	   = cdb;
24598 	com->uscsi_cdblen  = CDB_GROUP5;
24599 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
24600 	com->uscsi_buflen  = buflen;
24601 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24602 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
24603 	    SD_PATH_STANDARD);
24604 	kmem_free(subcode, sizeof (struct cdrom_subcode));
24605 	kmem_free(com, sizeof (*com));
24606 	return (rval);
24607 }
24608 
24609 
24610 /*
24611  *    Function: sr_read_subchannel()
24612  *
24613  * Description: This routine is the driver entry point for handling CD-ROM
24614  *		ioctl requests to return the Q sub-channel data of the CD
24615  *		current position block. (CDROMSUBCHNL) The data includes the
24616  *		track number, index number, absolute CD-ROM address (LBA or MSF
24617  *		format per the user) , track relative CD-ROM address (LBA or MSF
24618  *		format per the user), control data and audio status.
24619  *
24620  *   Arguments: dev	- the device 'dev_t'
24621  *		data	- pointer to user provided cdrom sub-channel structure
24622  *		flag	- this argument is a pass through to ddi_copyxxx()
24623  *		          directly from the mode argument of ioctl().
24624  *
24625  * Return Code: the code returned by sd_send_scsi_cmd()
24626  *		EFAULT if ddi_copyxxx() fails
24627  *		ENXIO if fail ddi_get_soft_state
24628  *		EINVAL if data pointer is NULL
24629  */
24630 
24631 static int
24632 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
24633 {
24634 	struct sd_lun		*un;
24635 	struct uscsi_cmd	*com;
24636 	struct cdrom_subchnl	subchanel;
24637 	struct cdrom_subchnl	*subchnl = &subchanel;
24638 	char			cdb[CDB_GROUP1];
24639 	caddr_t			buffer;
24640 	int			rval;
24641 
24642 	if (data == NULL) {
24643 		return (EINVAL);
24644 	}
24645 
24646 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24647 	    (un->un_state == SD_STATE_OFFLINE)) {
24648 		return (ENXIO);
24649 	}
24650 
24651 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
24652 		return (EFAULT);
24653 	}
24654 
24655 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
24656 	bzero(cdb, CDB_GROUP1);
24657 	cdb[0] = SCMD_READ_SUBCHANNEL;
24658 	/* Set the MSF bit based on the user requested address format */
24659 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
24660 	/*
24661 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
24662 	 * returned
24663 	 */
24664 	cdb[2] = 0x40;
24665 	/*
24666 	 * Set byte 3 to specify the return data format. A value of 0x01
24667 	 * indicates that the CD-ROM current position should be returned.
24668 	 */
24669 	cdb[3] = 0x01;
24670 	cdb[8] = 0x10;
24671 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24672 	com->uscsi_cdb	   = cdb;
24673 	com->uscsi_cdblen  = CDB_GROUP1;
24674 	com->uscsi_bufaddr = buffer;
24675 	com->uscsi_buflen  = 16;
24676 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24677 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24678 	    SD_PATH_STANDARD);
24679 	if (rval != 0) {
24680 		kmem_free(buffer, 16);
24681 		kmem_free(com, sizeof (*com));
24682 		return (rval);
24683 	}
24684 
24685 	/* Process the returned Q sub-channel data */
24686 	subchnl->cdsc_audiostatus = buffer[1];
24687 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
24688 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
24689 	subchnl->cdsc_trk	= buffer[6];
24690 	subchnl->cdsc_ind	= buffer[7];
24691 	if (subchnl->cdsc_format & CDROM_LBA) {
24692 		subchnl->cdsc_absaddr.lba =
24693 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
24694 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
24695 		subchnl->cdsc_reladdr.lba =
24696 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
24697 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
24698 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
24699 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
24700 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
24701 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
24702 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
24703 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
24704 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
24705 	} else {
24706 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
24707 		subchnl->cdsc_absaddr.msf.second = buffer[10];
24708 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
24709 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
24710 		subchnl->cdsc_reladdr.msf.second = buffer[14];
24711 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
24712 	}
24713 	kmem_free(buffer, 16);
24714 	kmem_free(com, sizeof (*com));
24715 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
24716 	    != 0) {
24717 		return (EFAULT);
24718 	}
24719 	return (rval);
24720 }
24721 
24722 
24723 /*
24724  *    Function: sr_read_tocentry()
24725  *
24726  * Description: This routine is the driver entry point for handling CD-ROM
24727  *		ioctl requests to read from the Table of Contents (TOC)
24728  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
24729  *		fields, the starting address (LBA or MSF format per the user)
24730  *		and the data mode if the user specified track is a data track.
24731  *
24732  *		Note: The READ HEADER (0x44) command used in this routine is
24733  *		obsolete per the SCSI MMC spec but still supported in the
24734  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
24735  *		therefore the command is still implemented in this routine.
24736  *
24737  *   Arguments: dev	- the device 'dev_t'
24738  *		data	- pointer to user provided toc entry structure,
24739  *			  specifying the track # and the address format
24740  *			  (LBA or MSF).
24741  *		flag	- this argument is a pass through to ddi_copyxxx()
24742  *		          directly from the mode argument of ioctl().
24743  *
24744  * Return Code: the code returned by sd_send_scsi_cmd()
24745  *		EFAULT if ddi_copyxxx() fails
24746  *		ENXIO if fail ddi_get_soft_state
24747  *		EINVAL if data pointer is NULL
24748  */
24749 
24750 static int
24751 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
24752 {
24753 	struct sd_lun		*un = NULL;
24754 	struct uscsi_cmd	*com;
24755 	struct cdrom_tocentry	toc_entry;
24756 	struct cdrom_tocentry	*entry = &toc_entry;
24757 	caddr_t			buffer;
24758 	int			rval;
24759 	char			cdb[CDB_GROUP1];
24760 
24761 	if (data == NULL) {
24762 		return (EINVAL);
24763 	}
24764 
24765 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24766 	    (un->un_state == SD_STATE_OFFLINE)) {
24767 		return (ENXIO);
24768 	}
24769 
24770 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
24771 		return (EFAULT);
24772 	}
24773 
24774 	/* Validate the requested track and address format */
24775 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
24776 		return (EINVAL);
24777 	}
24778 
24779 	if (entry->cdte_track == 0) {
24780 		return (EINVAL);
24781 	}
24782 
24783 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
24784 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24785 	bzero(cdb, CDB_GROUP1);
24786 
24787 	cdb[0] = SCMD_READ_TOC;
24788 	/* Set the MSF bit based on the user requested address format  */
24789 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
24790 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
24791 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
24792 	} else {
24793 		cdb[6] = entry->cdte_track;
24794 	}
24795 
24796 	/*
24797 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
24798 	 * (4 byte TOC response header + 8 byte track descriptor)
24799 	 */
24800 	cdb[8] = 12;
24801 	com->uscsi_cdb	   = cdb;
24802 	com->uscsi_cdblen  = CDB_GROUP1;
24803 	com->uscsi_bufaddr = buffer;
24804 	com->uscsi_buflen  = 0x0C;
24805 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
24806 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24807 	    SD_PATH_STANDARD);
24808 	if (rval != 0) {
24809 		kmem_free(buffer, 12);
24810 		kmem_free(com, sizeof (*com));
24811 		return (rval);
24812 	}
24813 
24814 	/* Process the toc entry */
24815 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
24816 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
24817 	if (entry->cdte_format & CDROM_LBA) {
24818 		entry->cdte_addr.lba =
24819 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
24820 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
24821 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
24822 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
24823 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
24824 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
24825 		/*
24826 		 * Send a READ TOC command using the LBA address format to get
24827 		 * the LBA for the track requested so it can be used in the
24828 		 * READ HEADER request
24829 		 *
24830 		 * Note: The MSF bit of the READ HEADER command specifies the
24831 		 * output format. The block address specified in that command
24832 		 * must be in LBA format.
24833 		 */
24834 		cdb[1] = 0;
24835 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24836 		    SD_PATH_STANDARD);
24837 		if (rval != 0) {
24838 			kmem_free(buffer, 12);
24839 			kmem_free(com, sizeof (*com));
24840 			return (rval);
24841 		}
24842 	} else {
24843 		entry->cdte_addr.msf.minute	= buffer[9];
24844 		entry->cdte_addr.msf.second	= buffer[10];
24845 		entry->cdte_addr.msf.frame	= buffer[11];
24846 		/*
24847 		 * Send a READ TOC command using the LBA address format to get
24848 		 * the LBA for the track requested so it can be used in the
24849 		 * READ HEADER request
24850 		 *
24851 		 * Note: The MSF bit of the READ HEADER command specifies the
24852 		 * output format. The block address specified in that command
24853 		 * must be in LBA format.
24854 		 */
24855 		cdb[1] = 0;
24856 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24857 		    SD_PATH_STANDARD);
24858 		if (rval != 0) {
24859 			kmem_free(buffer, 12);
24860 			kmem_free(com, sizeof (*com));
24861 			return (rval);
24862 		}
24863 	}
24864 
24865 	/*
24866 	 * Build and send the READ HEADER command to determine the data mode of
24867 	 * the user specified track.
24868 	 */
24869 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
24870 	    (entry->cdte_track != CDROM_LEADOUT)) {
24871 		bzero(cdb, CDB_GROUP1);
24872 		cdb[0] = SCMD_READ_HEADER;
24873 		cdb[2] = buffer[8];
24874 		cdb[3] = buffer[9];
24875 		cdb[4] = buffer[10];
24876 		cdb[5] = buffer[11];
24877 		cdb[8] = 0x08;
24878 		com->uscsi_buflen = 0x08;
24879 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24880 		    SD_PATH_STANDARD);
24881 		if (rval == 0) {
24882 			entry->cdte_datamode = buffer[0];
24883 		} else {
24884 			/*
24885 			 * READ HEADER command failed, since this is
24886 			 * obsoleted in one spec, its better to return
24887 			 * -1 for an invlid track so that we can still
24888 			 * receive the rest of the TOC data.
24889 			 */
24890 			entry->cdte_datamode = (uchar_t)-1;
24891 		}
24892 	} else {
24893 		entry->cdte_datamode = (uchar_t)-1;
24894 	}
24895 
24896 	kmem_free(buffer, 12);
24897 	kmem_free(com, sizeof (*com));
24898 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
24899 		return (EFAULT);
24900 
24901 	return (rval);
24902 }
24903 
24904 
24905 /*
24906  *    Function: sr_read_tochdr()
24907  *
24908  * Description: This routine is the driver entry point for handling CD-ROM
24909  * 		ioctl requests to read the Table of Contents (TOC) header
24910  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
24911  *		and ending track numbers
24912  *
24913  *   Arguments: dev	- the device 'dev_t'
24914  *		data	- pointer to user provided toc header structure,
24915  *			  specifying the starting and ending track numbers.
24916  *		flag	- this argument is a pass through to ddi_copyxxx()
24917  *			  directly from the mode argument of ioctl().
24918  *
24919  * Return Code: the code returned by sd_send_scsi_cmd()
24920  *		EFAULT if ddi_copyxxx() fails
24921  *		ENXIO if fail ddi_get_soft_state
24922  *		EINVAL if data pointer is NULL
24923  */
24924 
24925 static int
24926 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
24927 {
24928 	struct sd_lun		*un;
24929 	struct uscsi_cmd	*com;
24930 	struct cdrom_tochdr	toc_header;
24931 	struct cdrom_tochdr	*hdr = &toc_header;
24932 	char			cdb[CDB_GROUP1];
24933 	int			rval;
24934 	caddr_t			buffer;
24935 
24936 	if (data == NULL) {
24937 		return (EINVAL);
24938 	}
24939 
24940 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24941 	    (un->un_state == SD_STATE_OFFLINE)) {
24942 		return (ENXIO);
24943 	}
24944 
24945 	buffer = kmem_zalloc(4, KM_SLEEP);
24946 	bzero(cdb, CDB_GROUP1);
24947 	cdb[0] = SCMD_READ_TOC;
24948 	/*
24949 	 * Specifying a track number of 0x00 in the READ TOC command indicates
24950 	 * that the TOC header should be returned
24951 	 */
24952 	cdb[6] = 0x00;
24953 	/*
24954 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
24955 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
24956 	 */
24957 	cdb[8] = 0x04;
24958 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24959 	com->uscsi_cdb	   = cdb;
24960 	com->uscsi_cdblen  = CDB_GROUP1;
24961 	com->uscsi_bufaddr = buffer;
24962 	com->uscsi_buflen  = 0x04;
24963 	com->uscsi_timeout = 300;
24964 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24965 
24966 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24967 	    SD_PATH_STANDARD);
24968 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
24969 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
24970 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
24971 	} else {
24972 		hdr->cdth_trk0 = buffer[2];
24973 		hdr->cdth_trk1 = buffer[3];
24974 	}
24975 	kmem_free(buffer, 4);
24976 	kmem_free(com, sizeof (*com));
24977 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
24978 		return (EFAULT);
24979 	}
24980 	return (rval);
24981 }
24982 
24983 
24984 /*
24985  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
24986  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
24987  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
24988  * digital audio and extended architecture digital audio. These modes are
24989  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
24990  * MMC specs.
24991  *
24992  * In addition to support for the various data formats these routines also
24993  * include support for devices that implement only the direct access READ
24994  * commands (0x08, 0x28), devices that implement the READ_CD commands
24995  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
24996  * READ CDXA commands (0xD8, 0xDB)
24997  */
24998 
24999 /*
25000  *    Function: sr_read_mode1()
25001  *
25002  * Description: This routine is the driver entry point for handling CD-ROM
25003  *		ioctl read mode1 requests (CDROMREADMODE1).
25004  *
25005  *   Arguments: dev	- the device 'dev_t'
25006  *		data	- pointer to user provided cd read structure specifying
25007  *			  the lba buffer address and length.
25008  *		flag	- this argument is a pass through to ddi_copyxxx()
25009  *			  directly from the mode argument of ioctl().
25010  *
25011  * Return Code: the code returned by sd_send_scsi_cmd()
25012  *		EFAULT if ddi_copyxxx() fails
25013  *		ENXIO if fail ddi_get_soft_state
25014  *		EINVAL if data pointer is NULL
25015  */
25016 
25017 static int
25018 sr_read_mode1(dev_t dev, caddr_t data, int flag)
25019 {
25020 	struct sd_lun		*un;
25021 	struct cdrom_read	mode1_struct;
25022 	struct cdrom_read	*mode1 = &mode1_struct;
25023 	int			rval;
25024 #ifdef _MULTI_DATAMODEL
25025 	/* To support ILP32 applications in an LP64 world */
25026 	struct cdrom_read32	cdrom_read32;
25027 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25028 #endif /* _MULTI_DATAMODEL */
25029 
25030 	if (data == NULL) {
25031 		return (EINVAL);
25032 	}
25033 
25034 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25035 	    (un->un_state == SD_STATE_OFFLINE)) {
25036 		return (ENXIO);
25037 	}
25038 
25039 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25040 	    "sd_read_mode1: entry: un:0x%p\n", un);
25041 
25042 #ifdef _MULTI_DATAMODEL
25043 	switch (ddi_model_convert_from(flag & FMODELS)) {
25044 	case DDI_MODEL_ILP32:
25045 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25046 			return (EFAULT);
25047 		}
25048 		/* Convert the ILP32 uscsi data from the application to LP64 */
25049 		cdrom_read32tocdrom_read(cdrd32, mode1);
25050 		break;
25051 	case DDI_MODEL_NONE:
25052 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
25053 			return (EFAULT);
25054 		}
25055 	}
25056 #else /* ! _MULTI_DATAMODEL */
25057 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
25058 		return (EFAULT);
25059 	}
25060 #endif /* _MULTI_DATAMODEL */
25061 
25062 	rval = sd_send_scsi_READ(un, mode1->cdread_bufaddr,
25063 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
25064 
25065 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25066 	    "sd_read_mode1: exit: un:0x%p\n", un);
25067 
25068 	return (rval);
25069 }
25070 
25071 
25072 /*
25073  *    Function: sr_read_cd_mode2()
25074  *
25075  * Description: This routine is the driver entry point for handling CD-ROM
25076  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
25077  *		support the READ CD (0xBE) command or the 1st generation
25078  *		READ CD (0xD4) command.
25079  *
25080  *   Arguments: dev	- the device 'dev_t'
25081  *		data	- pointer to user provided cd read structure specifying
25082  *			  the lba buffer address and length.
25083  *		flag	- this argument is a pass through to ddi_copyxxx()
25084  *			  directly from the mode argument of ioctl().
25085  *
25086  * Return Code: the code returned by sd_send_scsi_cmd()
25087  *		EFAULT if ddi_copyxxx() fails
25088  *		ENXIO if fail ddi_get_soft_state
25089  *		EINVAL if data pointer is NULL
25090  */
25091 
25092 static int
25093 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
25094 {
25095 	struct sd_lun		*un;
25096 	struct uscsi_cmd	*com;
25097 	struct cdrom_read	mode2_struct;
25098 	struct cdrom_read	*mode2 = &mode2_struct;
25099 	uchar_t			cdb[CDB_GROUP5];
25100 	int			nblocks;
25101 	int			rval;
25102 #ifdef _MULTI_DATAMODEL
25103 	/*  To support ILP32 applications in an LP64 world */
25104 	struct cdrom_read32	cdrom_read32;
25105 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25106 #endif /* _MULTI_DATAMODEL */
25107 
25108 	if (data == NULL) {
25109 		return (EINVAL);
25110 	}
25111 
25112 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25113 	    (un->un_state == SD_STATE_OFFLINE)) {
25114 		return (ENXIO);
25115 	}
25116 
25117 #ifdef _MULTI_DATAMODEL
25118 	switch (ddi_model_convert_from(flag & FMODELS)) {
25119 	case DDI_MODEL_ILP32:
25120 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25121 			return (EFAULT);
25122 		}
25123 		/* Convert the ILP32 uscsi data from the application to LP64 */
25124 		cdrom_read32tocdrom_read(cdrd32, mode2);
25125 		break;
25126 	case DDI_MODEL_NONE:
25127 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25128 			return (EFAULT);
25129 		}
25130 		break;
25131 	}
25132 
25133 #else /* ! _MULTI_DATAMODEL */
25134 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25135 		return (EFAULT);
25136 	}
25137 #endif /* _MULTI_DATAMODEL */
25138 
25139 	bzero(cdb, sizeof (cdb));
25140 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
25141 		/* Read command supported by 1st generation atapi drives */
25142 		cdb[0] = SCMD_READ_CDD4;
25143 	} else {
25144 		/* Universal CD Access Command */
25145 		cdb[0] = SCMD_READ_CD;
25146 	}
25147 
25148 	/*
25149 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
25150 	 */
25151 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
25152 
25153 	/* set the start address */
25154 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
25155 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
25156 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
25157 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
25158 
25159 	/* set the transfer length */
25160 	nblocks = mode2->cdread_buflen / 2336;
25161 	cdb[6] = (uchar_t)(nblocks >> 16);
25162 	cdb[7] = (uchar_t)(nblocks >> 8);
25163 	cdb[8] = (uchar_t)nblocks;
25164 
25165 	/* set the filter bits */
25166 	cdb[9] = CDROM_READ_CD_USERDATA;
25167 
25168 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25169 	com->uscsi_cdb = (caddr_t)cdb;
25170 	com->uscsi_cdblen = sizeof (cdb);
25171 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
25172 	com->uscsi_buflen = mode2->cdread_buflen;
25173 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25174 
25175 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25176 	    SD_PATH_STANDARD);
25177 	kmem_free(com, sizeof (*com));
25178 	return (rval);
25179 }
25180 
25181 
25182 /*
25183  *    Function: sr_read_mode2()
25184  *
25185  * Description: This routine is the driver entry point for handling CD-ROM
25186  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
25187  *		do not support the READ CD (0xBE) command.
25188  *
25189  *   Arguments: dev	- the device 'dev_t'
25190  *		data	- pointer to user provided cd read structure specifying
25191  *			  the lba buffer address and length.
25192  *		flag	- this argument is a pass through to ddi_copyxxx()
25193  *			  directly from the mode argument of ioctl().
25194  *
25195  * Return Code: the code returned by sd_send_scsi_cmd()
25196  *		EFAULT if ddi_copyxxx() fails
25197  *		ENXIO if fail ddi_get_soft_state
25198  *		EINVAL if data pointer is NULL
25199  *		EIO if fail to reset block size
25200  *		EAGAIN if commands are in progress in the driver
25201  */
25202 
25203 static int
25204 sr_read_mode2(dev_t dev, caddr_t data, int flag)
25205 {
25206 	struct sd_lun		*un;
25207 	struct cdrom_read	mode2_struct;
25208 	struct cdrom_read	*mode2 = &mode2_struct;
25209 	int			rval;
25210 	uint32_t		restore_blksize;
25211 	struct uscsi_cmd	*com;
25212 	uchar_t			cdb[CDB_GROUP0];
25213 	int			nblocks;
25214 
25215 #ifdef _MULTI_DATAMODEL
25216 	/* To support ILP32 applications in an LP64 world */
25217 	struct cdrom_read32	cdrom_read32;
25218 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25219 #endif /* _MULTI_DATAMODEL */
25220 
25221 	if (data == NULL) {
25222 		return (EINVAL);
25223 	}
25224 
25225 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25226 	    (un->un_state == SD_STATE_OFFLINE)) {
25227 		return (ENXIO);
25228 	}
25229 
25230 	/*
25231 	 * Because this routine will update the device and driver block size
25232 	 * being used we want to make sure there are no commands in progress.
25233 	 * If commands are in progress the user will have to try again.
25234 	 *
25235 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
25236 	 * in sdioctl to protect commands from sdioctl through to the top of
25237 	 * sd_uscsi_strategy. See sdioctl for details.
25238 	 */
25239 	mutex_enter(SD_MUTEX(un));
25240 	if (un->un_ncmds_in_driver != 1) {
25241 		mutex_exit(SD_MUTEX(un));
25242 		return (EAGAIN);
25243 	}
25244 	mutex_exit(SD_MUTEX(un));
25245 
25246 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25247 	    "sd_read_mode2: entry: un:0x%p\n", un);
25248 
25249 #ifdef _MULTI_DATAMODEL
25250 	switch (ddi_model_convert_from(flag & FMODELS)) {
25251 	case DDI_MODEL_ILP32:
25252 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25253 			return (EFAULT);
25254 		}
25255 		/* Convert the ILP32 uscsi data from the application to LP64 */
25256 		cdrom_read32tocdrom_read(cdrd32, mode2);
25257 		break;
25258 	case DDI_MODEL_NONE:
25259 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25260 			return (EFAULT);
25261 		}
25262 		break;
25263 	}
25264 #else /* ! _MULTI_DATAMODEL */
25265 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
25266 		return (EFAULT);
25267 	}
25268 #endif /* _MULTI_DATAMODEL */
25269 
25270 	/* Store the current target block size for restoration later */
25271 	restore_blksize = un->un_tgt_blocksize;
25272 
25273 	/* Change the device and soft state target block size to 2336 */
25274 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
25275 		rval = EIO;
25276 		goto done;
25277 	}
25278 
25279 
25280 	bzero(cdb, sizeof (cdb));
25281 
25282 	/* set READ operation */
25283 	cdb[0] = SCMD_READ;
25284 
25285 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
25286 	mode2->cdread_lba >>= 2;
25287 
25288 	/* set the start address */
25289 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
25290 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
25291 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
25292 
25293 	/* set the transfer length */
25294 	nblocks = mode2->cdread_buflen / 2336;
25295 	cdb[4] = (uchar_t)nblocks & 0xFF;
25296 
25297 	/* build command */
25298 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25299 	com->uscsi_cdb = (caddr_t)cdb;
25300 	com->uscsi_cdblen = sizeof (cdb);
25301 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
25302 	com->uscsi_buflen = mode2->cdread_buflen;
25303 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25304 
25305 	/*
25306 	 * Issue SCSI command with user space address for read buffer.
25307 	 *
25308 	 * This sends the command through main channel in the driver.
25309 	 *
25310 	 * Since this is accessed via an IOCTL call, we go through the
25311 	 * standard path, so that if the device was powered down, then
25312 	 * it would be 'awakened' to handle the command.
25313 	 */
25314 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25315 	    SD_PATH_STANDARD);
25316 
25317 	kmem_free(com, sizeof (*com));
25318 
25319 	/* Restore the device and soft state target block size */
25320 	if (sr_sector_mode(dev, restore_blksize) != 0) {
25321 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25322 		    "can't do switch back to mode 1\n");
25323 		/*
25324 		 * If sd_send_scsi_READ succeeded we still need to report
25325 		 * an error because we failed to reset the block size
25326 		 */
25327 		if (rval == 0) {
25328 			rval = EIO;
25329 		}
25330 	}
25331 
25332 done:
25333 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25334 	    "sd_read_mode2: exit: un:0x%p\n", un);
25335 
25336 	return (rval);
25337 }
25338 
25339 
25340 /*
25341  *    Function: sr_sector_mode()
25342  *
25343  * Description: This utility function is used by sr_read_mode2 to set the target
25344  *		block size based on the user specified size. This is a legacy
25345  *		implementation based upon a vendor specific mode page
25346  *
25347  *   Arguments: dev	- the device 'dev_t'
25348  *		data	- flag indicating if block size is being set to 2336 or
25349  *			  512.
25350  *
25351  * Return Code: the code returned by sd_send_scsi_cmd()
25352  *		EFAULT if ddi_copyxxx() fails
25353  *		ENXIO if fail ddi_get_soft_state
25354  *		EINVAL if data pointer is NULL
25355  */
25356 
25357 static int
25358 sr_sector_mode(dev_t dev, uint32_t blksize)
25359 {
25360 	struct sd_lun	*un;
25361 	uchar_t		*sense;
25362 	uchar_t		*select;
25363 	int		rval;
25364 
25365 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25366 	    (un->un_state == SD_STATE_OFFLINE)) {
25367 		return (ENXIO);
25368 	}
25369 
25370 	sense = kmem_zalloc(20, KM_SLEEP);
25371 
25372 	/* Note: This is a vendor specific mode page (0x81) */
25373 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, 20, 0x81,
25374 	    SD_PATH_STANDARD)) != 0) {
25375 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25376 		    "sr_sector_mode: Mode Sense failed\n");
25377 		kmem_free(sense, 20);
25378 		return (rval);
25379 	}
25380 	select = kmem_zalloc(20, KM_SLEEP);
25381 	select[3] = 0x08;
25382 	select[10] = ((blksize >> 8) & 0xff);
25383 	select[11] = (blksize & 0xff);
25384 	select[12] = 0x01;
25385 	select[13] = 0x06;
25386 	select[14] = sense[14];
25387 	select[15] = sense[15];
25388 	if (blksize == SD_MODE2_BLKSIZE) {
25389 		select[14] |= 0x01;
25390 	}
25391 
25392 	if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select, 20,
25393 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
25394 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25395 		    "sr_sector_mode: Mode Select failed\n");
25396 	} else {
25397 		/*
25398 		 * Only update the softstate block size if we successfully
25399 		 * changed the device block mode.
25400 		 */
25401 		mutex_enter(SD_MUTEX(un));
25402 		sd_update_block_info(un, blksize, 0);
25403 		mutex_exit(SD_MUTEX(un));
25404 	}
25405 	kmem_free(sense, 20);
25406 	kmem_free(select, 20);
25407 	return (rval);
25408 }
25409 
25410 
25411 /*
25412  *    Function: sr_read_cdda()
25413  *
25414  * Description: This routine is the driver entry point for handling CD-ROM
25415  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
25416  *		the target supports CDDA these requests are handled via a vendor
25417  *		specific command (0xD8) If the target does not support CDDA
25418  *		these requests are handled via the READ CD command (0xBE).
25419  *
25420  *   Arguments: dev	- the device 'dev_t'
25421  *		data	- pointer to user provided CD-DA structure specifying
25422  *			  the track starting address, transfer length, and
25423  *			  subcode options.
25424  *		flag	- this argument is a pass through to ddi_copyxxx()
25425  *			  directly from the mode argument of ioctl().
25426  *
25427  * Return Code: the code returned by sd_send_scsi_cmd()
25428  *		EFAULT if ddi_copyxxx() fails
25429  *		ENXIO if fail ddi_get_soft_state
25430  *		EINVAL if invalid arguments are provided
25431  *		ENOTTY
25432  */
25433 
25434 static int
25435 sr_read_cdda(dev_t dev, caddr_t data, int flag)
25436 {
25437 	struct sd_lun			*un;
25438 	struct uscsi_cmd		*com;
25439 	struct cdrom_cdda		*cdda;
25440 	int				rval;
25441 	size_t				buflen;
25442 	char				cdb[CDB_GROUP5];
25443 
25444 #ifdef _MULTI_DATAMODEL
25445 	/* To support ILP32 applications in an LP64 world */
25446 	struct cdrom_cdda32	cdrom_cdda32;
25447 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
25448 #endif /* _MULTI_DATAMODEL */
25449 
25450 	if (data == NULL) {
25451 		return (EINVAL);
25452 	}
25453 
25454 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25455 		return (ENXIO);
25456 	}
25457 
25458 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
25459 
25460 #ifdef _MULTI_DATAMODEL
25461 	switch (ddi_model_convert_from(flag & FMODELS)) {
25462 	case DDI_MODEL_ILP32:
25463 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
25464 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25465 			    "sr_read_cdda: ddi_copyin Failed\n");
25466 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25467 			return (EFAULT);
25468 		}
25469 		/* Convert the ILP32 uscsi data from the application to LP64 */
25470 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
25471 		break;
25472 	case DDI_MODEL_NONE:
25473 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25474 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25475 			    "sr_read_cdda: ddi_copyin Failed\n");
25476 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25477 			return (EFAULT);
25478 		}
25479 		break;
25480 	}
25481 #else /* ! _MULTI_DATAMODEL */
25482 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25483 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25484 		    "sr_read_cdda: ddi_copyin Failed\n");
25485 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25486 		return (EFAULT);
25487 	}
25488 #endif /* _MULTI_DATAMODEL */
25489 
25490 	/*
25491 	 * Since MMC-2 expects max 3 bytes for length, check if the
25492 	 * length input is greater than 3 bytes
25493 	 */
25494 	if ((cdda->cdda_length & 0xFF000000) != 0) {
25495 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
25496 		    "cdrom transfer length too large: %d (limit %d)\n",
25497 		    cdda->cdda_length, 0xFFFFFF);
25498 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25499 		return (EINVAL);
25500 	}
25501 
25502 	switch (cdda->cdda_subcode) {
25503 	case CDROM_DA_NO_SUBCODE:
25504 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
25505 		break;
25506 	case CDROM_DA_SUBQ:
25507 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
25508 		break;
25509 	case CDROM_DA_ALL_SUBCODE:
25510 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
25511 		break;
25512 	case CDROM_DA_SUBCODE_ONLY:
25513 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
25514 		break;
25515 	default:
25516 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25517 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
25518 		    cdda->cdda_subcode);
25519 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25520 		return (EINVAL);
25521 	}
25522 
25523 	/* Build and send the command */
25524 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25525 	bzero(cdb, CDB_GROUP5);
25526 
25527 	if (un->un_f_cfg_cdda == TRUE) {
25528 		cdb[0] = (char)SCMD_READ_CD;
25529 		cdb[1] = 0x04;
25530 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25531 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25532 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25533 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25534 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25535 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25536 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
25537 		cdb[9] = 0x10;
25538 		switch (cdda->cdda_subcode) {
25539 		case CDROM_DA_NO_SUBCODE :
25540 			cdb[10] = 0x0;
25541 			break;
25542 		case CDROM_DA_SUBQ :
25543 			cdb[10] = 0x2;
25544 			break;
25545 		case CDROM_DA_ALL_SUBCODE :
25546 			cdb[10] = 0x1;
25547 			break;
25548 		case CDROM_DA_SUBCODE_ONLY :
25549 			/* FALLTHROUGH */
25550 		default :
25551 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25552 			kmem_free(com, sizeof (*com));
25553 			return (ENOTTY);
25554 		}
25555 	} else {
25556 		cdb[0] = (char)SCMD_READ_CDDA;
25557 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25558 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25559 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25560 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25561 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
25562 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25563 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25564 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
25565 		cdb[10] = cdda->cdda_subcode;
25566 	}
25567 
25568 	com->uscsi_cdb = cdb;
25569 	com->uscsi_cdblen = CDB_GROUP5;
25570 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
25571 	com->uscsi_buflen = buflen;
25572 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25573 
25574 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25575 	    SD_PATH_STANDARD);
25576 
25577 	kmem_free(cdda, sizeof (struct cdrom_cdda));
25578 	kmem_free(com, sizeof (*com));
25579 	return (rval);
25580 }
25581 
25582 
25583 /*
25584  *    Function: sr_read_cdxa()
25585  *
25586  * Description: This routine is the driver entry point for handling CD-ROM
25587  *		ioctl requests to return CD-XA (Extended Architecture) data.
25588  *		(CDROMCDXA).
25589  *
25590  *   Arguments: dev	- the device 'dev_t'
25591  *		data	- pointer to user provided CD-XA structure specifying
25592  *			  the data starting address, transfer length, and format
25593  *		flag	- this argument is a pass through to ddi_copyxxx()
25594  *			  directly from the mode argument of ioctl().
25595  *
25596  * Return Code: the code returned by sd_send_scsi_cmd()
25597  *		EFAULT if ddi_copyxxx() fails
25598  *		ENXIO if fail ddi_get_soft_state
25599  *		EINVAL if data pointer is NULL
25600  */
25601 
25602 static int
25603 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
25604 {
25605 	struct sd_lun		*un;
25606 	struct uscsi_cmd	*com;
25607 	struct cdrom_cdxa	*cdxa;
25608 	int			rval;
25609 	size_t			buflen;
25610 	char			cdb[CDB_GROUP5];
25611 	uchar_t			read_flags;
25612 
25613 #ifdef _MULTI_DATAMODEL
25614 	/* To support ILP32 applications in an LP64 world */
25615 	struct cdrom_cdxa32		cdrom_cdxa32;
25616 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
25617 #endif /* _MULTI_DATAMODEL */
25618 
25619 	if (data == NULL) {
25620 		return (EINVAL);
25621 	}
25622 
25623 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25624 		return (ENXIO);
25625 	}
25626 
25627 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
25628 
25629 #ifdef _MULTI_DATAMODEL
25630 	switch (ddi_model_convert_from(flag & FMODELS)) {
25631 	case DDI_MODEL_ILP32:
25632 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
25633 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25634 			return (EFAULT);
25635 		}
25636 		/*
25637 		 * Convert the ILP32 uscsi data from the
25638 		 * application to LP64 for internal use.
25639 		 */
25640 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
25641 		break;
25642 	case DDI_MODEL_NONE:
25643 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25644 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25645 			return (EFAULT);
25646 		}
25647 		break;
25648 	}
25649 #else /* ! _MULTI_DATAMODEL */
25650 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25651 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25652 		return (EFAULT);
25653 	}
25654 #endif /* _MULTI_DATAMODEL */
25655 
25656 	/*
25657 	 * Since MMC-2 expects max 3 bytes for length, check if the
25658 	 * length input is greater than 3 bytes
25659 	 */
25660 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
25661 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
25662 		    "cdrom transfer length too large: %d (limit %d)\n",
25663 		    cdxa->cdxa_length, 0xFFFFFF);
25664 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25665 		return (EINVAL);
25666 	}
25667 
25668 	switch (cdxa->cdxa_format) {
25669 	case CDROM_XA_DATA:
25670 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
25671 		read_flags = 0x10;
25672 		break;
25673 	case CDROM_XA_SECTOR_DATA:
25674 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
25675 		read_flags = 0xf8;
25676 		break;
25677 	case CDROM_XA_DATA_W_ERROR:
25678 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
25679 		read_flags = 0xfc;
25680 		break;
25681 	default:
25682 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25683 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
25684 		    cdxa->cdxa_format);
25685 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25686 		return (EINVAL);
25687 	}
25688 
25689 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25690 	bzero(cdb, CDB_GROUP5);
25691 	if (un->un_f_mmc_cap == TRUE) {
25692 		cdb[0] = (char)SCMD_READ_CD;
25693 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25694 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25695 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25696 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25697 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25698 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25699 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
25700 		cdb[9] = (char)read_flags;
25701 	} else {
25702 		/*
25703 		 * Note: A vendor specific command (0xDB) is being used her to
25704 		 * request a read of all subcodes.
25705 		 */
25706 		cdb[0] = (char)SCMD_READ_CDXA;
25707 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25708 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25709 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25710 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25711 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
25712 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25713 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25714 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
25715 		cdb[10] = cdxa->cdxa_format;
25716 	}
25717 	com->uscsi_cdb	   = cdb;
25718 	com->uscsi_cdblen  = CDB_GROUP5;
25719 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
25720 	com->uscsi_buflen  = buflen;
25721 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25722 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25723 	    SD_PATH_STANDARD);
25724 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25725 	kmem_free(com, sizeof (*com));
25726 	return (rval);
25727 }
25728 
25729 
25730 /*
25731  *    Function: sr_eject()
25732  *
25733  * Description: This routine is the driver entry point for handling CD-ROM
25734  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
25735  *
25736  *   Arguments: dev	- the device 'dev_t'
25737  *
25738  * Return Code: the code returned by sd_send_scsi_cmd()
25739  */
25740 
25741 static int
25742 sr_eject(dev_t dev)
25743 {
25744 	struct sd_lun	*un;
25745 	int		rval;
25746 
25747 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25748 	    (un->un_state == SD_STATE_OFFLINE)) {
25749 		return (ENXIO);
25750 	}
25751 
25752 	/*
25753 	 * To prevent race conditions with the eject
25754 	 * command, keep track of an eject command as
25755 	 * it progresses. If we are already handling
25756 	 * an eject command in the driver for the given
25757 	 * unit and another request to eject is received
25758 	 * immediately return EAGAIN so we don't lose
25759 	 * the command if the current eject command fails.
25760 	 */
25761 	mutex_enter(SD_MUTEX(un));
25762 	if (un->un_f_ejecting == TRUE) {
25763 		mutex_exit(SD_MUTEX(un));
25764 		return (EAGAIN);
25765 	}
25766 	un->un_f_ejecting = TRUE;
25767 	mutex_exit(SD_MUTEX(un));
25768 
25769 	if ((rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
25770 	    SD_PATH_STANDARD)) != 0) {
25771 		mutex_enter(SD_MUTEX(un));
25772 		un->un_f_ejecting = FALSE;
25773 		mutex_exit(SD_MUTEX(un));
25774 		return (rval);
25775 	}
25776 
25777 	rval = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_EJECT,
25778 	    SD_PATH_STANDARD);
25779 
25780 	if (rval == 0) {
25781 		mutex_enter(SD_MUTEX(un));
25782 		sr_ejected(un);
25783 		un->un_mediastate = DKIO_EJECTED;
25784 		un->un_f_ejecting = FALSE;
25785 		cv_broadcast(&un->un_state_cv);
25786 		mutex_exit(SD_MUTEX(un));
25787 	} else {
25788 		mutex_enter(SD_MUTEX(un));
25789 		un->un_f_ejecting = FALSE;
25790 		mutex_exit(SD_MUTEX(un));
25791 	}
25792 	return (rval);
25793 }
25794 
25795 
25796 /*
25797  *    Function: sr_ejected()
25798  *
25799  * Description: This routine updates the soft state structure to invalidate the
25800  *		geometry information after the media has been ejected or a
25801  *		media eject has been detected.
25802  *
25803  *   Arguments: un - driver soft state (unit) structure
25804  */
25805 
25806 static void
25807 sr_ejected(struct sd_lun *un)
25808 {
25809 	struct sd_errstats *stp;
25810 
25811 	ASSERT(un != NULL);
25812 	ASSERT(mutex_owned(SD_MUTEX(un)));
25813 
25814 	un->un_f_blockcount_is_valid	= FALSE;
25815 	un->un_f_tgt_blocksize_is_valid	= FALSE;
25816 	mutex_exit(SD_MUTEX(un));
25817 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
25818 	mutex_enter(SD_MUTEX(un));
25819 
25820 	if (un->un_errstats != NULL) {
25821 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
25822 		stp->sd_capacity.value.ui64 = 0;
25823 	}
25824 
25825 	/* remove "capacity-of-device" properties */
25826 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
25827 	    "device-nblocks");
25828 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
25829 	    "device-blksize");
25830 }
25831 
25832 
25833 /*
25834  *    Function: sr_check_wp()
25835  *
25836  * Description: This routine checks the write protection of a removable
25837  *      media disk and hotpluggable devices via the write protect bit of
25838  *      the Mode Page Header device specific field. Some devices choke
25839  *      on unsupported mode page. In order to workaround this issue,
25840  *      this routine has been implemented to use 0x3f mode page(request
25841  *      for all pages) for all device types.
25842  *
25843  *   Arguments: dev		- the device 'dev_t'
25844  *
25845  * Return Code: int indicating if the device is write protected (1) or not (0)
25846  *
25847  *     Context: Kernel thread.
25848  *
25849  */
25850 
25851 static int
25852 sr_check_wp(dev_t dev)
25853 {
25854 	struct sd_lun	*un;
25855 	uchar_t		device_specific;
25856 	uchar_t		*sense;
25857 	int		hdrlen;
25858 	int		rval = FALSE;
25859 
25860 	/*
25861 	 * Note: The return codes for this routine should be reworked to
25862 	 * properly handle the case of a NULL softstate.
25863 	 */
25864 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25865 		return (FALSE);
25866 	}
25867 
25868 	if (un->un_f_cfg_is_atapi == TRUE) {
25869 		/*
25870 		 * The mode page contents are not required; set the allocation
25871 		 * length for the mode page header only
25872 		 */
25873 		hdrlen = MODE_HEADER_LENGTH_GRP2;
25874 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
25875 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense, hdrlen,
25876 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
25877 			goto err_exit;
25878 		device_specific =
25879 		    ((struct mode_header_grp2 *)sense)->device_specific;
25880 	} else {
25881 		hdrlen = MODE_HEADER_LENGTH;
25882 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
25883 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, hdrlen,
25884 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
25885 			goto err_exit;
25886 		device_specific =
25887 		    ((struct mode_header *)sense)->device_specific;
25888 	}
25889 
25890 	/*
25891 	 * Write protect mode sense failed; not all disks
25892 	 * understand this query. Return FALSE assuming that
25893 	 * these devices are not writable.
25894 	 */
25895 	if (device_specific & WRITE_PROTECT) {
25896 		rval = TRUE;
25897 	}
25898 
25899 err_exit:
25900 	kmem_free(sense, hdrlen);
25901 	return (rval);
25902 }
25903 
25904 /*
25905  *    Function: sr_volume_ctrl()
25906  *
25907  * Description: This routine is the driver entry point for handling CD-ROM
25908  *		audio output volume ioctl requests. (CDROMVOLCTRL)
25909  *
25910  *   Arguments: dev	- the device 'dev_t'
25911  *		data	- pointer to user audio volume control structure
25912  *		flag	- this argument is a pass through to ddi_copyxxx()
25913  *			  directly from the mode argument of ioctl().
25914  *
25915  * Return Code: the code returned by sd_send_scsi_cmd()
25916  *		EFAULT if ddi_copyxxx() fails
25917  *		ENXIO if fail ddi_get_soft_state
25918  *		EINVAL if data pointer is NULL
25919  *
25920  */
25921 
25922 static int
25923 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
25924 {
25925 	struct sd_lun		*un;
25926 	struct cdrom_volctrl    volume;
25927 	struct cdrom_volctrl    *vol = &volume;
25928 	uchar_t			*sense_page;
25929 	uchar_t			*select_page;
25930 	uchar_t			*sense;
25931 	uchar_t			*select;
25932 	int			sense_buflen;
25933 	int			select_buflen;
25934 	int			rval;
25935 
25936 	if (data == NULL) {
25937 		return (EINVAL);
25938 	}
25939 
25940 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25941 	    (un->un_state == SD_STATE_OFFLINE)) {
25942 		return (ENXIO);
25943 	}
25944 
25945 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
25946 		return (EFAULT);
25947 	}
25948 
25949 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
25950 		struct mode_header_grp2		*sense_mhp;
25951 		struct mode_header_grp2		*select_mhp;
25952 		int				bd_len;
25953 
25954 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
25955 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
25956 		    MODEPAGE_AUDIO_CTRL_LEN;
25957 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
25958 		select = kmem_zalloc(select_buflen, KM_SLEEP);
25959 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
25960 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
25961 		    SD_PATH_STANDARD)) != 0) {
25962 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25963 			    "sr_volume_ctrl: Mode Sense Failed\n");
25964 			kmem_free(sense, sense_buflen);
25965 			kmem_free(select, select_buflen);
25966 			return (rval);
25967 		}
25968 		sense_mhp = (struct mode_header_grp2 *)sense;
25969 		select_mhp = (struct mode_header_grp2 *)select;
25970 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
25971 		    sense_mhp->bdesc_length_lo;
25972 		if (bd_len > MODE_BLK_DESC_LENGTH) {
25973 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25974 			    "sr_volume_ctrl: Mode Sense returned invalid "
25975 			    "block descriptor length\n");
25976 			kmem_free(sense, sense_buflen);
25977 			kmem_free(select, select_buflen);
25978 			return (EIO);
25979 		}
25980 		sense_page = (uchar_t *)
25981 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
25982 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
25983 		select_mhp->length_msb = 0;
25984 		select_mhp->length_lsb = 0;
25985 		select_mhp->bdesc_length_hi = 0;
25986 		select_mhp->bdesc_length_lo = 0;
25987 	} else {
25988 		struct mode_header		*sense_mhp, *select_mhp;
25989 
25990 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
25991 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
25992 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
25993 		select = kmem_zalloc(select_buflen, KM_SLEEP);
25994 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
25995 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
25996 		    SD_PATH_STANDARD)) != 0) {
25997 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25998 			    "sr_volume_ctrl: Mode Sense Failed\n");
25999 			kmem_free(sense, sense_buflen);
26000 			kmem_free(select, select_buflen);
26001 			return (rval);
26002 		}
26003 		sense_mhp  = (struct mode_header *)sense;
26004 		select_mhp = (struct mode_header *)select;
26005 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
26006 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26007 			    "sr_volume_ctrl: Mode Sense returned invalid "
26008 			    "block descriptor length\n");
26009 			kmem_free(sense, sense_buflen);
26010 			kmem_free(select, select_buflen);
26011 			return (EIO);
26012 		}
26013 		sense_page = (uchar_t *)
26014 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
26015 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
26016 		select_mhp->length = 0;
26017 		select_mhp->bdesc_length = 0;
26018 	}
26019 	/*
26020 	 * Note: An audio control data structure could be created and overlayed
26021 	 * on the following in place of the array indexing method implemented.
26022 	 */
26023 
26024 	/* Build the select data for the user volume data */
26025 	select_page[0] = MODEPAGE_AUDIO_CTRL;
26026 	select_page[1] = 0xE;
26027 	/* Set the immediate bit */
26028 	select_page[2] = 0x04;
26029 	/* Zero out reserved fields */
26030 	select_page[3] = 0x00;
26031 	select_page[4] = 0x00;
26032 	/* Return sense data for fields not to be modified */
26033 	select_page[5] = sense_page[5];
26034 	select_page[6] = sense_page[6];
26035 	select_page[7] = sense_page[7];
26036 	/* Set the user specified volume levels for channel 0 and 1 */
26037 	select_page[8] = 0x01;
26038 	select_page[9] = vol->channel0;
26039 	select_page[10] = 0x02;
26040 	select_page[11] = vol->channel1;
26041 	/* Channel 2 and 3 are currently unsupported so return the sense data */
26042 	select_page[12] = sense_page[12];
26043 	select_page[13] = sense_page[13];
26044 	select_page[14] = sense_page[14];
26045 	select_page[15] = sense_page[15];
26046 
26047 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
26048 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, select,
26049 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
26050 	} else {
26051 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
26052 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
26053 	}
26054 
26055 	kmem_free(sense, sense_buflen);
26056 	kmem_free(select, select_buflen);
26057 	return (rval);
26058 }
26059 
26060 
26061 /*
26062  *    Function: sr_read_sony_session_offset()
26063  *
26064  * Description: This routine is the driver entry point for handling CD-ROM
26065  *		ioctl requests for session offset information. (CDROMREADOFFSET)
26066  *		The address of the first track in the last session of a
26067  *		multi-session CD-ROM is returned
26068  *
26069  *		Note: This routine uses a vendor specific key value in the
26070  *		command control field without implementing any vendor check here
26071  *		or in the ioctl routine.
26072  *
26073  *   Arguments: dev	- the device 'dev_t'
26074  *		data	- pointer to an int to hold the requested address
26075  *		flag	- this argument is a pass through to ddi_copyxxx()
26076  *			  directly from the mode argument of ioctl().
26077  *
26078  * Return Code: the code returned by sd_send_scsi_cmd()
26079  *		EFAULT if ddi_copyxxx() fails
26080  *		ENXIO if fail ddi_get_soft_state
26081  *		EINVAL if data pointer is NULL
26082  */
26083 
26084 static int
26085 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
26086 {
26087 	struct sd_lun		*un;
26088 	struct uscsi_cmd	*com;
26089 	caddr_t			buffer;
26090 	char			cdb[CDB_GROUP1];
26091 	int			session_offset = 0;
26092 	int			rval;
26093 
26094 	if (data == NULL) {
26095 		return (EINVAL);
26096 	}
26097 
26098 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26099 	    (un->un_state == SD_STATE_OFFLINE)) {
26100 		return (ENXIO);
26101 	}
26102 
26103 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
26104 	bzero(cdb, CDB_GROUP1);
26105 	cdb[0] = SCMD_READ_TOC;
26106 	/*
26107 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
26108 	 * (4 byte TOC response header + 8 byte response data)
26109 	 */
26110 	cdb[8] = SONY_SESSION_OFFSET_LEN;
26111 	/* Byte 9 is the control byte. A vendor specific value is used */
26112 	cdb[9] = SONY_SESSION_OFFSET_KEY;
26113 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26114 	com->uscsi_cdb = cdb;
26115 	com->uscsi_cdblen = CDB_GROUP1;
26116 	com->uscsi_bufaddr = buffer;
26117 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
26118 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26119 
26120 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26121 	    SD_PATH_STANDARD);
26122 	if (rval != 0) {
26123 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
26124 		kmem_free(com, sizeof (*com));
26125 		return (rval);
26126 	}
26127 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
26128 		session_offset =
26129 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
26130 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
26131 		/*
26132 		 * Offset returned offset in current lbasize block's. Convert to
26133 		 * 2k block's to return to the user
26134 		 */
26135 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
26136 			session_offset >>= 2;
26137 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
26138 			session_offset >>= 1;
26139 		}
26140 	}
26141 
26142 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
26143 		rval = EFAULT;
26144 	}
26145 
26146 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
26147 	kmem_free(com, sizeof (*com));
26148 	return (rval);
26149 }
26150 
26151 
26152 /*
26153  *    Function: sd_wm_cache_constructor()
26154  *
26155  * Description: Cache Constructor for the wmap cache for the read/modify/write
26156  * 		devices.
26157  *
26158  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
26159  *		un	- sd_lun structure for the device.
26160  *		flag	- the km flags passed to constructor
26161  *
26162  * Return Code: 0 on success.
26163  *		-1 on failure.
26164  */
26165 
26166 /*ARGSUSED*/
26167 static int
26168 sd_wm_cache_constructor(void *wm, void *un, int flags)
26169 {
26170 	bzero(wm, sizeof (struct sd_w_map));
26171 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
26172 	return (0);
26173 }
26174 
26175 
26176 /*
26177  *    Function: sd_wm_cache_destructor()
26178  *
26179  * Description: Cache destructor for the wmap cache for the read/modify/write
26180  * 		devices.
26181  *
26182  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
26183  *		un	- sd_lun structure for the device.
26184  */
26185 /*ARGSUSED*/
26186 static void
26187 sd_wm_cache_destructor(void *wm, void *un)
26188 {
26189 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
26190 }
26191 
26192 
26193 /*
26194  *    Function: sd_range_lock()
26195  *
26196  * Description: Lock the range of blocks specified as parameter to ensure
26197  *		that read, modify write is atomic and no other i/o writes
26198  *		to the same location. The range is specified in terms
26199  *		of start and end blocks. Block numbers are the actual
26200  *		media block numbers and not system.
26201  *
26202  *   Arguments: un	- sd_lun structure for the device.
26203  *		startb - The starting block number
26204  *		endb - The end block number
26205  *		typ - type of i/o - simple/read_modify_write
26206  *
26207  * Return Code: wm  - pointer to the wmap structure.
26208  *
26209  *     Context: This routine can sleep.
26210  */
26211 
26212 static struct sd_w_map *
26213 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
26214 {
26215 	struct sd_w_map *wmp = NULL;
26216 	struct sd_w_map *sl_wmp = NULL;
26217 	struct sd_w_map *tmp_wmp;
26218 	wm_state state = SD_WM_CHK_LIST;
26219 
26220 
26221 	ASSERT(un != NULL);
26222 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26223 
26224 	mutex_enter(SD_MUTEX(un));
26225 
26226 	while (state != SD_WM_DONE) {
26227 
26228 		switch (state) {
26229 		case SD_WM_CHK_LIST:
26230 			/*
26231 			 * This is the starting state. Check the wmap list
26232 			 * to see if the range is currently available.
26233 			 */
26234 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
26235 				/*
26236 				 * If this is a simple write and no rmw
26237 				 * i/o is pending then try to lock the
26238 				 * range as the range should be available.
26239 				 */
26240 				state = SD_WM_LOCK_RANGE;
26241 			} else {
26242 				tmp_wmp = sd_get_range(un, startb, endb);
26243 				if (tmp_wmp != NULL) {
26244 					if ((wmp != NULL) && ONLIST(un, wmp)) {
26245 						/*
26246 						 * Should not keep onlist wmps
26247 						 * while waiting this macro
26248 						 * will also do wmp = NULL;
26249 						 */
26250 						FREE_ONLIST_WMAP(un, wmp);
26251 					}
26252 					/*
26253 					 * sl_wmp is the wmap on which wait
26254 					 * is done, since the tmp_wmp points
26255 					 * to the inuse wmap, set sl_wmp to
26256 					 * tmp_wmp and change the state to sleep
26257 					 */
26258 					sl_wmp = tmp_wmp;
26259 					state = SD_WM_WAIT_MAP;
26260 				} else {
26261 					state = SD_WM_LOCK_RANGE;
26262 				}
26263 
26264 			}
26265 			break;
26266 
26267 		case SD_WM_LOCK_RANGE:
26268 			ASSERT(un->un_wm_cache);
26269 			/*
26270 			 * The range need to be locked, try to get a wmap.
26271 			 * First attempt it with NO_SLEEP, want to avoid a sleep
26272 			 * if possible as we will have to release the sd mutex
26273 			 * if we have to sleep.
26274 			 */
26275 			if (wmp == NULL)
26276 				wmp = kmem_cache_alloc(un->un_wm_cache,
26277 				    KM_NOSLEEP);
26278 			if (wmp == NULL) {
26279 				mutex_exit(SD_MUTEX(un));
26280 				_NOTE(DATA_READABLE_WITHOUT_LOCK
26281 				    (sd_lun::un_wm_cache))
26282 				wmp = kmem_cache_alloc(un->un_wm_cache,
26283 				    KM_SLEEP);
26284 				mutex_enter(SD_MUTEX(un));
26285 				/*
26286 				 * we released the mutex so recheck and go to
26287 				 * check list state.
26288 				 */
26289 				state = SD_WM_CHK_LIST;
26290 			} else {
26291 				/*
26292 				 * We exit out of state machine since we
26293 				 * have the wmap. Do the housekeeping first.
26294 				 * place the wmap on the wmap list if it is not
26295 				 * on it already and then set the state to done.
26296 				 */
26297 				wmp->wm_start = startb;
26298 				wmp->wm_end = endb;
26299 				wmp->wm_flags = typ | SD_WM_BUSY;
26300 				if (typ & SD_WTYPE_RMW) {
26301 					un->un_rmw_count++;
26302 				}
26303 				/*
26304 				 * If not already on the list then link
26305 				 */
26306 				if (!ONLIST(un, wmp)) {
26307 					wmp->wm_next = un->un_wm;
26308 					wmp->wm_prev = NULL;
26309 					if (wmp->wm_next)
26310 						wmp->wm_next->wm_prev = wmp;
26311 					un->un_wm = wmp;
26312 				}
26313 				state = SD_WM_DONE;
26314 			}
26315 			break;
26316 
26317 		case SD_WM_WAIT_MAP:
26318 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
26319 			/*
26320 			 * Wait is done on sl_wmp, which is set in the
26321 			 * check_list state.
26322 			 */
26323 			sl_wmp->wm_wanted_count++;
26324 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
26325 			sl_wmp->wm_wanted_count--;
26326 			/*
26327 			 * We can reuse the memory from the completed sl_wmp
26328 			 * lock range for our new lock, but only if noone is
26329 			 * waiting for it.
26330 			 */
26331 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
26332 			if (sl_wmp->wm_wanted_count == 0) {
26333 				if (wmp != NULL)
26334 					CHK_N_FREEWMP(un, wmp);
26335 				wmp = sl_wmp;
26336 			}
26337 			sl_wmp = NULL;
26338 			/*
26339 			 * After waking up, need to recheck for availability of
26340 			 * range.
26341 			 */
26342 			state = SD_WM_CHK_LIST;
26343 			break;
26344 
26345 		default:
26346 			panic("sd_range_lock: "
26347 			    "Unknown state %d in sd_range_lock", state);
26348 			/*NOTREACHED*/
26349 		} /* switch(state) */
26350 
26351 	} /* while(state != SD_WM_DONE) */
26352 
26353 	mutex_exit(SD_MUTEX(un));
26354 
26355 	ASSERT(wmp != NULL);
26356 
26357 	return (wmp);
26358 }
26359 
26360 
26361 /*
26362  *    Function: sd_get_range()
26363  *
26364  * Description: Find if there any overlapping I/O to this one
26365  *		Returns the write-map of 1st such I/O, NULL otherwise.
26366  *
26367  *   Arguments: un	- sd_lun structure for the device.
26368  *		startb - The starting block number
26369  *		endb - The end block number
26370  *
26371  * Return Code: wm  - pointer to the wmap structure.
26372  */
26373 
26374 static struct sd_w_map *
26375 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
26376 {
26377 	struct sd_w_map *wmp;
26378 
26379 	ASSERT(un != NULL);
26380 
26381 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
26382 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
26383 			continue;
26384 		}
26385 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
26386 			break;
26387 		}
26388 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
26389 			break;
26390 		}
26391 	}
26392 
26393 	return (wmp);
26394 }
26395 
26396 
26397 /*
26398  *    Function: sd_free_inlist_wmap()
26399  *
26400  * Description: Unlink and free a write map struct.
26401  *
26402  *   Arguments: un      - sd_lun structure for the device.
26403  *		wmp	- sd_w_map which needs to be unlinked.
26404  */
26405 
26406 static void
26407 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
26408 {
26409 	ASSERT(un != NULL);
26410 
26411 	if (un->un_wm == wmp) {
26412 		un->un_wm = wmp->wm_next;
26413 	} else {
26414 		wmp->wm_prev->wm_next = wmp->wm_next;
26415 	}
26416 
26417 	if (wmp->wm_next) {
26418 		wmp->wm_next->wm_prev = wmp->wm_prev;
26419 	}
26420 
26421 	wmp->wm_next = wmp->wm_prev = NULL;
26422 
26423 	kmem_cache_free(un->un_wm_cache, wmp);
26424 }
26425 
26426 
26427 /*
26428  *    Function: sd_range_unlock()
26429  *
26430  * Description: Unlock the range locked by wm.
26431  *		Free write map if nobody else is waiting on it.
26432  *
26433  *   Arguments: un      - sd_lun structure for the device.
26434  *              wmp     - sd_w_map which needs to be unlinked.
26435  */
26436 
26437 static void
26438 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
26439 {
26440 	ASSERT(un != NULL);
26441 	ASSERT(wm != NULL);
26442 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26443 
26444 	mutex_enter(SD_MUTEX(un));
26445 
26446 	if (wm->wm_flags & SD_WTYPE_RMW) {
26447 		un->un_rmw_count--;
26448 	}
26449 
26450 	if (wm->wm_wanted_count) {
26451 		wm->wm_flags = 0;
26452 		/*
26453 		 * Broadcast that the wmap is available now.
26454 		 */
26455 		cv_broadcast(&wm->wm_avail);
26456 	} else {
26457 		/*
26458 		 * If no one is waiting on the map, it should be free'ed.
26459 		 */
26460 		sd_free_inlist_wmap(un, wm);
26461 	}
26462 
26463 	mutex_exit(SD_MUTEX(un));
26464 }
26465 
26466 
26467 /*
26468  *    Function: sd_read_modify_write_task
26469  *
26470  * Description: Called from a taskq thread to initiate the write phase of
26471  *		a read-modify-write request.  This is used for targets where
26472  *		un->un_sys_blocksize != un->un_tgt_blocksize.
26473  *
26474  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
26475  *
26476  *     Context: Called under taskq thread context.
26477  */
26478 
26479 static void
26480 sd_read_modify_write_task(void *arg)
26481 {
26482 	struct sd_mapblocksize_info	*bsp;
26483 	struct buf	*bp;
26484 	struct sd_xbuf	*xp;
26485 	struct sd_lun	*un;
26486 
26487 	bp = arg;	/* The bp is given in arg */
26488 	ASSERT(bp != NULL);
26489 
26490 	/* Get the pointer to the layer-private data struct */
26491 	xp = SD_GET_XBUF(bp);
26492 	ASSERT(xp != NULL);
26493 	bsp = xp->xb_private;
26494 	ASSERT(bsp != NULL);
26495 
26496 	un = SD_GET_UN(bp);
26497 	ASSERT(un != NULL);
26498 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26499 
26500 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26501 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
26502 
26503 	/*
26504 	 * This is the write phase of a read-modify-write request, called
26505 	 * under the context of a taskq thread in response to the completion
26506 	 * of the read portion of the rmw request completing under interrupt
26507 	 * context. The write request must be sent from here down the iostart
26508 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
26509 	 * we use the layer index saved in the layer-private data area.
26510 	 */
26511 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
26512 
26513 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26514 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
26515 }
26516 
26517 
26518 /*
26519  *    Function: sddump_do_read_of_rmw()
26520  *
26521  * Description: This routine will be called from sddump, If sddump is called
26522  *		with an I/O which not aligned on device blocksize boundary
26523  *		then the write has to be converted to read-modify-write.
26524  *		Do the read part here in order to keep sddump simple.
26525  *		Note - That the sd_mutex is held across the call to this
26526  *		routine.
26527  *
26528  *   Arguments: un	- sd_lun
26529  *		blkno	- block number in terms of media block size.
26530  *		nblk	- number of blocks.
26531  *		bpp	- pointer to pointer to the buf structure. On return
26532  *			from this function, *bpp points to the valid buffer
26533  *			to which the write has to be done.
26534  *
26535  * Return Code: 0 for success or errno-type return code
26536  */
26537 
26538 static int
26539 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
26540 	struct buf **bpp)
26541 {
26542 	int err;
26543 	int i;
26544 	int rval;
26545 	struct buf *bp;
26546 	struct scsi_pkt *pkt = NULL;
26547 	uint32_t target_blocksize;
26548 
26549 	ASSERT(un != NULL);
26550 	ASSERT(mutex_owned(SD_MUTEX(un)));
26551 
26552 	target_blocksize = un->un_tgt_blocksize;
26553 
26554 	mutex_exit(SD_MUTEX(un));
26555 
26556 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
26557 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
26558 	if (bp == NULL) {
26559 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26560 		    "no resources for dumping; giving up");
26561 		err = ENOMEM;
26562 		goto done;
26563 	}
26564 
26565 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
26566 	    blkno, nblk);
26567 	if (rval != 0) {
26568 		scsi_free_consistent_buf(bp);
26569 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26570 		    "no resources for dumping; giving up");
26571 		err = ENOMEM;
26572 		goto done;
26573 	}
26574 
26575 	pkt->pkt_flags |= FLAG_NOINTR;
26576 
26577 	err = EIO;
26578 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26579 
26580 		/*
26581 		 * Scsi_poll returns 0 (success) if the command completes and
26582 		 * the status block is STATUS_GOOD.  We should only check
26583 		 * errors if this condition is not true.  Even then we should
26584 		 * send our own request sense packet only if we have a check
26585 		 * condition and auto request sense has not been performed by
26586 		 * the hba.
26587 		 */
26588 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
26589 
26590 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
26591 			err = 0;
26592 			break;
26593 		}
26594 
26595 		/*
26596 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
26597 		 * no need to read RQS data.
26598 		 */
26599 		if (pkt->pkt_reason == CMD_DEV_GONE) {
26600 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26601 			    "Device is gone\n");
26602 			break;
26603 		}
26604 
26605 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
26606 			SD_INFO(SD_LOG_DUMP, un,
26607 			    "sddump: read failed with CHECK, try # %d\n", i);
26608 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
26609 				(void) sd_send_polled_RQS(un);
26610 			}
26611 
26612 			continue;
26613 		}
26614 
26615 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
26616 			int reset_retval = 0;
26617 
26618 			SD_INFO(SD_LOG_DUMP, un,
26619 			    "sddump: read failed with BUSY, try # %d\n", i);
26620 
26621 			if (un->un_f_lun_reset_enabled == TRUE) {
26622 				reset_retval = scsi_reset(SD_ADDRESS(un),
26623 				    RESET_LUN);
26624 			}
26625 			if (reset_retval == 0) {
26626 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26627 			}
26628 			(void) sd_send_polled_RQS(un);
26629 
26630 		} else {
26631 			SD_INFO(SD_LOG_DUMP, un,
26632 			    "sddump: read failed with 0x%x, try # %d\n",
26633 			    SD_GET_PKT_STATUS(pkt), i);
26634 			mutex_enter(SD_MUTEX(un));
26635 			sd_reset_target(un, pkt);
26636 			mutex_exit(SD_MUTEX(un));
26637 		}
26638 
26639 		/*
26640 		 * If we are not getting anywhere with lun/target resets,
26641 		 * let's reset the bus.
26642 		 */
26643 		if (i > SD_NDUMP_RETRIES/2) {
26644 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26645 			(void) sd_send_polled_RQS(un);
26646 		}
26647 
26648 	}
26649 	scsi_destroy_pkt(pkt);
26650 
26651 	if (err != 0) {
26652 		scsi_free_consistent_buf(bp);
26653 		*bpp = NULL;
26654 	} else {
26655 		*bpp = bp;
26656 	}
26657 
26658 done:
26659 	mutex_enter(SD_MUTEX(un));
26660 	return (err);
26661 }
26662 
26663 
26664 /*
26665  *    Function: sd_failfast_flushq
26666  *
26667  * Description: Take all bp's on the wait queue that have B_FAILFAST set
26668  *		in b_flags and move them onto the failfast queue, then kick
26669  *		off a thread to return all bp's on the failfast queue to
26670  *		their owners with an error set.
26671  *
26672  *   Arguments: un - pointer to the soft state struct for the instance.
26673  *
26674  *     Context: may execute in interrupt context.
26675  */
26676 
26677 static void
26678 sd_failfast_flushq(struct sd_lun *un)
26679 {
26680 	struct buf *bp;
26681 	struct buf *next_waitq_bp;
26682 	struct buf *prev_waitq_bp = NULL;
26683 
26684 	ASSERT(un != NULL);
26685 	ASSERT(mutex_owned(SD_MUTEX(un)));
26686 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
26687 	ASSERT(un->un_failfast_bp == NULL);
26688 
26689 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
26690 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
26691 
26692 	/*
26693 	 * Check if we should flush all bufs when entering failfast state, or
26694 	 * just those with B_FAILFAST set.
26695 	 */
26696 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
26697 		/*
26698 		 * Move *all* bp's on the wait queue to the failfast flush
26699 		 * queue, including those that do NOT have B_FAILFAST set.
26700 		 */
26701 		if (un->un_failfast_headp == NULL) {
26702 			ASSERT(un->un_failfast_tailp == NULL);
26703 			un->un_failfast_headp = un->un_waitq_headp;
26704 		} else {
26705 			ASSERT(un->un_failfast_tailp != NULL);
26706 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
26707 		}
26708 
26709 		un->un_failfast_tailp = un->un_waitq_tailp;
26710 
26711 		/* update kstat for each bp moved out of the waitq */
26712 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
26713 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
26714 		}
26715 
26716 		/* empty the waitq */
26717 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
26718 
26719 	} else {
26720 		/*
26721 		 * Go thru the wait queue, pick off all entries with
26722 		 * B_FAILFAST set, and move these onto the failfast queue.
26723 		 */
26724 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
26725 			/*
26726 			 * Save the pointer to the next bp on the wait queue,
26727 			 * so we get to it on the next iteration of this loop.
26728 			 */
26729 			next_waitq_bp = bp->av_forw;
26730 
26731 			/*
26732 			 * If this bp from the wait queue does NOT have
26733 			 * B_FAILFAST set, just move on to the next element
26734 			 * in the wait queue. Note, this is the only place
26735 			 * where it is correct to set prev_waitq_bp.
26736 			 */
26737 			if ((bp->b_flags & B_FAILFAST) == 0) {
26738 				prev_waitq_bp = bp;
26739 				continue;
26740 			}
26741 
26742 			/*
26743 			 * Remove the bp from the wait queue.
26744 			 */
26745 			if (bp == un->un_waitq_headp) {
26746 				/* The bp is the first element of the waitq. */
26747 				un->un_waitq_headp = next_waitq_bp;
26748 				if (un->un_waitq_headp == NULL) {
26749 					/* The wait queue is now empty */
26750 					un->un_waitq_tailp = NULL;
26751 				}
26752 			} else {
26753 				/*
26754 				 * The bp is either somewhere in the middle
26755 				 * or at the end of the wait queue.
26756 				 */
26757 				ASSERT(un->un_waitq_headp != NULL);
26758 				ASSERT(prev_waitq_bp != NULL);
26759 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
26760 				    == 0);
26761 				if (bp == un->un_waitq_tailp) {
26762 					/* bp is the last entry on the waitq. */
26763 					ASSERT(next_waitq_bp == NULL);
26764 					un->un_waitq_tailp = prev_waitq_bp;
26765 				}
26766 				prev_waitq_bp->av_forw = next_waitq_bp;
26767 			}
26768 			bp->av_forw = NULL;
26769 
26770 			/*
26771 			 * update kstat since the bp is moved out of
26772 			 * the waitq
26773 			 */
26774 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
26775 
26776 			/*
26777 			 * Now put the bp onto the failfast queue.
26778 			 */
26779 			if (un->un_failfast_headp == NULL) {
26780 				/* failfast queue is currently empty */
26781 				ASSERT(un->un_failfast_tailp == NULL);
26782 				un->un_failfast_headp =
26783 				    un->un_failfast_tailp = bp;
26784 			} else {
26785 				/* Add the bp to the end of the failfast q */
26786 				ASSERT(un->un_failfast_tailp != NULL);
26787 				ASSERT(un->un_failfast_tailp->b_flags &
26788 				    B_FAILFAST);
26789 				un->un_failfast_tailp->av_forw = bp;
26790 				un->un_failfast_tailp = bp;
26791 			}
26792 		}
26793 	}
26794 
26795 	/*
26796 	 * Now return all bp's on the failfast queue to their owners.
26797 	 */
26798 	while ((bp = un->un_failfast_headp) != NULL) {
26799 
26800 		un->un_failfast_headp = bp->av_forw;
26801 		if (un->un_failfast_headp == NULL) {
26802 			un->un_failfast_tailp = NULL;
26803 		}
26804 
26805 		/*
26806 		 * We want to return the bp with a failure error code, but
26807 		 * we do not want a call to sd_start_cmds() to occur here,
26808 		 * so use sd_return_failed_command_no_restart() instead of
26809 		 * sd_return_failed_command().
26810 		 */
26811 		sd_return_failed_command_no_restart(un, bp, EIO);
26812 	}
26813 
26814 	/* Flush the xbuf queues if required. */
26815 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
26816 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
26817 	}
26818 
26819 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
26820 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
26821 }
26822 
26823 
26824 /*
26825  *    Function: sd_failfast_flushq_callback
26826  *
26827  * Description: Return TRUE if the given bp meets the criteria for failfast
26828  *		flushing. Used with ddi_xbuf_flushq(9F).
26829  *
26830  *   Arguments: bp - ptr to buf struct to be examined.
26831  *
26832  *     Context: Any
26833  */
26834 
26835 static int
26836 sd_failfast_flushq_callback(struct buf *bp)
26837 {
26838 	/*
26839 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
26840 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
26841 	 */
26842 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
26843 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
26844 }
26845 
26846 
26847 
26848 /*
26849  * Function: sd_setup_next_xfer
26850  *
26851  * Description: Prepare next I/O operation using DMA_PARTIAL
26852  *
26853  */
26854 
26855 static int
26856 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
26857     struct scsi_pkt *pkt, struct sd_xbuf *xp)
26858 {
26859 	ssize_t	num_blks_not_xfered;
26860 	daddr_t	strt_blk_num;
26861 	ssize_t	bytes_not_xfered;
26862 	int	rval;
26863 
26864 	ASSERT(pkt->pkt_resid == 0);
26865 
26866 	/*
26867 	 * Calculate next block number and amount to be transferred.
26868 	 *
26869 	 * How much data NOT transfered to the HBA yet.
26870 	 */
26871 	bytes_not_xfered = xp->xb_dma_resid;
26872 
26873 	/*
26874 	 * figure how many blocks NOT transfered to the HBA yet.
26875 	 */
26876 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
26877 
26878 	/*
26879 	 * set starting block number to the end of what WAS transfered.
26880 	 */
26881 	strt_blk_num = xp->xb_blkno +
26882 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
26883 
26884 	/*
26885 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
26886 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
26887 	 * the disk mutex here.
26888 	 */
26889 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
26890 	    strt_blk_num, num_blks_not_xfered);
26891 
26892 	if (rval == 0) {
26893 
26894 		/*
26895 		 * Success.
26896 		 *
26897 		 * Adjust things if there are still more blocks to be
26898 		 * transfered.
26899 		 */
26900 		xp->xb_dma_resid = pkt->pkt_resid;
26901 		pkt->pkt_resid = 0;
26902 
26903 		return (1);
26904 	}
26905 
26906 	/*
26907 	 * There's really only one possible return value from
26908 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
26909 	 * returns NULL.
26910 	 */
26911 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
26912 
26913 	bp->b_resid = bp->b_bcount;
26914 	bp->b_flags |= B_ERROR;
26915 
26916 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26917 	    "Error setting up next portion of DMA transfer\n");
26918 
26919 	return (0);
26920 }
26921 
26922 /*
26923  *    Function: sd_panic_for_res_conflict
26924  *
26925  * Description: Call panic with a string formatted with "Reservation Conflict"
26926  *		and a human readable identifier indicating the SD instance
26927  *		that experienced the reservation conflict.
26928  *
26929  *   Arguments: un - pointer to the soft state struct for the instance.
26930  *
26931  *     Context: may execute in interrupt context.
26932  */
26933 
26934 #define	SD_RESV_CONFLICT_FMT_LEN 40
26935 void
26936 sd_panic_for_res_conflict(struct sd_lun *un)
26937 {
26938 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
26939 	char path_str[MAXPATHLEN];
26940 
26941 	(void) snprintf(panic_str, sizeof (panic_str),
26942 	    "Reservation Conflict\nDisk: %s",
26943 	    ddi_pathname(SD_DEVINFO(un), path_str));
26944 
26945 	panic(panic_str);
26946 }
26947 
26948 /*
26949  * Note: The following sd_faultinjection_ioctl( ) routines implement
26950  * driver support for handling fault injection for error analysis
26951  * causing faults in multiple layers of the driver.
26952  *
26953  */
26954 
26955 #ifdef SD_FAULT_INJECTION
26956 static uint_t   sd_fault_injection_on = 0;
26957 
26958 /*
26959  *    Function: sd_faultinjection_ioctl()
26960  *
26961  * Description: This routine is the driver entry point for handling
26962  *              faultinjection ioctls to inject errors into the
26963  *              layer model
26964  *
26965  *   Arguments: cmd	- the ioctl cmd received
26966  *		arg	- the arguments from user and returns
26967  */
26968 
26969 static void
26970 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
26971 
26972 	uint_t i;
26973 	uint_t rval;
26974 
26975 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
26976 
26977 	mutex_enter(SD_MUTEX(un));
26978 
26979 	switch (cmd) {
26980 	case SDIOCRUN:
26981 		/* Allow pushed faults to be injected */
26982 		SD_INFO(SD_LOG_SDTEST, un,
26983 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
26984 
26985 		sd_fault_injection_on = 1;
26986 
26987 		SD_INFO(SD_LOG_IOERR, un,
26988 		    "sd_faultinjection_ioctl: run finished\n");
26989 		break;
26990 
26991 	case SDIOCSTART:
26992 		/* Start Injection Session */
26993 		SD_INFO(SD_LOG_SDTEST, un,
26994 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
26995 
26996 		sd_fault_injection_on = 0;
26997 		un->sd_injection_mask = 0xFFFFFFFF;
26998 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
26999 			un->sd_fi_fifo_pkt[i] = NULL;
27000 			un->sd_fi_fifo_xb[i] = NULL;
27001 			un->sd_fi_fifo_un[i] = NULL;
27002 			un->sd_fi_fifo_arq[i] = NULL;
27003 		}
27004 		un->sd_fi_fifo_start = 0;
27005 		un->sd_fi_fifo_end = 0;
27006 
27007 		mutex_enter(&(un->un_fi_mutex));
27008 		un->sd_fi_log[0] = '\0';
27009 		un->sd_fi_buf_len = 0;
27010 		mutex_exit(&(un->un_fi_mutex));
27011 
27012 		SD_INFO(SD_LOG_IOERR, un,
27013 		    "sd_faultinjection_ioctl: start finished\n");
27014 		break;
27015 
27016 	case SDIOCSTOP:
27017 		/* Stop Injection Session */
27018 		SD_INFO(SD_LOG_SDTEST, un,
27019 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
27020 		sd_fault_injection_on = 0;
27021 		un->sd_injection_mask = 0x0;
27022 
27023 		/* Empty stray or unuseds structs from fifo */
27024 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
27025 			if (un->sd_fi_fifo_pkt[i] != NULL) {
27026 				kmem_free(un->sd_fi_fifo_pkt[i],
27027 				    sizeof (struct sd_fi_pkt));
27028 			}
27029 			if (un->sd_fi_fifo_xb[i] != NULL) {
27030 				kmem_free(un->sd_fi_fifo_xb[i],
27031 				    sizeof (struct sd_fi_xb));
27032 			}
27033 			if (un->sd_fi_fifo_un[i] != NULL) {
27034 				kmem_free(un->sd_fi_fifo_un[i],
27035 				    sizeof (struct sd_fi_un));
27036 			}
27037 			if (un->sd_fi_fifo_arq[i] != NULL) {
27038 				kmem_free(un->sd_fi_fifo_arq[i],
27039 				    sizeof (struct sd_fi_arq));
27040 			}
27041 			un->sd_fi_fifo_pkt[i] = NULL;
27042 			un->sd_fi_fifo_un[i] = NULL;
27043 			un->sd_fi_fifo_xb[i] = NULL;
27044 			un->sd_fi_fifo_arq[i] = NULL;
27045 		}
27046 		un->sd_fi_fifo_start = 0;
27047 		un->sd_fi_fifo_end = 0;
27048 
27049 		SD_INFO(SD_LOG_IOERR, un,
27050 		    "sd_faultinjection_ioctl: stop finished\n");
27051 		break;
27052 
27053 	case SDIOCINSERTPKT:
27054 		/* Store a packet struct to be pushed onto fifo */
27055 		SD_INFO(SD_LOG_SDTEST, un,
27056 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
27057 
27058 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27059 
27060 		sd_fault_injection_on = 0;
27061 
27062 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
27063 		if (un->sd_fi_fifo_pkt[i] != NULL) {
27064 			kmem_free(un->sd_fi_fifo_pkt[i],
27065 			    sizeof (struct sd_fi_pkt));
27066 		}
27067 		if (arg != NULL) {
27068 			un->sd_fi_fifo_pkt[i] =
27069 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
27070 			if (un->sd_fi_fifo_pkt[i] == NULL) {
27071 				/* Alloc failed don't store anything */
27072 				break;
27073 			}
27074 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
27075 			    sizeof (struct sd_fi_pkt), 0);
27076 			if (rval == -1) {
27077 				kmem_free(un->sd_fi_fifo_pkt[i],
27078 				    sizeof (struct sd_fi_pkt));
27079 				un->sd_fi_fifo_pkt[i] = NULL;
27080 			}
27081 		} else {
27082 			SD_INFO(SD_LOG_IOERR, un,
27083 			    "sd_faultinjection_ioctl: pkt null\n");
27084 		}
27085 		break;
27086 
27087 	case SDIOCINSERTXB:
27088 		/* Store a xb struct to be pushed onto fifo */
27089 		SD_INFO(SD_LOG_SDTEST, un,
27090 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
27091 
27092 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27093 
27094 		sd_fault_injection_on = 0;
27095 
27096 		if (un->sd_fi_fifo_xb[i] != NULL) {
27097 			kmem_free(un->sd_fi_fifo_xb[i],
27098 			    sizeof (struct sd_fi_xb));
27099 			un->sd_fi_fifo_xb[i] = NULL;
27100 		}
27101 		if (arg != NULL) {
27102 			un->sd_fi_fifo_xb[i] =
27103 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
27104 			if (un->sd_fi_fifo_xb[i] == NULL) {
27105 				/* Alloc failed don't store anything */
27106 				break;
27107 			}
27108 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
27109 			    sizeof (struct sd_fi_xb), 0);
27110 
27111 			if (rval == -1) {
27112 				kmem_free(un->sd_fi_fifo_xb[i],
27113 				    sizeof (struct sd_fi_xb));
27114 				un->sd_fi_fifo_xb[i] = NULL;
27115 			}
27116 		} else {
27117 			SD_INFO(SD_LOG_IOERR, un,
27118 			    "sd_faultinjection_ioctl: xb null\n");
27119 		}
27120 		break;
27121 
27122 	case SDIOCINSERTUN:
27123 		/* Store a un struct to be pushed onto fifo */
27124 		SD_INFO(SD_LOG_SDTEST, un,
27125 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
27126 
27127 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27128 
27129 		sd_fault_injection_on = 0;
27130 
27131 		if (un->sd_fi_fifo_un[i] != NULL) {
27132 			kmem_free(un->sd_fi_fifo_un[i],
27133 			    sizeof (struct sd_fi_un));
27134 			un->sd_fi_fifo_un[i] = NULL;
27135 		}
27136 		if (arg != NULL) {
27137 			un->sd_fi_fifo_un[i] =
27138 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
27139 			if (un->sd_fi_fifo_un[i] == NULL) {
27140 				/* Alloc failed don't store anything */
27141 				break;
27142 			}
27143 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
27144 			    sizeof (struct sd_fi_un), 0);
27145 			if (rval == -1) {
27146 				kmem_free(un->sd_fi_fifo_un[i],
27147 				    sizeof (struct sd_fi_un));
27148 				un->sd_fi_fifo_un[i] = NULL;
27149 			}
27150 
27151 		} else {
27152 			SD_INFO(SD_LOG_IOERR, un,
27153 			    "sd_faultinjection_ioctl: un null\n");
27154 		}
27155 
27156 		break;
27157 
27158 	case SDIOCINSERTARQ:
27159 		/* Store a arq struct to be pushed onto fifo */
27160 		SD_INFO(SD_LOG_SDTEST, un,
27161 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
27162 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27163 
27164 		sd_fault_injection_on = 0;
27165 
27166 		if (un->sd_fi_fifo_arq[i] != NULL) {
27167 			kmem_free(un->sd_fi_fifo_arq[i],
27168 			    sizeof (struct sd_fi_arq));
27169 			un->sd_fi_fifo_arq[i] = NULL;
27170 		}
27171 		if (arg != NULL) {
27172 			un->sd_fi_fifo_arq[i] =
27173 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
27174 			if (un->sd_fi_fifo_arq[i] == NULL) {
27175 				/* Alloc failed don't store anything */
27176 				break;
27177 			}
27178 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
27179 			    sizeof (struct sd_fi_arq), 0);
27180 			if (rval == -1) {
27181 				kmem_free(un->sd_fi_fifo_arq[i],
27182 				    sizeof (struct sd_fi_arq));
27183 				un->sd_fi_fifo_arq[i] = NULL;
27184 			}
27185 
27186 		} else {
27187 			SD_INFO(SD_LOG_IOERR, un,
27188 			    "sd_faultinjection_ioctl: arq null\n");
27189 		}
27190 
27191 		break;
27192 
27193 	case SDIOCPUSH:
27194 		/* Push stored xb, pkt, un, and arq onto fifo */
27195 		sd_fault_injection_on = 0;
27196 
27197 		if (arg != NULL) {
27198 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
27199 			if (rval != -1 &&
27200 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
27201 				un->sd_fi_fifo_end += i;
27202 			}
27203 		} else {
27204 			SD_INFO(SD_LOG_IOERR, un,
27205 			    "sd_faultinjection_ioctl: push arg null\n");
27206 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
27207 				un->sd_fi_fifo_end++;
27208 			}
27209 		}
27210 		SD_INFO(SD_LOG_IOERR, un,
27211 		    "sd_faultinjection_ioctl: push to end=%d\n",
27212 		    un->sd_fi_fifo_end);
27213 		break;
27214 
27215 	case SDIOCRETRIEVE:
27216 		/* Return buffer of log from Injection session */
27217 		SD_INFO(SD_LOG_SDTEST, un,
27218 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
27219 
27220 		sd_fault_injection_on = 0;
27221 
27222 		mutex_enter(&(un->un_fi_mutex));
27223 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
27224 		    un->sd_fi_buf_len+1, 0);
27225 		mutex_exit(&(un->un_fi_mutex));
27226 
27227 		if (rval == -1) {
27228 			/*
27229 			 * arg is possibly invalid setting
27230 			 * it to NULL for return
27231 			 */
27232 			arg = NULL;
27233 		}
27234 		break;
27235 	}
27236 
27237 	mutex_exit(SD_MUTEX(un));
27238 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
27239 			    " exit\n");
27240 }
27241 
27242 
27243 /*
27244  *    Function: sd_injection_log()
27245  *
27246  * Description: This routine adds buff to the already existing injection log
27247  *              for retrieval via faultinjection_ioctl for use in fault
27248  *              detection and recovery
27249  *
27250  *   Arguments: buf - the string to add to the log
27251  */
27252 
27253 static void
27254 sd_injection_log(char *buf, struct sd_lun *un)
27255 {
27256 	uint_t len;
27257 
27258 	ASSERT(un != NULL);
27259 	ASSERT(buf != NULL);
27260 
27261 	mutex_enter(&(un->un_fi_mutex));
27262 
27263 	len = min(strlen(buf), 255);
27264 	/* Add logged value to Injection log to be returned later */
27265 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
27266 		uint_t	offset = strlen((char *)un->sd_fi_log);
27267 		char *destp = (char *)un->sd_fi_log + offset;
27268 		int i;
27269 		for (i = 0; i < len; i++) {
27270 			*destp++ = *buf++;
27271 		}
27272 		un->sd_fi_buf_len += len;
27273 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
27274 	}
27275 
27276 	mutex_exit(&(un->un_fi_mutex));
27277 }
27278 
27279 
27280 /*
27281  *    Function: sd_faultinjection()
27282  *
27283  * Description: This routine takes the pkt and changes its
27284  *		content based on error injection scenerio.
27285  *
27286  *   Arguments: pktp	- packet to be changed
27287  */
27288 
27289 static void
27290 sd_faultinjection(struct scsi_pkt *pktp)
27291 {
27292 	uint_t i;
27293 	struct sd_fi_pkt *fi_pkt;
27294 	struct sd_fi_xb *fi_xb;
27295 	struct sd_fi_un *fi_un;
27296 	struct sd_fi_arq *fi_arq;
27297 	struct buf *bp;
27298 	struct sd_xbuf *xb;
27299 	struct sd_lun *un;
27300 
27301 	ASSERT(pktp != NULL);
27302 
27303 	/* pull bp xb and un from pktp */
27304 	bp = (struct buf *)pktp->pkt_private;
27305 	xb = SD_GET_XBUF(bp);
27306 	un = SD_GET_UN(bp);
27307 
27308 	ASSERT(un != NULL);
27309 
27310 	mutex_enter(SD_MUTEX(un));
27311 
27312 	SD_TRACE(SD_LOG_SDTEST, un,
27313 	    "sd_faultinjection: entry Injection from sdintr\n");
27314 
27315 	/* if injection is off return */
27316 	if (sd_fault_injection_on == 0 ||
27317 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
27318 		mutex_exit(SD_MUTEX(un));
27319 		return;
27320 	}
27321 
27322 
27323 	/* take next set off fifo */
27324 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
27325 
27326 	fi_pkt = un->sd_fi_fifo_pkt[i];
27327 	fi_xb = un->sd_fi_fifo_xb[i];
27328 	fi_un = un->sd_fi_fifo_un[i];
27329 	fi_arq = un->sd_fi_fifo_arq[i];
27330 
27331 
27332 	/* set variables accordingly */
27333 	/* set pkt if it was on fifo */
27334 	if (fi_pkt != NULL) {
27335 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
27336 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
27337 		SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
27338 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
27339 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
27340 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
27341 
27342 	}
27343 
27344 	/* set xb if it was on fifo */
27345 	if (fi_xb != NULL) {
27346 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
27347 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
27348 		SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
27349 		SD_CONDSET(xb, xb, xb_victim_retry_count,
27350 		    "xb_victim_retry_count");
27351 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
27352 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
27353 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
27354 
27355 		/* copy in block data from sense */
27356 		if (fi_xb->xb_sense_data[0] != -1) {
27357 			bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
27358 			    SENSE_LENGTH);
27359 		}
27360 
27361 		/* copy in extended sense codes */
27362 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_code,
27363 		    "es_code");
27364 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_key,
27365 		    "es_key");
27366 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_add_code,
27367 		    "es_add_code");
27368 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb,
27369 		    es_qual_code, "es_qual_code");
27370 	}
27371 
27372 	/* set un if it was on fifo */
27373 	if (fi_un != NULL) {
27374 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
27375 		SD_CONDSET(un, un, un_ctype, "un_ctype");
27376 		SD_CONDSET(un, un, un_reset_retry_count,
27377 		    "un_reset_retry_count");
27378 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
27379 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
27380 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
27381 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
27382 		    "un_f_allow_bus_device_reset");
27383 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
27384 
27385 	}
27386 
27387 	/* copy in auto request sense if it was on fifo */
27388 	if (fi_arq != NULL) {
27389 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
27390 	}
27391 
27392 	/* free structs */
27393 	if (un->sd_fi_fifo_pkt[i] != NULL) {
27394 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
27395 	}
27396 	if (un->sd_fi_fifo_xb[i] != NULL) {
27397 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
27398 	}
27399 	if (un->sd_fi_fifo_un[i] != NULL) {
27400 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
27401 	}
27402 	if (un->sd_fi_fifo_arq[i] != NULL) {
27403 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
27404 	}
27405 
27406 	/*
27407 	 * kmem_free does not gurantee to set to NULL
27408 	 * since we uses these to determine if we set
27409 	 * values or not lets confirm they are always
27410 	 * NULL after free
27411 	 */
27412 	un->sd_fi_fifo_pkt[i] = NULL;
27413 	un->sd_fi_fifo_un[i] = NULL;
27414 	un->sd_fi_fifo_xb[i] = NULL;
27415 	un->sd_fi_fifo_arq[i] = NULL;
27416 
27417 	un->sd_fi_fifo_start++;
27418 
27419 	mutex_exit(SD_MUTEX(un));
27420 
27421 	SD_TRACE(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
27422 }
27423 
27424 #endif /* SD_FAULT_INJECTION */
27425 
27426 /*
27427  * This routine is invoked in sd_unit_attach(). Before calling it, the
27428  * properties in conf file should be processed already, and "hotpluggable"
27429  * property was processed also.
27430  *
27431  * The sd driver distinguishes 3 different type of devices: removable media,
27432  * non-removable media, and hotpluggable. Below the differences are defined:
27433  *
27434  * 1. Device ID
27435  *
27436  *     The device ID of a device is used to identify this device. Refer to
27437  *     ddi_devid_register(9F).
27438  *
27439  *     For a non-removable media disk device which can provide 0x80 or 0x83
27440  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
27441  *     device ID is created to identify this device. For other non-removable
27442  *     media devices, a default device ID is created only if this device has
27443  *     at least 2 alter cylinders. Otherwise, this device has no devid.
27444  *
27445  *     -------------------------------------------------------
27446  *     removable media   hotpluggable  | Can Have Device ID
27447  *     -------------------------------------------------------
27448  *         false             false     |     Yes
27449  *         false             true      |     Yes
27450  *         true                x       |     No
27451  *     ------------------------------------------------------
27452  *
27453  *
27454  * 2. SCSI group 4 commands
27455  *
27456  *     In SCSI specs, only some commands in group 4 command set can use
27457  *     8-byte addresses that can be used to access >2TB storage spaces.
27458  *     Other commands have no such capability. Without supporting group4,
27459  *     it is impossible to make full use of storage spaces of a disk with
27460  *     capacity larger than 2TB.
27461  *
27462  *     -----------------------------------------------
27463  *     removable media   hotpluggable   LP64  |  Group
27464  *     -----------------------------------------------
27465  *           false          false       false |   1
27466  *           false          false       true  |   4
27467  *           false          true        false |   1
27468  *           false          true        true  |   4
27469  *           true             x           x   |   5
27470  *     -----------------------------------------------
27471  *
27472  *
27473  * 3. Check for VTOC Label
27474  *
27475  *     If a direct-access disk has no EFI label, sd will check if it has a
27476  *     valid VTOC label. Now, sd also does that check for removable media
27477  *     and hotpluggable devices.
27478  *
27479  *     --------------------------------------------------------------
27480  *     Direct-Access   removable media    hotpluggable |  Check Label
27481  *     -------------------------------------------------------------
27482  *         false          false           false        |   No
27483  *         false          false           true         |   No
27484  *         false          true            false        |   Yes
27485  *         false          true            true         |   Yes
27486  *         true            x                x          |   Yes
27487  *     --------------------------------------------------------------
27488  *
27489  *
27490  * 4. Building default VTOC label
27491  *
27492  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
27493  *     If those devices have no valid VTOC label, sd(7d) will attempt to
27494  *     create default VTOC for them. Currently sd creates default VTOC label
27495  *     for all devices on x86 platform (VTOC_16), but only for removable
27496  *     media devices on SPARC (VTOC_8).
27497  *
27498  *     -----------------------------------------------------------
27499  *       removable media hotpluggable platform   |   Default Label
27500  *     -----------------------------------------------------------
27501  *             false          false    sparc     |     No
27502  *             false          true      x86      |     Yes
27503  *             false          true     sparc     |     Yes
27504  *             true             x        x       |     Yes
27505  *     ----------------------------------------------------------
27506  *
27507  *
27508  * 5. Supported blocksizes of target devices
27509  *
27510  *     Sd supports non-512-byte blocksize for removable media devices only.
27511  *     For other devices, only 512-byte blocksize is supported. This may be
27512  *     changed in near future because some RAID devices require non-512-byte
27513  *     blocksize
27514  *
27515  *     -----------------------------------------------------------
27516  *     removable media    hotpluggable    | non-512-byte blocksize
27517  *     -----------------------------------------------------------
27518  *           false          false         |   No
27519  *           false          true          |   No
27520  *           true             x           |   Yes
27521  *     -----------------------------------------------------------
27522  *
27523  *
27524  * 6. Automatic mount & unmount
27525  *
27526  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
27527  *     if a device is removable media device. It return 1 for removable media
27528  *     devices, and 0 for others.
27529  *
27530  *     The automatic mounting subsystem should distinguish between the types
27531  *     of devices and apply automounting policies to each.
27532  *
27533  *
27534  * 7. fdisk partition management
27535  *
27536  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
27537  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
27538  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
27539  *     fdisk partitions on both x86 and SPARC platform.
27540  *
27541  *     -----------------------------------------------------------
27542  *       platform   removable media  USB/1394  |  fdisk supported
27543  *     -----------------------------------------------------------
27544  *        x86         X               X        |       true
27545  *     ------------------------------------------------------------
27546  *        sparc       X               X        |       false
27547  *     ------------------------------------------------------------
27548  *
27549  *
27550  * 8. MBOOT/MBR
27551  *
27552  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
27553  *     read/write mboot for removable media devices on sparc platform.
27554  *
27555  *     -----------------------------------------------------------
27556  *       platform   removable media  USB/1394  |  mboot supported
27557  *     -----------------------------------------------------------
27558  *        x86         X               X        |       true
27559  *     ------------------------------------------------------------
27560  *        sparc      false           false     |       false
27561  *        sparc      false           true      |       true
27562  *        sparc      true            false     |       true
27563  *        sparc      true            true      |       true
27564  *     ------------------------------------------------------------
27565  *
27566  *
27567  * 9.  error handling during opening device
27568  *
27569  *     If failed to open a disk device, an errno is returned. For some kinds
27570  *     of errors, different errno is returned depending on if this device is
27571  *     a removable media device. This brings USB/1394 hard disks in line with
27572  *     expected hard disk behavior. It is not expected that this breaks any
27573  *     application.
27574  *
27575  *     ------------------------------------------------------
27576  *       removable media    hotpluggable   |  errno
27577  *     ------------------------------------------------------
27578  *             false          false        |   EIO
27579  *             false          true         |   EIO
27580  *             true             x          |   ENXIO
27581  *     ------------------------------------------------------
27582  *
27583  *
27584  * 11. ioctls: DKIOCEJECT, CDROMEJECT
27585  *
27586  *     These IOCTLs are applicable only to removable media devices.
27587  *
27588  *     -----------------------------------------------------------
27589  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
27590  *     -----------------------------------------------------------
27591  *             false          false        |     No
27592  *             false          true         |     No
27593  *             true            x           |     Yes
27594  *     -----------------------------------------------------------
27595  *
27596  *
27597  * 12. Kstats for partitions
27598  *
27599  *     sd creates partition kstat for non-removable media devices. USB and
27600  *     Firewire hard disks now have partition kstats
27601  *
27602  *      ------------------------------------------------------
27603  *       removable media    hotpluggable   |   kstat
27604  *      ------------------------------------------------------
27605  *             false          false        |    Yes
27606  *             false          true         |    Yes
27607  *             true             x          |    No
27608  *       ------------------------------------------------------
27609  *
27610  *
27611  * 13. Removable media & hotpluggable properties
27612  *
27613  *     Sd driver creates a "removable-media" property for removable media
27614  *     devices. Parent nexus drivers create a "hotpluggable" property if
27615  *     it supports hotplugging.
27616  *
27617  *     ---------------------------------------------------------------------
27618  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
27619  *     ---------------------------------------------------------------------
27620  *       false            false       |    No                   No
27621  *       false            true        |    No                   Yes
27622  *       true             false       |    Yes                  No
27623  *       true             true        |    Yes                  Yes
27624  *     ---------------------------------------------------------------------
27625  *
27626  *
27627  * 14. Power Management
27628  *
27629  *     sd only power manages removable media devices or devices that support
27630  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
27631  *
27632  *     A parent nexus that supports hotplugging can also set "pm-capable"
27633  *     if the disk can be power managed.
27634  *
27635  *     ------------------------------------------------------------
27636  *       removable media hotpluggable pm-capable  |   power manage
27637  *     ------------------------------------------------------------
27638  *             false          false     false     |     No
27639  *             false          false     true      |     Yes
27640  *             false          true      false     |     No
27641  *             false          true      true      |     Yes
27642  *             true             x        x        |     Yes
27643  *     ------------------------------------------------------------
27644  *
27645  *      USB and firewire hard disks can now be power managed independently
27646  *      of the framebuffer
27647  *
27648  *
27649  * 15. Support for USB disks with capacity larger than 1TB
27650  *
27651  *     Currently, sd doesn't permit a fixed disk device with capacity
27652  *     larger than 1TB to be used in a 32-bit operating system environment.
27653  *     However, sd doesn't do that for removable media devices. Instead, it
27654  *     assumes that removable media devices cannot have a capacity larger
27655  *     than 1TB. Therefore, using those devices on 32-bit system is partially
27656  *     supported, which can cause some unexpected results.
27657  *
27658  *     ---------------------------------------------------------------------
27659  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
27660  *     ---------------------------------------------------------------------
27661  *             false          false  |   true         |     no
27662  *             false          true   |   true         |     no
27663  *             true           false  |   true         |     Yes
27664  *             true           true   |   true         |     Yes
27665  *     ---------------------------------------------------------------------
27666  *
27667  *
27668  * 16. Check write-protection at open time
27669  *
27670  *     When a removable media device is being opened for writing without NDELAY
27671  *     flag, sd will check if this device is writable. If attempting to open
27672  *     without NDELAY flag a write-protected device, this operation will abort.
27673  *
27674  *     ------------------------------------------------------------
27675  *       removable media    USB/1394   |   WP Check
27676  *     ------------------------------------------------------------
27677  *             false          false    |     No
27678  *             false          true     |     No
27679  *             true           false    |     Yes
27680  *             true           true     |     Yes
27681  *     ------------------------------------------------------------
27682  *
27683  *
27684  * 17. syslog when corrupted VTOC is encountered
27685  *
27686  *      Currently, if an invalid VTOC is encountered, sd only print syslog
27687  *      for fixed SCSI disks.
27688  *     ------------------------------------------------------------
27689  *       removable media    USB/1394   |   print syslog
27690  *     ------------------------------------------------------------
27691  *             false          false    |     Yes
27692  *             false          true     |     No
27693  *             true           false    |     No
27694  *             true           true     |     No
27695  *     ------------------------------------------------------------
27696  */
27697 static void
27698 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
27699 {
27700 	int	pm_capable_prop;
27701 
27702 	ASSERT(un->un_sd);
27703 	ASSERT(un->un_sd->sd_inq);
27704 
27705 	/*
27706 	 * Enable SYNC CACHE support for all devices.
27707 	 */
27708 	un->un_f_sync_cache_supported = TRUE;
27709 
27710 	if (un->un_sd->sd_inq->inq_rmb) {
27711 		/*
27712 		 * The media of this device is removable. And for this kind
27713 		 * of devices, it is possible to change medium after opening
27714 		 * devices. Thus we should support this operation.
27715 		 */
27716 		un->un_f_has_removable_media = TRUE;
27717 
27718 		/*
27719 		 * support non-512-byte blocksize of removable media devices
27720 		 */
27721 		un->un_f_non_devbsize_supported = TRUE;
27722 
27723 		/*
27724 		 * Assume that all removable media devices support DOOR_LOCK
27725 		 */
27726 		un->un_f_doorlock_supported = TRUE;
27727 
27728 		/*
27729 		 * For a removable media device, it is possible to be opened
27730 		 * with NDELAY flag when there is no media in drive, in this
27731 		 * case we don't care if device is writable. But if without
27732 		 * NDELAY flag, we need to check if media is write-protected.
27733 		 */
27734 		un->un_f_chk_wp_open = TRUE;
27735 
27736 		/*
27737 		 * need to start a SCSI watch thread to monitor media state,
27738 		 * when media is being inserted or ejected, notify syseventd.
27739 		 */
27740 		un->un_f_monitor_media_state = TRUE;
27741 
27742 		/*
27743 		 * Some devices don't support START_STOP_UNIT command.
27744 		 * Therefore, we'd better check if a device supports it
27745 		 * before sending it.
27746 		 */
27747 		un->un_f_check_start_stop = TRUE;
27748 
27749 		/*
27750 		 * support eject media ioctl:
27751 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
27752 		 */
27753 		un->un_f_eject_media_supported = TRUE;
27754 
27755 		/*
27756 		 * Because many removable-media devices don't support
27757 		 * LOG_SENSE, we couldn't use this command to check if
27758 		 * a removable media device support power-management.
27759 		 * We assume that they support power-management via
27760 		 * START_STOP_UNIT command and can be spun up and down
27761 		 * without limitations.
27762 		 */
27763 		un->un_f_pm_supported = TRUE;
27764 
27765 		/*
27766 		 * Need to create a zero length (Boolean) property
27767 		 * removable-media for the removable media devices.
27768 		 * Note that the return value of the property is not being
27769 		 * checked, since if unable to create the property
27770 		 * then do not want the attach to fail altogether. Consistent
27771 		 * with other property creation in attach.
27772 		 */
27773 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
27774 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
27775 
27776 	} else {
27777 		/*
27778 		 * create device ID for device
27779 		 */
27780 		un->un_f_devid_supported = TRUE;
27781 
27782 		/*
27783 		 * Spin up non-removable-media devices once it is attached
27784 		 */
27785 		un->un_f_attach_spinup = TRUE;
27786 
27787 		/*
27788 		 * According to SCSI specification, Sense data has two kinds of
27789 		 * format: fixed format, and descriptor format. At present, we
27790 		 * don't support descriptor format sense data for removable
27791 		 * media.
27792 		 */
27793 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
27794 			un->un_f_descr_format_supported = TRUE;
27795 		}
27796 
27797 		/*
27798 		 * kstats are created only for non-removable media devices.
27799 		 *
27800 		 * Set this in sd.conf to 0 in order to disable kstats.  The
27801 		 * default is 1, so they are enabled by default.
27802 		 */
27803 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
27804 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
27805 		    "enable-partition-kstats", 1));
27806 
27807 		/*
27808 		 * Check if HBA has set the "pm-capable" property.
27809 		 * If "pm-capable" exists and is non-zero then we can
27810 		 * power manage the device without checking the start/stop
27811 		 * cycle count log sense page.
27812 		 *
27813 		 * If "pm-capable" exists and is SD_PM_CAPABLE_FALSE (0)
27814 		 * then we should not power manage the device.
27815 		 *
27816 		 * If "pm-capable" doesn't exist then pm_capable_prop will
27817 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
27818 		 * sd will check the start/stop cycle count log sense page
27819 		 * and power manage the device if the cycle count limit has
27820 		 * not been exceeded.
27821 		 */
27822 		pm_capable_prop = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
27823 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
27824 		if (pm_capable_prop == SD_PM_CAPABLE_UNDEFINED) {
27825 			un->un_f_log_sense_supported = TRUE;
27826 		} else {
27827 			/*
27828 			 * pm-capable property exists.
27829 			 *
27830 			 * Convert "TRUE" values for pm_capable_prop to
27831 			 * SD_PM_CAPABLE_TRUE (1) to make it easier to check
27832 			 * later. "TRUE" values are any values except
27833 			 * SD_PM_CAPABLE_FALSE (0) and
27834 			 * SD_PM_CAPABLE_UNDEFINED (-1)
27835 			 */
27836 			if (pm_capable_prop == SD_PM_CAPABLE_FALSE) {
27837 				un->un_f_log_sense_supported = FALSE;
27838 			} else {
27839 				un->un_f_pm_supported = TRUE;
27840 			}
27841 
27842 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
27843 			    "sd_unit_attach: un:0x%p pm-capable "
27844 			    "property set to %d.\n", un, un->un_f_pm_supported);
27845 		}
27846 	}
27847 
27848 	if (un->un_f_is_hotpluggable) {
27849 
27850 		/*
27851 		 * Have to watch hotpluggable devices as well, since
27852 		 * that's the only way for userland applications to
27853 		 * detect hot removal while device is busy/mounted.
27854 		 */
27855 		un->un_f_monitor_media_state = TRUE;
27856 
27857 		un->un_f_check_start_stop = TRUE;
27858 
27859 	}
27860 }
27861 
27862 /*
27863  * sd_tg_rdwr:
27864  * Provides rdwr access for cmlb via sd_tgops. The start_block is
27865  * in sys block size, req_length in bytes.
27866  *
27867  */
27868 static int
27869 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
27870     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
27871 {
27872 	struct sd_lun *un;
27873 	int path_flag = (int)(uintptr_t)tg_cookie;
27874 	char *dkl = NULL;
27875 	diskaddr_t real_addr = start_block;
27876 	diskaddr_t first_byte, end_block;
27877 
27878 	size_t	buffer_size = reqlength;
27879 	int rval;
27880 	diskaddr_t	cap;
27881 	uint32_t	lbasize;
27882 
27883 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
27884 	if (un == NULL)
27885 		return (ENXIO);
27886 
27887 	if (cmd != TG_READ && cmd != TG_WRITE)
27888 		return (EINVAL);
27889 
27890 	mutex_enter(SD_MUTEX(un));
27891 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
27892 		mutex_exit(SD_MUTEX(un));
27893 		rval = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
27894 		    &lbasize, path_flag);
27895 		if (rval != 0)
27896 			return (rval);
27897 		mutex_enter(SD_MUTEX(un));
27898 		sd_update_block_info(un, lbasize, cap);
27899 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
27900 			mutex_exit(SD_MUTEX(un));
27901 			return (EIO);
27902 		}
27903 	}
27904 
27905 	if (NOT_DEVBSIZE(un)) {
27906 		/*
27907 		 * sys_blocksize != tgt_blocksize, need to re-adjust
27908 		 * blkno and save the index to beginning of dk_label
27909 		 */
27910 		first_byte  = SD_SYSBLOCKS2BYTES(un, start_block);
27911 		real_addr = first_byte / un->un_tgt_blocksize;
27912 
27913 		end_block = (first_byte + reqlength +
27914 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
27915 
27916 		/* round up buffer size to multiple of target block size */
27917 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
27918 
27919 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
27920 		    "label_addr: 0x%x allocation size: 0x%x\n",
27921 		    real_addr, buffer_size);
27922 
27923 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
27924 		    (reqlength % un->un_tgt_blocksize) != 0)
27925 			/* the request is not aligned */
27926 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
27927 	}
27928 
27929 	/*
27930 	 * The MMC standard allows READ CAPACITY to be
27931 	 * inaccurate by a bounded amount (in the interest of
27932 	 * response latency).  As a result, failed READs are
27933 	 * commonplace (due to the reading of metadata and not
27934 	 * data). Depending on the per-Vendor/drive Sense data,
27935 	 * the failed READ can cause many (unnecessary) retries.
27936 	 */
27937 
27938 	if (ISCD(un) && (cmd == TG_READ) &&
27939 	    (un->un_f_blockcount_is_valid == TRUE) &&
27940 	    ((start_block == (un->un_blockcount - 1))||
27941 	    (start_block == (un->un_blockcount - 2)))) {
27942 			path_flag = SD_PATH_DIRECT_PRIORITY;
27943 	}
27944 
27945 	mutex_exit(SD_MUTEX(un));
27946 	if (cmd == TG_READ) {
27947 		rval = sd_send_scsi_READ(un, (dkl != NULL)? dkl: bufaddr,
27948 		    buffer_size, real_addr, path_flag);
27949 		if (dkl != NULL)
27950 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
27951 			    real_addr), bufaddr, reqlength);
27952 	} else {
27953 		if (dkl) {
27954 			rval = sd_send_scsi_READ(un, dkl, buffer_size,
27955 			    real_addr, path_flag);
27956 			if (rval) {
27957 				kmem_free(dkl, buffer_size);
27958 				return (rval);
27959 			}
27960 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
27961 			    real_addr), reqlength);
27962 		}
27963 		rval = sd_send_scsi_WRITE(un, (dkl != NULL)? dkl: bufaddr,
27964 		    buffer_size, real_addr, path_flag);
27965 	}
27966 
27967 	if (dkl != NULL)
27968 		kmem_free(dkl, buffer_size);
27969 
27970 	return (rval);
27971 }
27972 
27973 
27974 static int
27975 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
27976 {
27977 
27978 	struct sd_lun *un;
27979 	diskaddr_t	cap;
27980 	uint32_t	lbasize;
27981 	int		path_flag = (int)(uintptr_t)tg_cookie;
27982 	int		ret = 0;
27983 
27984 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
27985 	if (un == NULL)
27986 		return (ENXIO);
27987 
27988 	switch (cmd) {
27989 	case TG_GETPHYGEOM:
27990 	case TG_GETVIRTGEOM:
27991 	case TG_GETCAPACITY:
27992 	case  TG_GETBLOCKSIZE:
27993 		mutex_enter(SD_MUTEX(un));
27994 
27995 		if ((un->un_f_blockcount_is_valid == TRUE) &&
27996 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
27997 			cap = un->un_blockcount;
27998 			lbasize = un->un_tgt_blocksize;
27999 			mutex_exit(SD_MUTEX(un));
28000 		} else {
28001 			mutex_exit(SD_MUTEX(un));
28002 			ret = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
28003 			    &lbasize, path_flag);
28004 			if (ret != 0)
28005 				return (ret);
28006 			mutex_enter(SD_MUTEX(un));
28007 			sd_update_block_info(un, lbasize, cap);
28008 			if ((un->un_f_blockcount_is_valid == FALSE) ||
28009 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
28010 				mutex_exit(SD_MUTEX(un));
28011 				return (EIO);
28012 			}
28013 			mutex_exit(SD_MUTEX(un));
28014 		}
28015 
28016 		if (cmd == TG_GETCAPACITY) {
28017 			*(diskaddr_t *)arg = cap;
28018 			return (0);
28019 		}
28020 
28021 		if (cmd == TG_GETBLOCKSIZE) {
28022 			*(uint32_t *)arg = lbasize;
28023 			return (0);
28024 		}
28025 
28026 		if (cmd == TG_GETPHYGEOM)
28027 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
28028 			    cap, lbasize, path_flag);
28029 		else
28030 			/* TG_GETVIRTGEOM */
28031 			ret = sd_get_virtual_geometry(un,
28032 			    (cmlb_geom_t *)arg, cap, lbasize);
28033 
28034 		return (ret);
28035 
28036 	case TG_GETATTR:
28037 		mutex_enter(SD_MUTEX(un));
28038 		((tg_attribute_t *)arg)->media_is_writable =
28039 		    un->un_f_mmc_writable_media;
28040 		mutex_exit(SD_MUTEX(un));
28041 		return (0);
28042 	default:
28043 		return (ENOTTY);
28044 
28045 	}
28046 
28047 }
28048