xref: /illumos-gate/usr/src/uts/common/io/scsi/targets/sd.c (revision 611e78b1)
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);
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 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
10495 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
10496 
10497 	/* Use the index obtained within xbuf_init */
10498 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
10499 
10500 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
10501 
10502 	return (0);
10503 }
10504 
10505 /*
10506  *    Function: sd_send_scsi_cmd
10507  *
10508  * Description: Runs a USCSI command for user (when called thru sdioctl),
10509  *		or for the driver
10510  *
10511  *   Arguments: dev - the dev_t for the device
10512  *		incmd - ptr to a valid uscsi_cmd struct
10513  *		flag - bit flag, indicating open settings, 32/64 bit type
10514  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
10515  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
10516  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
10517  *			to use the USCSI "direct" chain and bypass the normal
10518  *			command waitq.
10519  *
10520  * Return Code: 0 -  successful completion of the given command
10521  *		EIO - scsi_uscsi_handle_command() failed
10522  *		ENXIO  - soft state not found for specified dev
10523  *		EINVAL
10524  *		EFAULT - copyin/copyout error
10525  *		return code of scsi_uscsi_handle_command():
10526  *			EIO
10527  *			ENXIO
10528  *			EACCES
10529  *
10530  *     Context: Waits for command to complete. Can sleep.
10531  */
10532 
10533 static int
10534 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
10535 	enum uio_seg dataspace, int path_flag)
10536 {
10537 	struct sd_uscsi_info	*uip;
10538 	struct uscsi_cmd	*uscmd;
10539 	struct sd_lun	*un;
10540 	int	format = 0;
10541 	int	rval;
10542 
10543 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
10544 	if (un == NULL) {
10545 		return (ENXIO);
10546 	}
10547 
10548 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10549 
10550 #ifdef SDDEBUG
10551 	switch (dataspace) {
10552 	case UIO_USERSPACE:
10553 		SD_TRACE(SD_LOG_IO, un,
10554 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_USERSPACE\n", un);
10555 		break;
10556 	case UIO_SYSSPACE:
10557 		SD_TRACE(SD_LOG_IO, un,
10558 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_SYSSPACE\n", un);
10559 		break;
10560 	default:
10561 		SD_TRACE(SD_LOG_IO, un,
10562 		    "sd_send_scsi_cmd: entry: un:0x%p UNEXPECTED SPACE\n", un);
10563 		break;
10564 	}
10565 #endif
10566 
10567 	rval = scsi_uscsi_alloc_and_copyin((intptr_t)incmd, flag,
10568 	    SD_ADDRESS(un), &uscmd);
10569 	if (rval != 0) {
10570 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
10571 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
10572 		return (rval);
10573 	}
10574 
10575 	if ((uscmd->uscsi_cdb != NULL) &&
10576 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
10577 		mutex_enter(SD_MUTEX(un));
10578 		un->un_f_format_in_progress = TRUE;
10579 		mutex_exit(SD_MUTEX(un));
10580 		format = 1;
10581 	}
10582 
10583 	/*
10584 	 * Allocate an sd_uscsi_info struct and fill it with the info
10585 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
10586 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
10587 	 * since we allocate the buf here in this function, we do not
10588 	 * need to preserve the prior contents of b_private.
10589 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
10590 	 */
10591 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
10592 	uip->ui_flags = path_flag;
10593 	uip->ui_cmdp = uscmd;
10594 
10595 	/*
10596 	 * Commands sent with priority are intended for error recovery
10597 	 * situations, and do not have retries performed.
10598 	 */
10599 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
10600 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
10601 	}
10602 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
10603 
10604 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
10605 	    sd_uscsi_strategy, NULL, uip);
10606 
10607 #ifdef SDDEBUG
10608 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10609 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
10610 	    uscmd->uscsi_status, uscmd->uscsi_resid);
10611 	if (uscmd->uscsi_bufaddr != NULL) {
10612 		SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10613 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
10614 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
10615 		if (dataspace == UIO_SYSSPACE) {
10616 			SD_DUMP_MEMORY(un, SD_LOG_IO,
10617 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
10618 			    uscmd->uscsi_buflen, SD_LOG_HEX);
10619 		}
10620 	}
10621 #endif
10622 
10623 	if (format == 1) {
10624 		mutex_enter(SD_MUTEX(un));
10625 		un->un_f_format_in_progress = FALSE;
10626 		mutex_exit(SD_MUTEX(un));
10627 	}
10628 
10629 	(void) scsi_uscsi_copyout_and_free((intptr_t)incmd, uscmd);
10630 	kmem_free(uip, sizeof (struct sd_uscsi_info));
10631 
10632 	return (rval);
10633 }
10634 
10635 
10636 /*
10637  *    Function: sd_buf_iodone
10638  *
10639  * Description: Frees the sd_xbuf & returns the buf to its originator.
10640  *
10641  *     Context: May be called from interrupt context.
10642  */
10643 /* ARGSUSED */
10644 static void
10645 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
10646 {
10647 	struct sd_xbuf *xp;
10648 
10649 	ASSERT(un != NULL);
10650 	ASSERT(bp != NULL);
10651 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10652 
10653 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
10654 
10655 	xp = SD_GET_XBUF(bp);
10656 	ASSERT(xp != NULL);
10657 
10658 	mutex_enter(SD_MUTEX(un));
10659 
10660 	/*
10661 	 * Grab time when the cmd completed.
10662 	 * This is used for determining if the system has been
10663 	 * idle long enough to make it idle to the PM framework.
10664 	 * This is for lowering the overhead, and therefore improving
10665 	 * performance per I/O operation.
10666 	 */
10667 	un->un_pm_idle_time = ddi_get_time();
10668 
10669 	un->un_ncmds_in_driver--;
10670 	ASSERT(un->un_ncmds_in_driver >= 0);
10671 	SD_INFO(SD_LOG_IO, un, "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
10672 	    un->un_ncmds_in_driver);
10673 
10674 	mutex_exit(SD_MUTEX(un));
10675 
10676 	ddi_xbuf_done(bp, un->un_xbuf_attr);	/* xbuf is gone after this */
10677 	biodone(bp);				/* bp is gone after this */
10678 
10679 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
10680 }
10681 
10682 
10683 /*
10684  *    Function: sd_uscsi_iodone
10685  *
10686  * Description: Frees the sd_xbuf & returns the buf to its originator.
10687  *
10688  *     Context: May be called from interrupt context.
10689  */
10690 /* ARGSUSED */
10691 static void
10692 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
10693 {
10694 	struct sd_xbuf *xp;
10695 
10696 	ASSERT(un != NULL);
10697 	ASSERT(bp != NULL);
10698 
10699 	xp = SD_GET_XBUF(bp);
10700 	ASSERT(xp != NULL);
10701 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10702 
10703 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
10704 
10705 	bp->b_private = xp->xb_private;
10706 
10707 	mutex_enter(SD_MUTEX(un));
10708 
10709 	/*
10710 	 * Grab time when the cmd completed.
10711 	 * This is used for determining if the system has been
10712 	 * idle long enough to make it idle to the PM framework.
10713 	 * This is for lowering the overhead, and therefore improving
10714 	 * performance per I/O operation.
10715 	 */
10716 	un->un_pm_idle_time = ddi_get_time();
10717 
10718 	un->un_ncmds_in_driver--;
10719 	ASSERT(un->un_ncmds_in_driver >= 0);
10720 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
10721 	    un->un_ncmds_in_driver);
10722 
10723 	mutex_exit(SD_MUTEX(un));
10724 
10725 	kmem_free(xp, sizeof (struct sd_xbuf));
10726 	biodone(bp);
10727 
10728 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
10729 }
10730 
10731 
10732 /*
10733  *    Function: sd_mapblockaddr_iostart
10734  *
10735  * Description: Verify request lies within the partition limits for
10736  *		the indicated minor device.  Issue "overrun" buf if
10737  *		request would exceed partition range.  Converts
10738  *		partition-relative block address to absolute.
10739  *
10740  *     Context: Can sleep
10741  *
10742  *      Issues: This follows what the old code did, in terms of accessing
10743  *		some of the partition info in the unit struct without holding
10744  *		the mutext.  This is a general issue, if the partition info
10745  *		can be altered while IO is in progress... as soon as we send
10746  *		a buf, its partitioning can be invalid before it gets to the
10747  *		device.  Probably the right fix is to move partitioning out
10748  *		of the driver entirely.
10749  */
10750 
10751 static void
10752 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
10753 {
10754 	diskaddr_t	nblocks;	/* #blocks in the given partition */
10755 	daddr_t	blocknum;	/* Block number specified by the buf */
10756 	size_t	requested_nblocks;
10757 	size_t	available_nblocks;
10758 	int	partition;
10759 	diskaddr_t	partition_offset;
10760 	struct sd_xbuf *xp;
10761 
10762 
10763 	ASSERT(un != NULL);
10764 	ASSERT(bp != NULL);
10765 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10766 
10767 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10768 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
10769 
10770 	xp = SD_GET_XBUF(bp);
10771 	ASSERT(xp != NULL);
10772 
10773 	/*
10774 	 * If the geometry is not indicated as valid, attempt to access
10775 	 * the unit & verify the geometry/label. This can be the case for
10776 	 * removable-media devices, of if the device was opened in
10777 	 * NDELAY/NONBLOCK mode.
10778 	 */
10779 	if (!SD_IS_VALID_LABEL(un) &&
10780 	    (sd_ready_and_valid(un) != SD_READY_VALID)) {
10781 		/*
10782 		 * For removable devices it is possible to start an I/O
10783 		 * without a media by opening the device in nodelay mode.
10784 		 * Also for writable CDs there can be many scenarios where
10785 		 * there is no geometry yet but volume manager is trying to
10786 		 * issue a read() just because it can see TOC on the CD. So
10787 		 * do not print a message for removables.
10788 		 */
10789 		if (!un->un_f_has_removable_media) {
10790 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10791 			    "i/o to invalid geometry\n");
10792 		}
10793 		bioerror(bp, EIO);
10794 		bp->b_resid = bp->b_bcount;
10795 		SD_BEGIN_IODONE(index, un, bp);
10796 		return;
10797 	}
10798 
10799 	partition = SDPART(bp->b_edev);
10800 
10801 	nblocks = 0;
10802 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
10803 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
10804 
10805 	/*
10806 	 * blocknum is the starting block number of the request. At this
10807 	 * point it is still relative to the start of the minor device.
10808 	 */
10809 	blocknum = xp->xb_blkno;
10810 
10811 	/*
10812 	 * Legacy: If the starting block number is one past the last block
10813 	 * in the partition, do not set B_ERROR in the buf.
10814 	 */
10815 	if (blocknum == nblocks)  {
10816 		goto error_exit;
10817 	}
10818 
10819 	/*
10820 	 * Confirm that the first block of the request lies within the
10821 	 * partition limits. Also the requested number of bytes must be
10822 	 * a multiple of the system block size.
10823 	 */
10824 	if ((blocknum < 0) || (blocknum >= nblocks) ||
10825 	    ((bp->b_bcount & (un->un_sys_blocksize - 1)) != 0)) {
10826 		bp->b_flags |= B_ERROR;
10827 		goto error_exit;
10828 	}
10829 
10830 	/*
10831 	 * If the requsted # blocks exceeds the available # blocks, that
10832 	 * is an overrun of the partition.
10833 	 */
10834 	requested_nblocks = SD_BYTES2SYSBLOCKS(un, bp->b_bcount);
10835 	available_nblocks = (size_t)(nblocks - blocknum);
10836 	ASSERT(nblocks >= blocknum);
10837 
10838 	if (requested_nblocks > available_nblocks) {
10839 		/*
10840 		 * Allocate an "overrun" buf to allow the request to proceed
10841 		 * for the amount of space available in the partition. The
10842 		 * amount not transferred will be added into the b_resid
10843 		 * when the operation is complete. The overrun buf
10844 		 * replaces the original buf here, and the original buf
10845 		 * is saved inside the overrun buf, for later use.
10846 		 */
10847 		size_t resid = SD_SYSBLOCKS2BYTES(un,
10848 		    (offset_t)(requested_nblocks - available_nblocks));
10849 		size_t count = bp->b_bcount - resid;
10850 		/*
10851 		 * Note: count is an unsigned entity thus it'll NEVER
10852 		 * be less than 0 so ASSERT the original values are
10853 		 * correct.
10854 		 */
10855 		ASSERT(bp->b_bcount >= resid);
10856 
10857 		bp = sd_bioclone_alloc(bp, count, blocknum,
10858 		    (int (*)(struct buf *)) sd_mapblockaddr_iodone);
10859 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
10860 		ASSERT(xp != NULL);
10861 	}
10862 
10863 	/* At this point there should be no residual for this buf. */
10864 	ASSERT(bp->b_resid == 0);
10865 
10866 	/* Convert the block number to an absolute address. */
10867 	xp->xb_blkno += partition_offset;
10868 
10869 	SD_NEXT_IOSTART(index, un, bp);
10870 
10871 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10872 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
10873 
10874 	return;
10875 
10876 error_exit:
10877 	bp->b_resid = bp->b_bcount;
10878 	SD_BEGIN_IODONE(index, un, bp);
10879 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10880 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
10881 }
10882 
10883 
10884 /*
10885  *    Function: sd_mapblockaddr_iodone
10886  *
10887  * Description: Completion-side processing for partition management.
10888  *
10889  *     Context: May be called under interrupt context
10890  */
10891 
10892 static void
10893 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
10894 {
10895 	/* int	partition; */	/* Not used, see below. */
10896 	ASSERT(un != NULL);
10897 	ASSERT(bp != NULL);
10898 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10899 
10900 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10901 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
10902 
10903 	if (bp->b_iodone == (int (*)(struct buf *)) sd_mapblockaddr_iodone) {
10904 		/*
10905 		 * We have an "overrun" buf to deal with...
10906 		 */
10907 		struct sd_xbuf	*xp;
10908 		struct buf	*obp;	/* ptr to the original buf */
10909 
10910 		xp = SD_GET_XBUF(bp);
10911 		ASSERT(xp != NULL);
10912 
10913 		/* Retrieve the pointer to the original buf */
10914 		obp = (struct buf *)xp->xb_private;
10915 		ASSERT(obp != NULL);
10916 
10917 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
10918 		bioerror(obp, bp->b_error);
10919 
10920 		sd_bioclone_free(bp);
10921 
10922 		/*
10923 		 * Get back the original buf.
10924 		 * Note that since the restoration of xb_blkno below
10925 		 * was removed, the sd_xbuf is not needed.
10926 		 */
10927 		bp = obp;
10928 		/*
10929 		 * xp = SD_GET_XBUF(bp);
10930 		 * ASSERT(xp != NULL);
10931 		 */
10932 	}
10933 
10934 	/*
10935 	 * Convert sd->xb_blkno back to a minor-device relative value.
10936 	 * Note: this has been commented out, as it is not needed in the
10937 	 * current implementation of the driver (ie, since this function
10938 	 * is at the top of the layering chains, so the info will be
10939 	 * discarded) and it is in the "hot" IO path.
10940 	 *
10941 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
10942 	 * xp->xb_blkno -= un->un_offset[partition];
10943 	 */
10944 
10945 	SD_NEXT_IODONE(index, un, bp);
10946 
10947 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10948 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
10949 }
10950 
10951 
10952 /*
10953  *    Function: sd_mapblocksize_iostart
10954  *
10955  * Description: Convert between system block size (un->un_sys_blocksize)
10956  *		and target block size (un->un_tgt_blocksize).
10957  *
10958  *     Context: Can sleep to allocate resources.
10959  *
10960  * Assumptions: A higher layer has already performed any partition validation,
10961  *		and converted the xp->xb_blkno to an absolute value relative
10962  *		to the start of the device.
10963  *
10964  *		It is also assumed that the higher layer has implemented
10965  *		an "overrun" mechanism for the case where the request would
10966  *		read/write beyond the end of a partition.  In this case we
10967  *		assume (and ASSERT) that bp->b_resid == 0.
10968  *
10969  *		Note: The implementation for this routine assumes the target
10970  *		block size remains constant between allocation and transport.
10971  */
10972 
10973 static void
10974 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
10975 {
10976 	struct sd_mapblocksize_info	*bsp;
10977 	struct sd_xbuf			*xp;
10978 	offset_t first_byte;
10979 	daddr_t	start_block, end_block;
10980 	daddr_t	request_bytes;
10981 	ushort_t is_aligned = FALSE;
10982 
10983 	ASSERT(un != NULL);
10984 	ASSERT(bp != NULL);
10985 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10986 	ASSERT(bp->b_resid == 0);
10987 
10988 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
10989 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
10990 
10991 	/*
10992 	 * For a non-writable CD, a write request is an error
10993 	 */
10994 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
10995 	    (un->un_f_mmc_writable_media == FALSE)) {
10996 		bioerror(bp, EIO);
10997 		bp->b_resid = bp->b_bcount;
10998 		SD_BEGIN_IODONE(index, un, bp);
10999 		return;
11000 	}
11001 
11002 	/*
11003 	 * We do not need a shadow buf if the device is using
11004 	 * un->un_sys_blocksize as its block size or if bcount == 0.
11005 	 * In this case there is no layer-private data block allocated.
11006 	 */
11007 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
11008 	    (bp->b_bcount == 0)) {
11009 		goto done;
11010 	}
11011 
11012 #if defined(__i386) || defined(__amd64)
11013 	/* We do not support non-block-aligned transfers for ROD devices */
11014 	ASSERT(!ISROD(un));
11015 #endif
11016 
11017 	xp = SD_GET_XBUF(bp);
11018 	ASSERT(xp != NULL);
11019 
11020 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11021 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
11022 	    un->un_tgt_blocksize, un->un_sys_blocksize);
11023 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11024 	    "request start block:0x%x\n", xp->xb_blkno);
11025 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11026 	    "request len:0x%x\n", bp->b_bcount);
11027 
11028 	/*
11029 	 * Allocate the layer-private data area for the mapblocksize layer.
11030 	 * Layers are allowed to use the xp_private member of the sd_xbuf
11031 	 * struct to store the pointer to their layer-private data block, but
11032 	 * each layer also has the responsibility of restoring the prior
11033 	 * contents of xb_private before returning the buf/xbuf to the
11034 	 * higher layer that sent it.
11035 	 *
11036 	 * Here we save the prior contents of xp->xb_private into the
11037 	 * bsp->mbs_oprivate field of our layer-private data area. This value
11038 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
11039 	 * the layer-private area and returning the buf/xbuf to the layer
11040 	 * that sent it.
11041 	 *
11042 	 * Note that here we use kmem_zalloc for the allocation as there are
11043 	 * parts of the mapblocksize code that expect certain fields to be
11044 	 * zero unless explicitly set to a required value.
11045 	 */
11046 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
11047 	bsp->mbs_oprivate = xp->xb_private;
11048 	xp->xb_private = bsp;
11049 
11050 	/*
11051 	 * This treats the data on the disk (target) as an array of bytes.
11052 	 * first_byte is the byte offset, from the beginning of the device,
11053 	 * to the location of the request. This is converted from a
11054 	 * un->un_sys_blocksize block address to a byte offset, and then back
11055 	 * to a block address based upon a un->un_tgt_blocksize block size.
11056 	 *
11057 	 * xp->xb_blkno should be absolute upon entry into this function,
11058 	 * but, but it is based upon partitions that use the "system"
11059 	 * block size. It must be adjusted to reflect the block size of
11060 	 * the target.
11061 	 *
11062 	 * Note that end_block is actually the block that follows the last
11063 	 * block of the request, but that's what is needed for the computation.
11064 	 */
11065 	first_byte  = SD_SYSBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
11066 	start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
11067 	end_block   = (first_byte + bp->b_bcount + un->un_tgt_blocksize - 1) /
11068 	    un->un_tgt_blocksize;
11069 
11070 	/* request_bytes is rounded up to a multiple of the target block size */
11071 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
11072 
11073 	/*
11074 	 * See if the starting address of the request and the request
11075 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
11076 	 * then we do not need to allocate a shadow buf to handle the request.
11077 	 */
11078 	if (((first_byte   % un->un_tgt_blocksize) == 0) &&
11079 	    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
11080 		is_aligned = TRUE;
11081 	}
11082 
11083 	if ((bp->b_flags & B_READ) == 0) {
11084 		/*
11085 		 * Lock the range for a write operation. An aligned request is
11086 		 * considered a simple write; otherwise the request must be a
11087 		 * read-modify-write.
11088 		 */
11089 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
11090 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
11091 	}
11092 
11093 	/*
11094 	 * Alloc a shadow buf if the request is not aligned. Also, this is
11095 	 * where the READ command is generated for a read-modify-write. (The
11096 	 * write phase is deferred until after the read completes.)
11097 	 */
11098 	if (is_aligned == FALSE) {
11099 
11100 		struct sd_mapblocksize_info	*shadow_bsp;
11101 		struct sd_xbuf	*shadow_xp;
11102 		struct buf	*shadow_bp;
11103 
11104 		/*
11105 		 * Allocate the shadow buf and it associated xbuf. Note that
11106 		 * after this call the xb_blkno value in both the original
11107 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
11108 		 * same: absolute relative to the start of the device, and
11109 		 * adjusted for the target block size. The b_blkno in the
11110 		 * shadow buf will also be set to this value. We should never
11111 		 * change b_blkno in the original bp however.
11112 		 *
11113 		 * Note also that the shadow buf will always need to be a
11114 		 * READ command, regardless of whether the incoming command
11115 		 * is a READ or a WRITE.
11116 		 */
11117 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
11118 		    xp->xb_blkno,
11119 		    (int (*)(struct buf *)) sd_mapblocksize_iodone);
11120 
11121 		shadow_xp = SD_GET_XBUF(shadow_bp);
11122 
11123 		/*
11124 		 * Allocate the layer-private data for the shadow buf.
11125 		 * (No need to preserve xb_private in the shadow xbuf.)
11126 		 */
11127 		shadow_xp->xb_private = shadow_bsp =
11128 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
11129 
11130 		/*
11131 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
11132 		 * to figure out where the start of the user data is (based upon
11133 		 * the system block size) in the data returned by the READ
11134 		 * command (which will be based upon the target blocksize). Note
11135 		 * that this is only really used if the request is unaligned.
11136 		 */
11137 		bsp->mbs_copy_offset = (ssize_t)(first_byte -
11138 		    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
11139 		ASSERT((bsp->mbs_copy_offset >= 0) &&
11140 		    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
11141 
11142 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
11143 
11144 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
11145 
11146 		/* Transfer the wmap (if any) to the shadow buf */
11147 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
11148 		bsp->mbs_wmp = NULL;
11149 
11150 		/*
11151 		 * The shadow buf goes on from here in place of the
11152 		 * original buf.
11153 		 */
11154 		shadow_bsp->mbs_orig_bp = bp;
11155 		bp = shadow_bp;
11156 	}
11157 
11158 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11159 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
11160 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11161 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
11162 	    request_bytes);
11163 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11164 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
11165 
11166 done:
11167 	SD_NEXT_IOSTART(index, un, bp);
11168 
11169 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11170 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
11171 }
11172 
11173 
11174 /*
11175  *    Function: sd_mapblocksize_iodone
11176  *
11177  * Description: Completion side processing for block-size mapping.
11178  *
11179  *     Context: May be called under interrupt context
11180  */
11181 
11182 static void
11183 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
11184 {
11185 	struct sd_mapblocksize_info	*bsp;
11186 	struct sd_xbuf	*xp;
11187 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
11188 	struct buf	*orig_bp;	/* ptr to the original buf */
11189 	offset_t	shadow_end;
11190 	offset_t	request_end;
11191 	offset_t	shadow_start;
11192 	ssize_t		copy_offset;
11193 	size_t		copy_length;
11194 	size_t		shortfall;
11195 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
11196 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
11197 
11198 	ASSERT(un != NULL);
11199 	ASSERT(bp != NULL);
11200 
11201 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11202 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
11203 
11204 	/*
11205 	 * There is no shadow buf or layer-private data if the target is
11206 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
11207 	 */
11208 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
11209 	    (bp->b_bcount == 0)) {
11210 		goto exit;
11211 	}
11212 
11213 	xp = SD_GET_XBUF(bp);
11214 	ASSERT(xp != NULL);
11215 
11216 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
11217 	bsp = xp->xb_private;
11218 
11219 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
11220 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
11221 
11222 	if (is_write) {
11223 		/*
11224 		 * For a WRITE request we must free up the block range that
11225 		 * we have locked up.  This holds regardless of whether this is
11226 		 * an aligned write request or a read-modify-write request.
11227 		 */
11228 		sd_range_unlock(un, bsp->mbs_wmp);
11229 		bsp->mbs_wmp = NULL;
11230 	}
11231 
11232 	if ((bp->b_iodone != (int(*)(struct buf *))sd_mapblocksize_iodone)) {
11233 		/*
11234 		 * An aligned read or write command will have no shadow buf;
11235 		 * there is not much else to do with it.
11236 		 */
11237 		goto done;
11238 	}
11239 
11240 	orig_bp = bsp->mbs_orig_bp;
11241 	ASSERT(orig_bp != NULL);
11242 	orig_xp = SD_GET_XBUF(orig_bp);
11243 	ASSERT(orig_xp != NULL);
11244 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11245 
11246 	if (!is_write && has_wmap) {
11247 		/*
11248 		 * A READ with a wmap means this is the READ phase of a
11249 		 * read-modify-write. If an error occurred on the READ then
11250 		 * we do not proceed with the WRITE phase or copy any data.
11251 		 * Just release the write maps and return with an error.
11252 		 */
11253 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
11254 			orig_bp->b_resid = orig_bp->b_bcount;
11255 			bioerror(orig_bp, bp->b_error);
11256 			sd_range_unlock(un, bsp->mbs_wmp);
11257 			goto freebuf_done;
11258 		}
11259 	}
11260 
11261 	/*
11262 	 * Here is where we set up to copy the data from the shadow buf
11263 	 * into the space associated with the original buf.
11264 	 *
11265 	 * To deal with the conversion between block sizes, these
11266 	 * computations treat the data as an array of bytes, with the
11267 	 * first byte (byte 0) corresponding to the first byte in the
11268 	 * first block on the disk.
11269 	 */
11270 
11271 	/*
11272 	 * shadow_start and shadow_len indicate the location and size of
11273 	 * the data returned with the shadow IO request.
11274 	 */
11275 	shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
11276 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
11277 
11278 	/*
11279 	 * copy_offset gives the offset (in bytes) from the start of the first
11280 	 * block of the READ request to the beginning of the data.  We retrieve
11281 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
11282 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
11283 	 * data to be copied (in bytes).
11284 	 */
11285 	copy_offset  = bsp->mbs_copy_offset;
11286 	ASSERT((copy_offset >= 0) && (copy_offset < un->un_tgt_blocksize));
11287 	copy_length  = orig_bp->b_bcount;
11288 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
11289 
11290 	/*
11291 	 * Set up the resid and error fields of orig_bp as appropriate.
11292 	 */
11293 	if (shadow_end >= request_end) {
11294 		/* We got all the requested data; set resid to zero */
11295 		orig_bp->b_resid = 0;
11296 	} else {
11297 		/*
11298 		 * We failed to get enough data to fully satisfy the original
11299 		 * request. Just copy back whatever data we got and set
11300 		 * up the residual and error code as required.
11301 		 *
11302 		 * 'shortfall' is the amount by which the data received with the
11303 		 * shadow buf has "fallen short" of the requested amount.
11304 		 */
11305 		shortfall = (size_t)(request_end - shadow_end);
11306 
11307 		if (shortfall > orig_bp->b_bcount) {
11308 			/*
11309 			 * We did not get enough data to even partially
11310 			 * fulfill the original request.  The residual is
11311 			 * equal to the amount requested.
11312 			 */
11313 			orig_bp->b_resid = orig_bp->b_bcount;
11314 		} else {
11315 			/*
11316 			 * We did not get all the data that we requested
11317 			 * from the device, but we will try to return what
11318 			 * portion we did get.
11319 			 */
11320 			orig_bp->b_resid = shortfall;
11321 		}
11322 		ASSERT(copy_length >= orig_bp->b_resid);
11323 		copy_length  -= orig_bp->b_resid;
11324 	}
11325 
11326 	/* Propagate the error code from the shadow buf to the original buf */
11327 	bioerror(orig_bp, bp->b_error);
11328 
11329 	if (is_write) {
11330 		goto freebuf_done;	/* No data copying for a WRITE */
11331 	}
11332 
11333 	if (has_wmap) {
11334 		/*
11335 		 * This is a READ command from the READ phase of a
11336 		 * read-modify-write request. We have to copy the data given
11337 		 * by the user OVER the data returned by the READ command,
11338 		 * then convert the command from a READ to a WRITE and send
11339 		 * it back to the target.
11340 		 */
11341 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
11342 		    copy_length);
11343 
11344 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
11345 
11346 		/*
11347 		 * Dispatch the WRITE command to the taskq thread, which
11348 		 * will in turn send the command to the target. When the
11349 		 * WRITE command completes, we (sd_mapblocksize_iodone())
11350 		 * will get called again as part of the iodone chain
11351 		 * processing for it. Note that we will still be dealing
11352 		 * with the shadow buf at that point.
11353 		 */
11354 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
11355 		    KM_NOSLEEP) != 0) {
11356 			/*
11357 			 * Dispatch was successful so we are done. Return
11358 			 * without going any higher up the iodone chain. Do
11359 			 * not free up any layer-private data until after the
11360 			 * WRITE completes.
11361 			 */
11362 			return;
11363 		}
11364 
11365 		/*
11366 		 * Dispatch of the WRITE command failed; set up the error
11367 		 * condition and send this IO back up the iodone chain.
11368 		 */
11369 		bioerror(orig_bp, EIO);
11370 		orig_bp->b_resid = orig_bp->b_bcount;
11371 
11372 	} else {
11373 		/*
11374 		 * This is a regular READ request (ie, not a RMW). Copy the
11375 		 * data from the shadow buf into the original buf. The
11376 		 * copy_offset compensates for any "misalignment" between the
11377 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
11378 		 * original buf (with its un->un_sys_blocksize blocks).
11379 		 */
11380 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
11381 		    copy_length);
11382 	}
11383 
11384 freebuf_done:
11385 
11386 	/*
11387 	 * At this point we still have both the shadow buf AND the original
11388 	 * buf to deal with, as well as the layer-private data area in each.
11389 	 * Local variables are as follows:
11390 	 *
11391 	 * bp -- points to shadow buf
11392 	 * xp -- points to xbuf of shadow buf
11393 	 * bsp -- points to layer-private data area of shadow buf
11394 	 * orig_bp -- points to original buf
11395 	 *
11396 	 * First free the shadow buf and its associated xbuf, then free the
11397 	 * layer-private data area from the shadow buf. There is no need to
11398 	 * restore xb_private in the shadow xbuf.
11399 	 */
11400 	sd_shadow_buf_free(bp);
11401 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11402 
11403 	/*
11404 	 * Now update the local variables to point to the original buf, xbuf,
11405 	 * and layer-private area.
11406 	 */
11407 	bp = orig_bp;
11408 	xp = SD_GET_XBUF(bp);
11409 	ASSERT(xp != NULL);
11410 	ASSERT(xp == orig_xp);
11411 	bsp = xp->xb_private;
11412 	ASSERT(bsp != NULL);
11413 
11414 done:
11415 	/*
11416 	 * Restore xb_private to whatever it was set to by the next higher
11417 	 * layer in the chain, then free the layer-private data area.
11418 	 */
11419 	xp->xb_private = bsp->mbs_oprivate;
11420 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11421 
11422 exit:
11423 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
11424 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
11425 
11426 	SD_NEXT_IODONE(index, un, bp);
11427 }
11428 
11429 
11430 /*
11431  *    Function: sd_checksum_iostart
11432  *
11433  * Description: A stub function for a layer that's currently not used.
11434  *		For now just a placeholder.
11435  *
11436  *     Context: Kernel thread context
11437  */
11438 
11439 static void
11440 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
11441 {
11442 	ASSERT(un != NULL);
11443 	ASSERT(bp != NULL);
11444 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11445 	SD_NEXT_IOSTART(index, un, bp);
11446 }
11447 
11448 
11449 /*
11450  *    Function: sd_checksum_iodone
11451  *
11452  * Description: A stub function for a layer that's currently not used.
11453  *		For now just a placeholder.
11454  *
11455  *     Context: May be called under interrupt context
11456  */
11457 
11458 static void
11459 sd_checksum_iodone(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_IODONE(index, un, bp);
11465 }
11466 
11467 
11468 /*
11469  *    Function: sd_checksum_uscsi_iostart
11470  *
11471  * Description: A stub function for a layer that's currently not used.
11472  *		For now just a placeholder.
11473  *
11474  *     Context: Kernel thread context
11475  */
11476 
11477 static void
11478 sd_checksum_uscsi_iostart(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_IOSTART(index, un, bp);
11484 }
11485 
11486 
11487 /*
11488  *    Function: sd_checksum_uscsi_iodone
11489  *
11490  * Description: A stub function for a layer that's currently not used.
11491  *		For now just a placeholder.
11492  *
11493  *     Context: May be called under interrupt context
11494  */
11495 
11496 static void
11497 sd_checksum_uscsi_iodone(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_IODONE(index, un, bp);
11503 }
11504 
11505 
11506 /*
11507  *    Function: sd_pm_iostart
11508  *
11509  * Description: iostart-side routine for Power mangement.
11510  *
11511  *     Context: Kernel thread context
11512  */
11513 
11514 static void
11515 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
11516 {
11517 	ASSERT(un != NULL);
11518 	ASSERT(bp != NULL);
11519 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11520 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11521 
11522 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
11523 
11524 	if (sd_pm_entry(un) != DDI_SUCCESS) {
11525 		/*
11526 		 * Set up to return the failed buf back up the 'iodone'
11527 		 * side of the calling chain.
11528 		 */
11529 		bioerror(bp, EIO);
11530 		bp->b_resid = bp->b_bcount;
11531 
11532 		SD_BEGIN_IODONE(index, un, bp);
11533 
11534 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11535 		return;
11536 	}
11537 
11538 	SD_NEXT_IOSTART(index, un, bp);
11539 
11540 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11541 }
11542 
11543 
11544 /*
11545  *    Function: sd_pm_iodone
11546  *
11547  * Description: iodone-side routine for power mangement.
11548  *
11549  *     Context: may be called from interrupt context
11550  */
11551 
11552 static void
11553 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
11554 {
11555 	ASSERT(un != NULL);
11556 	ASSERT(bp != NULL);
11557 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11558 
11559 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
11560 
11561 	/*
11562 	 * After attach the following flag is only read, so don't
11563 	 * take the penalty of acquiring a mutex for it.
11564 	 */
11565 	if (un->un_f_pm_is_enabled == TRUE) {
11566 		sd_pm_exit(un);
11567 	}
11568 
11569 	SD_NEXT_IODONE(index, un, bp);
11570 
11571 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
11572 }
11573 
11574 
11575 /*
11576  *    Function: sd_core_iostart
11577  *
11578  * Description: Primary driver function for enqueuing buf(9S) structs from
11579  *		the system and initiating IO to the target device
11580  *
11581  *     Context: Kernel thread context. Can sleep.
11582  *
11583  * Assumptions:  - The given xp->xb_blkno is absolute
11584  *		   (ie, relative to the start of the device).
11585  *		 - The IO is to be done using the native blocksize of
11586  *		   the device, as specified in un->un_tgt_blocksize.
11587  */
11588 /* ARGSUSED */
11589 static void
11590 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
11591 {
11592 	struct sd_xbuf *xp;
11593 
11594 	ASSERT(un != NULL);
11595 	ASSERT(bp != NULL);
11596 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11597 	ASSERT(bp->b_resid == 0);
11598 
11599 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
11600 
11601 	xp = SD_GET_XBUF(bp);
11602 	ASSERT(xp != NULL);
11603 
11604 	mutex_enter(SD_MUTEX(un));
11605 
11606 	/*
11607 	 * If we are currently in the failfast state, fail any new IO
11608 	 * that has B_FAILFAST set, then return.
11609 	 */
11610 	if ((bp->b_flags & B_FAILFAST) &&
11611 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
11612 		mutex_exit(SD_MUTEX(un));
11613 		bioerror(bp, EIO);
11614 		bp->b_resid = bp->b_bcount;
11615 		SD_BEGIN_IODONE(index, un, bp);
11616 		return;
11617 	}
11618 
11619 	if (SD_IS_DIRECT_PRIORITY(xp)) {
11620 		/*
11621 		 * Priority command -- transport it immediately.
11622 		 *
11623 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
11624 		 * because all direct priority commands should be associated
11625 		 * with error recovery actions which we don't want to retry.
11626 		 */
11627 		sd_start_cmds(un, bp);
11628 	} else {
11629 		/*
11630 		 * Normal command -- add it to the wait queue, then start
11631 		 * transporting commands from the wait queue.
11632 		 */
11633 		sd_add_buf_to_waitq(un, bp);
11634 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
11635 		sd_start_cmds(un, NULL);
11636 	}
11637 
11638 	mutex_exit(SD_MUTEX(un));
11639 
11640 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
11641 }
11642 
11643 
11644 /*
11645  *    Function: sd_init_cdb_limits
11646  *
11647  * Description: This is to handle scsi_pkt initialization differences
11648  *		between the driver platforms.
11649  *
11650  *		Legacy behaviors:
11651  *
11652  *		If the block number or the sector count exceeds the
11653  *		capabilities of a Group 0 command, shift over to a
11654  *		Group 1 command. We don't blindly use Group 1
11655  *		commands because a) some drives (CDC Wren IVs) get a
11656  *		bit confused, and b) there is probably a fair amount
11657  *		of speed difference for a target to receive and decode
11658  *		a 10 byte command instead of a 6 byte command.
11659  *
11660  *		The xfer time difference of 6 vs 10 byte CDBs is
11661  *		still significant so this code is still worthwhile.
11662  *		10 byte CDBs are very inefficient with the fas HBA driver
11663  *		and older disks. Each CDB byte took 1 usec with some
11664  *		popular disks.
11665  *
11666  *     Context: Must be called at attach time
11667  */
11668 
11669 static void
11670 sd_init_cdb_limits(struct sd_lun *un)
11671 {
11672 	int hba_cdb_limit;
11673 
11674 	/*
11675 	 * Use CDB_GROUP1 commands for most devices except for
11676 	 * parallel SCSI fixed drives in which case we get better
11677 	 * performance using CDB_GROUP0 commands (where applicable).
11678 	 */
11679 	un->un_mincdb = SD_CDB_GROUP1;
11680 #if !defined(__fibre)
11681 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
11682 	    !un->un_f_has_removable_media) {
11683 		un->un_mincdb = SD_CDB_GROUP0;
11684 	}
11685 #endif
11686 
11687 	/*
11688 	 * Try to read the max-cdb-length supported by HBA.
11689 	 */
11690 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
11691 	if (0 >= un->un_max_hba_cdb) {
11692 		un->un_max_hba_cdb = CDB_GROUP4;
11693 		hba_cdb_limit = SD_CDB_GROUP4;
11694 	} else if (0 < un->un_max_hba_cdb &&
11695 	    un->un_max_hba_cdb < CDB_GROUP1) {
11696 		hba_cdb_limit = SD_CDB_GROUP0;
11697 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
11698 	    un->un_max_hba_cdb < CDB_GROUP5) {
11699 		hba_cdb_limit = SD_CDB_GROUP1;
11700 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
11701 	    un->un_max_hba_cdb < CDB_GROUP4) {
11702 		hba_cdb_limit = SD_CDB_GROUP5;
11703 	} else {
11704 		hba_cdb_limit = SD_CDB_GROUP4;
11705 	}
11706 
11707 	/*
11708 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
11709 	 * commands for fixed disks unless we are building for a 32 bit
11710 	 * kernel.
11711 	 */
11712 #ifdef _LP64
11713 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11714 	    min(hba_cdb_limit, SD_CDB_GROUP4);
11715 #else
11716 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11717 	    min(hba_cdb_limit, SD_CDB_GROUP1);
11718 #endif
11719 
11720 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
11721 	    ? sizeof (struct scsi_arq_status) : 1);
11722 	un->un_cmd_timeout = (ushort_t)sd_io_time;
11723 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
11724 }
11725 
11726 
11727 /*
11728  *    Function: sd_initpkt_for_buf
11729  *
11730  * Description: Allocate and initialize for transport a scsi_pkt struct,
11731  *		based upon the info specified in the given buf struct.
11732  *
11733  *		Assumes the xb_blkno in the request is absolute (ie,
11734  *		relative to the start of the device (NOT partition!).
11735  *		Also assumes that the request is using the native block
11736  *		size of the device (as returned by the READ CAPACITY
11737  *		command).
11738  *
11739  * Return Code: SD_PKT_ALLOC_SUCCESS
11740  *		SD_PKT_ALLOC_FAILURE
11741  *		SD_PKT_ALLOC_FAILURE_NO_DMA
11742  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11743  *
11744  *     Context: Kernel thread and may be called from software interrupt context
11745  *		as part of a sdrunout callback. This function may not block or
11746  *		call routines that block
11747  */
11748 
11749 static int
11750 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
11751 {
11752 	struct sd_xbuf	*xp;
11753 	struct scsi_pkt *pktp = NULL;
11754 	struct sd_lun	*un;
11755 	size_t		blockcount;
11756 	daddr_t		startblock;
11757 	int		rval;
11758 	int		cmd_flags;
11759 
11760 	ASSERT(bp != NULL);
11761 	ASSERT(pktpp != NULL);
11762 	xp = SD_GET_XBUF(bp);
11763 	ASSERT(xp != NULL);
11764 	un = SD_GET_UN(bp);
11765 	ASSERT(un != NULL);
11766 	ASSERT(mutex_owned(SD_MUTEX(un)));
11767 	ASSERT(bp->b_resid == 0);
11768 
11769 	SD_TRACE(SD_LOG_IO_CORE, un,
11770 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
11771 
11772 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11773 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
11774 		/*
11775 		 * Already have a scsi_pkt -- just need DMA resources.
11776 		 * We must recompute the CDB in case the mapping returns
11777 		 * a nonzero pkt_resid.
11778 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
11779 		 * that is being retried, the unmap/remap of the DMA resouces
11780 		 * will result in the entire transfer starting over again
11781 		 * from the very first block.
11782 		 */
11783 		ASSERT(xp->xb_pktp != NULL);
11784 		pktp = xp->xb_pktp;
11785 	} else {
11786 		pktp = NULL;
11787 	}
11788 #endif /* __i386 || __amd64 */
11789 
11790 	startblock = xp->xb_blkno;	/* Absolute block num. */
11791 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
11792 
11793 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11794 
11795 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
11796 
11797 #else
11798 
11799 	cmd_flags = un->un_pkt_flags | xp->xb_pkt_flags;
11800 
11801 #endif
11802 
11803 	/*
11804 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
11805 	 * call scsi_init_pkt, and build the CDB.
11806 	 */
11807 	rval = sd_setup_rw_pkt(un, &pktp, bp,
11808 	    cmd_flags, sdrunout, (caddr_t)un,
11809 	    startblock, blockcount);
11810 
11811 	if (rval == 0) {
11812 		/*
11813 		 * Success.
11814 		 *
11815 		 * If partial DMA is being used and required for this transfer.
11816 		 * set it up here.
11817 		 */
11818 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
11819 		    (pktp->pkt_resid != 0)) {
11820 
11821 			/*
11822 			 * Save the CDB length and pkt_resid for the
11823 			 * next xfer
11824 			 */
11825 			xp->xb_dma_resid = pktp->pkt_resid;
11826 
11827 			/* rezero resid */
11828 			pktp->pkt_resid = 0;
11829 
11830 		} else {
11831 			xp->xb_dma_resid = 0;
11832 		}
11833 
11834 		pktp->pkt_flags = un->un_tagflags;
11835 		pktp->pkt_time  = un->un_cmd_timeout;
11836 		pktp->pkt_comp  = sdintr;
11837 
11838 		pktp->pkt_private = bp;
11839 		*pktpp = pktp;
11840 
11841 		SD_TRACE(SD_LOG_IO_CORE, un,
11842 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
11843 
11844 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11845 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
11846 #endif
11847 
11848 		return (SD_PKT_ALLOC_SUCCESS);
11849 
11850 	}
11851 
11852 	/*
11853 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
11854 	 * from sd_setup_rw_pkt.
11855 	 */
11856 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
11857 
11858 	if (rval == SD_PKT_ALLOC_FAILURE) {
11859 		*pktpp = NULL;
11860 		/*
11861 		 * Set the driver state to RWAIT to indicate the driver
11862 		 * is waiting on resource allocations. The driver will not
11863 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
11864 		 */
11865 		New_state(un, SD_STATE_RWAIT);
11866 
11867 		SD_ERROR(SD_LOG_IO_CORE, un,
11868 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
11869 
11870 		if ((bp->b_flags & B_ERROR) != 0) {
11871 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
11872 		}
11873 		return (SD_PKT_ALLOC_FAILURE);
11874 	} else {
11875 		/*
11876 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11877 		 *
11878 		 * This should never happen.  Maybe someone messed with the
11879 		 * kernel's minphys?
11880 		 */
11881 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
11882 		    "Request rejected: too large for CDB: "
11883 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
11884 		SD_ERROR(SD_LOG_IO_CORE, un,
11885 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
11886 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
11887 
11888 	}
11889 }
11890 
11891 
11892 /*
11893  *    Function: sd_destroypkt_for_buf
11894  *
11895  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
11896  *
11897  *     Context: Kernel thread or interrupt context
11898  */
11899 
11900 static void
11901 sd_destroypkt_for_buf(struct buf *bp)
11902 {
11903 	ASSERT(bp != NULL);
11904 	ASSERT(SD_GET_UN(bp) != NULL);
11905 
11906 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11907 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
11908 
11909 	ASSERT(SD_GET_PKTP(bp) != NULL);
11910 	scsi_destroy_pkt(SD_GET_PKTP(bp));
11911 
11912 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11913 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
11914 }
11915 
11916 /*
11917  *    Function: sd_setup_rw_pkt
11918  *
11919  * Description: Determines appropriate CDB group for the requested LBA
11920  *		and transfer length, calls scsi_init_pkt, and builds
11921  *		the CDB.  Do not use for partial DMA transfers except
11922  *		for the initial transfer since the CDB size must
11923  *		remain constant.
11924  *
11925  *     Context: Kernel thread and may be called from software interrupt
11926  *		context as part of a sdrunout callback. This function may not
11927  *		block or call routines that block
11928  */
11929 
11930 
11931 int
11932 sd_setup_rw_pkt(struct sd_lun *un,
11933     struct scsi_pkt **pktpp, struct buf *bp, int flags,
11934     int (*callback)(caddr_t), caddr_t callback_arg,
11935     diskaddr_t lba, uint32_t blockcount)
11936 {
11937 	struct scsi_pkt *return_pktp;
11938 	union scsi_cdb *cdbp;
11939 	struct sd_cdbinfo *cp = NULL;
11940 	int i;
11941 
11942 	/*
11943 	 * See which size CDB to use, based upon the request.
11944 	 */
11945 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
11946 
11947 		/*
11948 		 * Check lba and block count against sd_cdbtab limits.
11949 		 * In the partial DMA case, we have to use the same size
11950 		 * CDB for all the transfers.  Check lba + blockcount
11951 		 * against the max LBA so we know that segment of the
11952 		 * transfer can use the CDB we select.
11953 		 */
11954 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
11955 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
11956 
11957 			/*
11958 			 * The command will fit into the CDB type
11959 			 * specified by sd_cdbtab[i].
11960 			 */
11961 			cp = sd_cdbtab + i;
11962 
11963 			/*
11964 			 * Call scsi_init_pkt so we can fill in the
11965 			 * CDB.
11966 			 */
11967 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
11968 			    bp, cp->sc_grpcode, un->un_status_len, 0,
11969 			    flags, callback, callback_arg);
11970 
11971 			if (return_pktp != NULL) {
11972 
11973 				/*
11974 				 * Return new value of pkt
11975 				 */
11976 				*pktpp = return_pktp;
11977 
11978 				/*
11979 				 * To be safe, zero the CDB insuring there is
11980 				 * no leftover data from a previous command.
11981 				 */
11982 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
11983 
11984 				/*
11985 				 * Handle partial DMA mapping
11986 				 */
11987 				if (return_pktp->pkt_resid != 0) {
11988 
11989 					/*
11990 					 * Not going to xfer as many blocks as
11991 					 * originally expected
11992 					 */
11993 					blockcount -=
11994 					    SD_BYTES2TGTBLOCKS(un,
11995 					    return_pktp->pkt_resid);
11996 				}
11997 
11998 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
11999 
12000 				/*
12001 				 * Set command byte based on the CDB
12002 				 * type we matched.
12003 				 */
12004 				cdbp->scc_cmd = cp->sc_grpmask |
12005 				    ((bp->b_flags & B_READ) ?
12006 				    SCMD_READ : SCMD_WRITE);
12007 
12008 				SD_FILL_SCSI1_LUN(un, return_pktp);
12009 
12010 				/*
12011 				 * Fill in LBA and length
12012 				 */
12013 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
12014 				    (cp->sc_grpcode == CDB_GROUP4) ||
12015 				    (cp->sc_grpcode == CDB_GROUP0) ||
12016 				    (cp->sc_grpcode == CDB_GROUP5));
12017 
12018 				if (cp->sc_grpcode == CDB_GROUP1) {
12019 					FORMG1ADDR(cdbp, lba);
12020 					FORMG1COUNT(cdbp, blockcount);
12021 					return (0);
12022 				} else if (cp->sc_grpcode == CDB_GROUP4) {
12023 					FORMG4LONGADDR(cdbp, lba);
12024 					FORMG4COUNT(cdbp, blockcount);
12025 					return (0);
12026 				} else if (cp->sc_grpcode == CDB_GROUP0) {
12027 					FORMG0ADDR(cdbp, lba);
12028 					FORMG0COUNT(cdbp, blockcount);
12029 					return (0);
12030 				} else if (cp->sc_grpcode == CDB_GROUP5) {
12031 					FORMG5ADDR(cdbp, lba);
12032 					FORMG5COUNT(cdbp, blockcount);
12033 					return (0);
12034 				}
12035 
12036 				/*
12037 				 * It should be impossible to not match one
12038 				 * of the CDB types above, so we should never
12039 				 * reach this point.  Set the CDB command byte
12040 				 * to test-unit-ready to avoid writing
12041 				 * to somewhere we don't intend.
12042 				 */
12043 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
12044 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12045 			} else {
12046 				/*
12047 				 * Couldn't get scsi_pkt
12048 				 */
12049 				return (SD_PKT_ALLOC_FAILURE);
12050 			}
12051 		}
12052 	}
12053 
12054 	/*
12055 	 * None of the available CDB types were suitable.  This really
12056 	 * should never happen:  on a 64 bit system we support
12057 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
12058 	 * and on a 32 bit system we will refuse to bind to a device
12059 	 * larger than 2TB so addresses will never be larger than 32 bits.
12060 	 */
12061 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12062 }
12063 
12064 /*
12065  *    Function: sd_setup_next_rw_pkt
12066  *
12067  * Description: Setup packet for partial DMA transfers, except for the
12068  * 		initial transfer.  sd_setup_rw_pkt should be used for
12069  *		the initial transfer.
12070  *
12071  *     Context: Kernel thread and may be called from interrupt context.
12072  */
12073 
12074 int
12075 sd_setup_next_rw_pkt(struct sd_lun *un,
12076     struct scsi_pkt *pktp, struct buf *bp,
12077     diskaddr_t lba, uint32_t blockcount)
12078 {
12079 	uchar_t com;
12080 	union scsi_cdb *cdbp;
12081 	uchar_t cdb_group_id;
12082 
12083 	ASSERT(pktp != NULL);
12084 	ASSERT(pktp->pkt_cdbp != NULL);
12085 
12086 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
12087 	com = cdbp->scc_cmd;
12088 	cdb_group_id = CDB_GROUPID(com);
12089 
12090 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
12091 	    (cdb_group_id == CDB_GROUPID_1) ||
12092 	    (cdb_group_id == CDB_GROUPID_4) ||
12093 	    (cdb_group_id == CDB_GROUPID_5));
12094 
12095 	/*
12096 	 * Move pkt to the next portion of the xfer.
12097 	 * func is NULL_FUNC so we do not have to release
12098 	 * the disk mutex here.
12099 	 */
12100 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
12101 	    NULL_FUNC, NULL) == pktp) {
12102 		/* Success.  Handle partial DMA */
12103 		if (pktp->pkt_resid != 0) {
12104 			blockcount -=
12105 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
12106 		}
12107 
12108 		cdbp->scc_cmd = com;
12109 		SD_FILL_SCSI1_LUN(un, pktp);
12110 		if (cdb_group_id == CDB_GROUPID_1) {
12111 			FORMG1ADDR(cdbp, lba);
12112 			FORMG1COUNT(cdbp, blockcount);
12113 			return (0);
12114 		} else if (cdb_group_id == CDB_GROUPID_4) {
12115 			FORMG4LONGADDR(cdbp, lba);
12116 			FORMG4COUNT(cdbp, blockcount);
12117 			return (0);
12118 		} else if (cdb_group_id == CDB_GROUPID_0) {
12119 			FORMG0ADDR(cdbp, lba);
12120 			FORMG0COUNT(cdbp, blockcount);
12121 			return (0);
12122 		} else if (cdb_group_id == CDB_GROUPID_5) {
12123 			FORMG5ADDR(cdbp, lba);
12124 			FORMG5COUNT(cdbp, blockcount);
12125 			return (0);
12126 		}
12127 
12128 		/* Unreachable */
12129 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12130 	}
12131 
12132 	/*
12133 	 * Error setting up next portion of cmd transfer.
12134 	 * Something is definitely very wrong and this
12135 	 * should not happen.
12136 	 */
12137 	return (SD_PKT_ALLOC_FAILURE);
12138 }
12139 
12140 /*
12141  *    Function: sd_initpkt_for_uscsi
12142  *
12143  * Description: Allocate and initialize for transport a scsi_pkt struct,
12144  *		based upon the info specified in the given uscsi_cmd struct.
12145  *
12146  * Return Code: SD_PKT_ALLOC_SUCCESS
12147  *		SD_PKT_ALLOC_FAILURE
12148  *		SD_PKT_ALLOC_FAILURE_NO_DMA
12149  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
12150  *
12151  *     Context: Kernel thread and may be called from software interrupt context
12152  *		as part of a sdrunout callback. This function may not block or
12153  *		call routines that block
12154  */
12155 
12156 static int
12157 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
12158 {
12159 	struct uscsi_cmd *uscmd;
12160 	struct sd_xbuf	*xp;
12161 	struct scsi_pkt	*pktp;
12162 	struct sd_lun	*un;
12163 	uint32_t	flags = 0;
12164 
12165 	ASSERT(bp != NULL);
12166 	ASSERT(pktpp != NULL);
12167 	xp = SD_GET_XBUF(bp);
12168 	ASSERT(xp != NULL);
12169 	un = SD_GET_UN(bp);
12170 	ASSERT(un != NULL);
12171 	ASSERT(mutex_owned(SD_MUTEX(un)));
12172 
12173 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12174 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12175 	ASSERT(uscmd != NULL);
12176 
12177 	SD_TRACE(SD_LOG_IO_CORE, un,
12178 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
12179 
12180 	/*
12181 	 * Allocate the scsi_pkt for the command.
12182 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
12183 	 *	 during scsi_init_pkt time and will continue to use the
12184 	 *	 same path as long as the same scsi_pkt is used without
12185 	 *	 intervening scsi_dma_free(). Since uscsi command does
12186 	 *	 not call scsi_dmafree() before retry failed command, it
12187 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
12188 	 *	 set such that scsi_vhci can use other available path for
12189 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
12190 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
12191 	 */
12192 	pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
12193 	    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
12194 	    sizeof (struct scsi_arq_status), 0,
12195 	    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
12196 	    sdrunout, (caddr_t)un);
12197 
12198 	if (pktp == NULL) {
12199 		*pktpp = NULL;
12200 		/*
12201 		 * Set the driver state to RWAIT to indicate the driver
12202 		 * is waiting on resource allocations. The driver will not
12203 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
12204 		 */
12205 		New_state(un, SD_STATE_RWAIT);
12206 
12207 		SD_ERROR(SD_LOG_IO_CORE, un,
12208 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
12209 
12210 		if ((bp->b_flags & B_ERROR) != 0) {
12211 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
12212 		}
12213 		return (SD_PKT_ALLOC_FAILURE);
12214 	}
12215 
12216 	/*
12217 	 * We do not do DMA breakup for USCSI commands, so return failure
12218 	 * here if all the needed DMA resources were not allocated.
12219 	 */
12220 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
12221 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
12222 		scsi_destroy_pkt(pktp);
12223 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
12224 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
12225 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
12226 	}
12227 
12228 	/* Init the cdb from the given uscsi struct */
12229 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
12230 	    uscmd->uscsi_cdb[0], 0, 0, 0);
12231 
12232 	SD_FILL_SCSI1_LUN(un, pktp);
12233 
12234 	/*
12235 	 * Set up the optional USCSI flags. See the uscsi (7I) man page
12236 	 * for listing of the supported flags.
12237 	 */
12238 
12239 	if (uscmd->uscsi_flags & USCSI_SILENT) {
12240 		flags |= FLAG_SILENT;
12241 	}
12242 
12243 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
12244 		flags |= FLAG_DIAGNOSE;
12245 	}
12246 
12247 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
12248 		flags |= FLAG_ISOLATE;
12249 	}
12250 
12251 	if (un->un_f_is_fibre == FALSE) {
12252 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
12253 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
12254 		}
12255 	}
12256 
12257 	/*
12258 	 * Set the pkt flags here so we save time later.
12259 	 * Note: These flags are NOT in the uscsi man page!!!
12260 	 */
12261 	if (uscmd->uscsi_flags & USCSI_HEAD) {
12262 		flags |= FLAG_HEAD;
12263 	}
12264 
12265 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
12266 		flags |= FLAG_NOINTR;
12267 	}
12268 
12269 	/*
12270 	 * For tagged queueing, things get a bit complicated.
12271 	 * Check first for head of queue and last for ordered queue.
12272 	 * If neither head nor order, use the default driver tag flags.
12273 	 */
12274 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
12275 		if (uscmd->uscsi_flags & USCSI_HTAG) {
12276 			flags |= FLAG_HTAG;
12277 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
12278 			flags |= FLAG_OTAG;
12279 		} else {
12280 			flags |= un->un_tagflags & FLAG_TAGMASK;
12281 		}
12282 	}
12283 
12284 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
12285 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
12286 	}
12287 
12288 	pktp->pkt_flags = flags;
12289 
12290 	/* Copy the caller's CDB into the pkt... */
12291 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
12292 
12293 	if (uscmd->uscsi_timeout == 0) {
12294 		pktp->pkt_time = un->un_uscsi_timeout;
12295 	} else {
12296 		pktp->pkt_time = uscmd->uscsi_timeout;
12297 	}
12298 
12299 	/* need it later to identify USCSI request in sdintr */
12300 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
12301 
12302 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
12303 
12304 	pktp->pkt_private = bp;
12305 	pktp->pkt_comp = sdintr;
12306 	*pktpp = pktp;
12307 
12308 	SD_TRACE(SD_LOG_IO_CORE, un,
12309 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
12310 
12311 	return (SD_PKT_ALLOC_SUCCESS);
12312 }
12313 
12314 
12315 /*
12316  *    Function: sd_destroypkt_for_uscsi
12317  *
12318  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
12319  *		IOs.. Also saves relevant info into the associated uscsi_cmd
12320  *		struct.
12321  *
12322  *     Context: May be called under interrupt context
12323  */
12324 
12325 static void
12326 sd_destroypkt_for_uscsi(struct buf *bp)
12327 {
12328 	struct uscsi_cmd *uscmd;
12329 	struct sd_xbuf	*xp;
12330 	struct scsi_pkt	*pktp;
12331 	struct sd_lun	*un;
12332 
12333 	ASSERT(bp != NULL);
12334 	xp = SD_GET_XBUF(bp);
12335 	ASSERT(xp != NULL);
12336 	un = SD_GET_UN(bp);
12337 	ASSERT(un != NULL);
12338 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12339 	pktp = SD_GET_PKTP(bp);
12340 	ASSERT(pktp != NULL);
12341 
12342 	SD_TRACE(SD_LOG_IO_CORE, un,
12343 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
12344 
12345 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12346 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12347 	ASSERT(uscmd != NULL);
12348 
12349 	/* Save the status and the residual into the uscsi_cmd struct */
12350 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
12351 	uscmd->uscsi_resid  = bp->b_resid;
12352 
12353 	/*
12354 	 * If enabled, copy any saved sense data into the area specified
12355 	 * by the uscsi command.
12356 	 */
12357 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
12358 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
12359 		/*
12360 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
12361 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
12362 		 */
12363 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
12364 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
12365 		bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf, SENSE_LENGTH);
12366 	}
12367 
12368 	/* We are done with the scsi_pkt; free it now */
12369 	ASSERT(SD_GET_PKTP(bp) != NULL);
12370 	scsi_destroy_pkt(SD_GET_PKTP(bp));
12371 
12372 	SD_TRACE(SD_LOG_IO_CORE, un,
12373 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
12374 }
12375 
12376 
12377 /*
12378  *    Function: sd_bioclone_alloc
12379  *
12380  * Description: Allocate a buf(9S) and init it as per the given buf
12381  *		and the various arguments.  The associated sd_xbuf
12382  *		struct is (nearly) duplicated.  The struct buf *bp
12383  *		argument is saved in new_xp->xb_private.
12384  *
12385  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12386  *		datalen - size of data area for the shadow bp
12387  *		blkno - starting LBA
12388  *		func - function pointer for b_iodone in the shadow buf. (May
12389  *			be NULL if none.)
12390  *
12391  * Return Code: Pointer to allocates buf(9S) struct
12392  *
12393  *     Context: Can sleep.
12394  */
12395 
12396 static struct buf *
12397 sd_bioclone_alloc(struct buf *bp, size_t datalen,
12398 	daddr_t blkno, int (*func)(struct buf *))
12399 {
12400 	struct	sd_lun	*un;
12401 	struct	sd_xbuf	*xp;
12402 	struct	sd_xbuf	*new_xp;
12403 	struct	buf	*new_bp;
12404 
12405 	ASSERT(bp != NULL);
12406 	xp = SD_GET_XBUF(bp);
12407 	ASSERT(xp != NULL);
12408 	un = SD_GET_UN(bp);
12409 	ASSERT(un != NULL);
12410 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12411 
12412 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
12413 	    NULL, KM_SLEEP);
12414 
12415 	new_bp->b_lblkno	= blkno;
12416 
12417 	/*
12418 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12419 	 * original xbuf into it.
12420 	 */
12421 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12422 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12423 
12424 	/*
12425 	 * The given bp is automatically saved in the xb_private member
12426 	 * of the new xbuf.  Callers are allowed to depend on this.
12427 	 */
12428 	new_xp->xb_private = bp;
12429 
12430 	new_bp->b_private  = new_xp;
12431 
12432 	return (new_bp);
12433 }
12434 
12435 /*
12436  *    Function: sd_shadow_buf_alloc
12437  *
12438  * Description: Allocate a buf(9S) and init it as per the given buf
12439  *		and the various arguments.  The associated sd_xbuf
12440  *		struct is (nearly) duplicated.  The struct buf *bp
12441  *		argument is saved in new_xp->xb_private.
12442  *
12443  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12444  *		datalen - size of data area for the shadow bp
12445  *		bflags - B_READ or B_WRITE (pseudo flag)
12446  *		blkno - starting LBA
12447  *		func - function pointer for b_iodone in the shadow buf. (May
12448  *			be NULL if none.)
12449  *
12450  * Return Code: Pointer to allocates buf(9S) struct
12451  *
12452  *     Context: Can sleep.
12453  */
12454 
12455 static struct buf *
12456 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
12457 	daddr_t blkno, int (*func)(struct buf *))
12458 {
12459 	struct	sd_lun	*un;
12460 	struct	sd_xbuf	*xp;
12461 	struct	sd_xbuf	*new_xp;
12462 	struct	buf	*new_bp;
12463 
12464 	ASSERT(bp != NULL);
12465 	xp = SD_GET_XBUF(bp);
12466 	ASSERT(xp != NULL);
12467 	un = SD_GET_UN(bp);
12468 	ASSERT(un != NULL);
12469 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12470 
12471 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
12472 		bp_mapin(bp);
12473 	}
12474 
12475 	bflags &= (B_READ | B_WRITE);
12476 #if defined(__i386) || defined(__amd64)
12477 	new_bp = getrbuf(KM_SLEEP);
12478 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
12479 	new_bp->b_bcount = datalen;
12480 	new_bp->b_flags = bflags |
12481 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
12482 #else
12483 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
12484 	    datalen, bflags, SLEEP_FUNC, NULL);
12485 #endif
12486 	new_bp->av_forw	= NULL;
12487 	new_bp->av_back	= NULL;
12488 	new_bp->b_dev	= bp->b_dev;
12489 	new_bp->b_blkno	= blkno;
12490 	new_bp->b_iodone = func;
12491 	new_bp->b_edev	= bp->b_edev;
12492 	new_bp->b_resid	= 0;
12493 
12494 	/* We need to preserve the B_FAILFAST flag */
12495 	if (bp->b_flags & B_FAILFAST) {
12496 		new_bp->b_flags |= B_FAILFAST;
12497 	}
12498 
12499 	/*
12500 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12501 	 * original xbuf into it.
12502 	 */
12503 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12504 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12505 
12506 	/* Need later to copy data between the shadow buf & original buf! */
12507 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
12508 
12509 	/*
12510 	 * The given bp is automatically saved in the xb_private member
12511 	 * of the new xbuf.  Callers are allowed to depend on this.
12512 	 */
12513 	new_xp->xb_private = bp;
12514 
12515 	new_bp->b_private  = new_xp;
12516 
12517 	return (new_bp);
12518 }
12519 
12520 /*
12521  *    Function: sd_bioclone_free
12522  *
12523  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
12524  *		in the larger than partition operation.
12525  *
12526  *     Context: May be called under interrupt context
12527  */
12528 
12529 static void
12530 sd_bioclone_free(struct buf *bp)
12531 {
12532 	struct sd_xbuf	*xp;
12533 
12534 	ASSERT(bp != NULL);
12535 	xp = SD_GET_XBUF(bp);
12536 	ASSERT(xp != NULL);
12537 
12538 	/*
12539 	 * Call bp_mapout() before freeing the buf,  in case a lower
12540 	 * layer or HBA  had done a bp_mapin().  we must do this here
12541 	 * as we are the "originator" of the shadow buf.
12542 	 */
12543 	bp_mapout(bp);
12544 
12545 	/*
12546 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12547 	 * never gets confused by a stale value in this field. (Just a little
12548 	 * extra defensiveness here.)
12549 	 */
12550 	bp->b_iodone = NULL;
12551 
12552 	freerbuf(bp);
12553 
12554 	kmem_free(xp, sizeof (struct sd_xbuf));
12555 }
12556 
12557 /*
12558  *    Function: sd_shadow_buf_free
12559  *
12560  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
12561  *
12562  *     Context: May be called under interrupt context
12563  */
12564 
12565 static void
12566 sd_shadow_buf_free(struct buf *bp)
12567 {
12568 	struct sd_xbuf	*xp;
12569 
12570 	ASSERT(bp != NULL);
12571 	xp = SD_GET_XBUF(bp);
12572 	ASSERT(xp != NULL);
12573 
12574 #if defined(__sparc)
12575 	/*
12576 	 * Call bp_mapout() before freeing the buf,  in case a lower
12577 	 * layer or HBA  had done a bp_mapin().  we must do this here
12578 	 * as we are the "originator" of the shadow buf.
12579 	 */
12580 	bp_mapout(bp);
12581 #endif
12582 
12583 	/*
12584 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12585 	 * never gets confused by a stale value in this field. (Just a little
12586 	 * extra defensiveness here.)
12587 	 */
12588 	bp->b_iodone = NULL;
12589 
12590 #if defined(__i386) || defined(__amd64)
12591 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
12592 	freerbuf(bp);
12593 #else
12594 	scsi_free_consistent_buf(bp);
12595 #endif
12596 
12597 	kmem_free(xp, sizeof (struct sd_xbuf));
12598 }
12599 
12600 
12601 /*
12602  *    Function: sd_print_transport_rejected_message
12603  *
12604  * Description: This implements the ludicrously complex rules for printing
12605  *		a "transport rejected" message.  This is to address the
12606  *		specific problem of having a flood of this error message
12607  *		produced when a failover occurs.
12608  *
12609  *     Context: Any.
12610  */
12611 
12612 static void
12613 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
12614 	int code)
12615 {
12616 	ASSERT(un != NULL);
12617 	ASSERT(mutex_owned(SD_MUTEX(un)));
12618 	ASSERT(xp != NULL);
12619 
12620 	/*
12621 	 * Print the "transport rejected" message under the following
12622 	 * conditions:
12623 	 *
12624 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
12625 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
12626 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
12627 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
12628 	 *   scsi_transport(9F) (which indicates that the target might have
12629 	 *   gone off-line).  This uses the un->un_tran_fatal_count
12630 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
12631 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
12632 	 *   from scsi_transport().
12633 	 *
12634 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
12635 	 * the preceeding cases in order for the message to be printed.
12636 	 */
12637 	if ((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) {
12638 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
12639 		    (code != TRAN_FATAL_ERROR) ||
12640 		    (un->un_tran_fatal_count == 1)) {
12641 			switch (code) {
12642 			case TRAN_BADPKT:
12643 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12644 				    "transport rejected bad packet\n");
12645 				break;
12646 			case TRAN_FATAL_ERROR:
12647 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12648 				    "transport rejected fatal error\n");
12649 				break;
12650 			default:
12651 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12652 				    "transport rejected (%d)\n", code);
12653 				break;
12654 			}
12655 		}
12656 	}
12657 }
12658 
12659 
12660 /*
12661  *    Function: sd_add_buf_to_waitq
12662  *
12663  * Description: Add the given buf(9S) struct to the wait queue for the
12664  *		instance.  If sorting is enabled, then the buf is added
12665  *		to the queue via an elevator sort algorithm (a la
12666  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
12667  *		If sorting is not enabled, then the buf is just added
12668  *		to the end of the wait queue.
12669  *
12670  * Return Code: void
12671  *
12672  *     Context: Does not sleep/block, therefore technically can be called
12673  *		from any context.  However if sorting is enabled then the
12674  *		execution time is indeterminate, and may take long if
12675  *		the wait queue grows large.
12676  */
12677 
12678 static void
12679 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
12680 {
12681 	struct buf *ap;
12682 
12683 	ASSERT(bp != NULL);
12684 	ASSERT(un != NULL);
12685 	ASSERT(mutex_owned(SD_MUTEX(un)));
12686 
12687 	/* If the queue is empty, add the buf as the only entry & return. */
12688 	if (un->un_waitq_headp == NULL) {
12689 		ASSERT(un->un_waitq_tailp == NULL);
12690 		un->un_waitq_headp = un->un_waitq_tailp = bp;
12691 		bp->av_forw = NULL;
12692 		return;
12693 	}
12694 
12695 	ASSERT(un->un_waitq_tailp != NULL);
12696 
12697 	/*
12698 	 * If sorting is disabled, just add the buf to the tail end of
12699 	 * the wait queue and return.
12700 	 */
12701 	if (un->un_f_disksort_disabled) {
12702 		un->un_waitq_tailp->av_forw = bp;
12703 		un->un_waitq_tailp = bp;
12704 		bp->av_forw = NULL;
12705 		return;
12706 	}
12707 
12708 	/*
12709 	 * Sort thru the list of requests currently on the wait queue
12710 	 * and add the new buf request at the appropriate position.
12711 	 *
12712 	 * The un->un_waitq_headp is an activity chain pointer on which
12713 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
12714 	 * first queue holds those requests which are positioned after
12715 	 * the current SD_GET_BLKNO() (in the first request); the second holds
12716 	 * requests which came in after their SD_GET_BLKNO() number was passed.
12717 	 * Thus we implement a one way scan, retracting after reaching
12718 	 * the end of the drive to the first request on the second
12719 	 * queue, at which time it becomes the first queue.
12720 	 * A one-way scan is natural because of the way UNIX read-ahead
12721 	 * blocks are allocated.
12722 	 *
12723 	 * If we lie after the first request, then we must locate the
12724 	 * second request list and add ourselves to it.
12725 	 */
12726 	ap = un->un_waitq_headp;
12727 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
12728 		while (ap->av_forw != NULL) {
12729 			/*
12730 			 * Look for an "inversion" in the (normally
12731 			 * ascending) block numbers. This indicates
12732 			 * the start of the second request list.
12733 			 */
12734 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
12735 				/*
12736 				 * Search the second request list for the
12737 				 * first request at a larger block number.
12738 				 * We go before that; however if there is
12739 				 * no such request, we go at the end.
12740 				 */
12741 				do {
12742 					if (SD_GET_BLKNO(bp) <
12743 					    SD_GET_BLKNO(ap->av_forw)) {
12744 						goto insert;
12745 					}
12746 					ap = ap->av_forw;
12747 				} while (ap->av_forw != NULL);
12748 				goto insert;		/* after last */
12749 			}
12750 			ap = ap->av_forw;
12751 		}
12752 
12753 		/*
12754 		 * No inversions... we will go after the last, and
12755 		 * be the first request in the second request list.
12756 		 */
12757 		goto insert;
12758 	}
12759 
12760 	/*
12761 	 * Request is at/after the current request...
12762 	 * sort in the first request list.
12763 	 */
12764 	while (ap->av_forw != NULL) {
12765 		/*
12766 		 * We want to go after the current request (1) if
12767 		 * there is an inversion after it (i.e. it is the end
12768 		 * of the first request list), or (2) if the next
12769 		 * request is a larger block no. than our request.
12770 		 */
12771 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
12772 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
12773 			goto insert;
12774 		}
12775 		ap = ap->av_forw;
12776 	}
12777 
12778 	/*
12779 	 * Neither a second list nor a larger request, therefore
12780 	 * we go at the end of the first list (which is the same
12781 	 * as the end of the whole schebang).
12782 	 */
12783 insert:
12784 	bp->av_forw = ap->av_forw;
12785 	ap->av_forw = bp;
12786 
12787 	/*
12788 	 * If we inserted onto the tail end of the waitq, make sure the
12789 	 * tail pointer is updated.
12790 	 */
12791 	if (ap == un->un_waitq_tailp) {
12792 		un->un_waitq_tailp = bp;
12793 	}
12794 }
12795 
12796 
12797 /*
12798  *    Function: sd_start_cmds
12799  *
12800  * Description: Remove and transport cmds from the driver queues.
12801  *
12802  *   Arguments: un - pointer to the unit (soft state) struct for the target.
12803  *
12804  *		immed_bp - ptr to a buf to be transported immediately. Only
12805  *		the immed_bp is transported; bufs on the waitq are not
12806  *		processed and the un_retry_bp is not checked.  If immed_bp is
12807  *		NULL, then normal queue processing is performed.
12808  *
12809  *     Context: May be called from kernel thread context, interrupt context,
12810  *		or runout callback context. This function may not block or
12811  *		call routines that block.
12812  */
12813 
12814 static void
12815 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
12816 {
12817 	struct	sd_xbuf	*xp;
12818 	struct	buf	*bp;
12819 	void	(*statp)(kstat_io_t *);
12820 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12821 	void	(*saved_statp)(kstat_io_t *);
12822 #endif
12823 	int	rval;
12824 
12825 	ASSERT(un != NULL);
12826 	ASSERT(mutex_owned(SD_MUTEX(un)));
12827 	ASSERT(un->un_ncmds_in_transport >= 0);
12828 	ASSERT(un->un_throttle >= 0);
12829 
12830 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
12831 
12832 	do {
12833 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12834 		saved_statp = NULL;
12835 #endif
12836 
12837 		/*
12838 		 * If we are syncing or dumping, fail the command to
12839 		 * avoid recursively calling back into scsi_transport().
12840 		 * The dump I/O itself uses a separate code path so this
12841 		 * only prevents non-dump I/O from being sent while dumping.
12842 		 * File system sync takes place before dumping begins.
12843 		 * During panic, filesystem I/O is allowed provided
12844 		 * un_in_callback is <= 1.  This is to prevent recursion
12845 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
12846 		 * sd_start_cmds and so on.  See panic.c for more information
12847 		 * about the states the system can be in during panic.
12848 		 */
12849 		if ((un->un_state == SD_STATE_DUMPING) ||
12850 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
12851 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12852 			    "sd_start_cmds: panicking\n");
12853 			goto exit;
12854 		}
12855 
12856 		if ((bp = immed_bp) != NULL) {
12857 			/*
12858 			 * We have a bp that must be transported immediately.
12859 			 * It's OK to transport the immed_bp here without doing
12860 			 * the throttle limit check because the immed_bp is
12861 			 * always used in a retry/recovery case. This means
12862 			 * that we know we are not at the throttle limit by
12863 			 * virtue of the fact that to get here we must have
12864 			 * already gotten a command back via sdintr(). This also
12865 			 * relies on (1) the command on un_retry_bp preventing
12866 			 * further commands from the waitq from being issued;
12867 			 * and (2) the code in sd_retry_command checking the
12868 			 * throttle limit before issuing a delayed or immediate
12869 			 * retry. This holds even if the throttle limit is
12870 			 * currently ratcheted down from its maximum value.
12871 			 */
12872 			statp = kstat_runq_enter;
12873 			if (bp == un->un_retry_bp) {
12874 				ASSERT((un->un_retry_statp == NULL) ||
12875 				    (un->un_retry_statp == kstat_waitq_enter) ||
12876 				    (un->un_retry_statp ==
12877 				    kstat_runq_back_to_waitq));
12878 				/*
12879 				 * If the waitq kstat was incremented when
12880 				 * sd_set_retry_bp() queued this bp for a retry,
12881 				 * then we must set up statp so that the waitq
12882 				 * count will get decremented correctly below.
12883 				 * Also we must clear un->un_retry_statp to
12884 				 * ensure that we do not act on a stale value
12885 				 * in this field.
12886 				 */
12887 				if ((un->un_retry_statp == kstat_waitq_enter) ||
12888 				    (un->un_retry_statp ==
12889 				    kstat_runq_back_to_waitq)) {
12890 					statp = kstat_waitq_to_runq;
12891 				}
12892 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12893 				saved_statp = un->un_retry_statp;
12894 #endif
12895 				un->un_retry_statp = NULL;
12896 
12897 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
12898 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
12899 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
12900 				    un, un->un_retry_bp, un->un_throttle,
12901 				    un->un_ncmds_in_transport);
12902 			} else {
12903 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
12904 				    "processing priority bp:0x%p\n", bp);
12905 			}
12906 
12907 		} else if ((bp = un->un_waitq_headp) != NULL) {
12908 			/*
12909 			 * A command on the waitq is ready to go, but do not
12910 			 * send it if:
12911 			 *
12912 			 * (1) the throttle limit has been reached, or
12913 			 * (2) a retry is pending, or
12914 			 * (3) a START_STOP_UNIT callback pending, or
12915 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
12916 			 *	command is pending.
12917 			 *
12918 			 * For all of these conditions, IO processing will
12919 			 * restart after the condition is cleared.
12920 			 */
12921 			if (un->un_ncmds_in_transport >= un->un_throttle) {
12922 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12923 				    "sd_start_cmds: exiting, "
12924 				    "throttle limit reached!\n");
12925 				goto exit;
12926 			}
12927 			if (un->un_retry_bp != NULL) {
12928 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12929 				    "sd_start_cmds: exiting, retry pending!\n");
12930 				goto exit;
12931 			}
12932 			if (un->un_startstop_timeid != NULL) {
12933 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12934 				    "sd_start_cmds: exiting, "
12935 				    "START_STOP pending!\n");
12936 				goto exit;
12937 			}
12938 			if (un->un_direct_priority_timeid != NULL) {
12939 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12940 				    "sd_start_cmds: exiting, "
12941 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
12942 				goto exit;
12943 			}
12944 
12945 			/* Dequeue the command */
12946 			un->un_waitq_headp = bp->av_forw;
12947 			if (un->un_waitq_headp == NULL) {
12948 				un->un_waitq_tailp = NULL;
12949 			}
12950 			bp->av_forw = NULL;
12951 			statp = kstat_waitq_to_runq;
12952 			SD_TRACE(SD_LOG_IO_CORE, un,
12953 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
12954 
12955 		} else {
12956 			/* No work to do so bail out now */
12957 			SD_TRACE(SD_LOG_IO_CORE, un,
12958 			    "sd_start_cmds: no more work, exiting!\n");
12959 			goto exit;
12960 		}
12961 
12962 		/*
12963 		 * Reset the state to normal. This is the mechanism by which
12964 		 * the state transitions from either SD_STATE_RWAIT or
12965 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
12966 		 * If state is SD_STATE_PM_CHANGING then this command is
12967 		 * part of the device power control and the state must
12968 		 * not be put back to normal. Doing so would would
12969 		 * allow new commands to proceed when they shouldn't,
12970 		 * the device may be going off.
12971 		 */
12972 		if ((un->un_state != SD_STATE_SUSPENDED) &&
12973 		    (un->un_state != SD_STATE_PM_CHANGING)) {
12974 			New_state(un, SD_STATE_NORMAL);
12975 		}
12976 
12977 		xp = SD_GET_XBUF(bp);
12978 		ASSERT(xp != NULL);
12979 
12980 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12981 		/*
12982 		 * Allocate the scsi_pkt if we need one, or attach DMA
12983 		 * resources if we have a scsi_pkt that needs them. The
12984 		 * latter should only occur for commands that are being
12985 		 * retried.
12986 		 */
12987 		if ((xp->xb_pktp == NULL) ||
12988 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
12989 #else
12990 		if (xp->xb_pktp == NULL) {
12991 #endif
12992 			/*
12993 			 * There is no scsi_pkt allocated for this buf. Call
12994 			 * the initpkt function to allocate & init one.
12995 			 *
12996 			 * The scsi_init_pkt runout callback functionality is
12997 			 * implemented as follows:
12998 			 *
12999 			 * 1) The initpkt function always calls
13000 			 *    scsi_init_pkt(9F) with sdrunout specified as the
13001 			 *    callback routine.
13002 			 * 2) A successful packet allocation is initialized and
13003 			 *    the I/O is transported.
13004 			 * 3) The I/O associated with an allocation resource
13005 			 *    failure is left on its queue to be retried via
13006 			 *    runout or the next I/O.
13007 			 * 4) The I/O associated with a DMA error is removed
13008 			 *    from the queue and failed with EIO. Processing of
13009 			 *    the transport queues is also halted to be
13010 			 *    restarted via runout or the next I/O.
13011 			 * 5) The I/O associated with a CDB size or packet
13012 			 *    size error is removed from the queue and failed
13013 			 *    with EIO. Processing of the transport queues is
13014 			 *    continued.
13015 			 *
13016 			 * Note: there is no interface for canceling a runout
13017 			 * callback. To prevent the driver from detaching or
13018 			 * suspending while a runout is pending the driver
13019 			 * state is set to SD_STATE_RWAIT
13020 			 *
13021 			 * Note: using the scsi_init_pkt callback facility can
13022 			 * result in an I/O request persisting at the head of
13023 			 * the list which cannot be satisfied even after
13024 			 * multiple retries. In the future the driver may
13025 			 * implement some kind of maximum runout count before
13026 			 * failing an I/O.
13027 			 *
13028 			 * Note: the use of funcp below may seem superfluous,
13029 			 * but it helps warlock figure out the correct
13030 			 * initpkt function calls (see [s]sd.wlcmd).
13031 			 */
13032 			struct scsi_pkt	*pktp;
13033 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
13034 
13035 			ASSERT(bp != un->un_rqs_bp);
13036 
13037 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
13038 			switch ((*funcp)(bp, &pktp)) {
13039 			case  SD_PKT_ALLOC_SUCCESS:
13040 				xp->xb_pktp = pktp;
13041 				SD_TRACE(SD_LOG_IO_CORE, un,
13042 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
13043 				    pktp);
13044 				goto got_pkt;
13045 
13046 			case SD_PKT_ALLOC_FAILURE:
13047 				/*
13048 				 * Temporary (hopefully) resource depletion.
13049 				 * Since retries and RQS commands always have a
13050 				 * scsi_pkt allocated, these cases should never
13051 				 * get here. So the only cases this needs to
13052 				 * handle is a bp from the waitq (which we put
13053 				 * back onto the waitq for sdrunout), or a bp
13054 				 * sent as an immed_bp (which we just fail).
13055 				 */
13056 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13057 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
13058 
13059 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13060 
13061 				if (bp == immed_bp) {
13062 					/*
13063 					 * If SD_XB_DMA_FREED is clear, then
13064 					 * this is a failure to allocate a
13065 					 * scsi_pkt, and we must fail the
13066 					 * command.
13067 					 */
13068 					if ((xp->xb_pkt_flags &
13069 					    SD_XB_DMA_FREED) == 0) {
13070 						break;
13071 					}
13072 
13073 					/*
13074 					 * If this immediate command is NOT our
13075 					 * un_retry_bp, then we must fail it.
13076 					 */
13077 					if (bp != un->un_retry_bp) {
13078 						break;
13079 					}
13080 
13081 					/*
13082 					 * We get here if this cmd is our
13083 					 * un_retry_bp that was DMAFREED, but
13084 					 * scsi_init_pkt() failed to reallocate
13085 					 * DMA resources when we attempted to
13086 					 * retry it. This can happen when an
13087 					 * mpxio failover is in progress, but
13088 					 * we don't want to just fail the
13089 					 * command in this case.
13090 					 *
13091 					 * Use timeout(9F) to restart it after
13092 					 * a 100ms delay.  We don't want to
13093 					 * let sdrunout() restart it, because
13094 					 * sdrunout() is just supposed to start
13095 					 * commands that are sitting on the
13096 					 * wait queue.  The un_retry_bp stays
13097 					 * set until the command completes, but
13098 					 * sdrunout can be called many times
13099 					 * before that happens.  Since sdrunout
13100 					 * cannot tell if the un_retry_bp is
13101 					 * already in the transport, it could
13102 					 * end up calling scsi_transport() for
13103 					 * the un_retry_bp multiple times.
13104 					 *
13105 					 * Also: don't schedule the callback
13106 					 * if some other callback is already
13107 					 * pending.
13108 					 */
13109 					if (un->un_retry_statp == NULL) {
13110 						/*
13111 						 * restore the kstat pointer to
13112 						 * keep kstat counts coherent
13113 						 * when we do retry the command.
13114 						 */
13115 						un->un_retry_statp =
13116 						    saved_statp;
13117 					}
13118 
13119 					if ((un->un_startstop_timeid == NULL) &&
13120 					    (un->un_retry_timeid == NULL) &&
13121 					    (un->un_direct_priority_timeid ==
13122 					    NULL)) {
13123 
13124 						un->un_retry_timeid =
13125 						    timeout(
13126 						    sd_start_retry_command,
13127 						    un, SD_RESTART_TIMEOUT);
13128 					}
13129 					goto exit;
13130 				}
13131 
13132 #else
13133 				if (bp == immed_bp) {
13134 					break;	/* Just fail the command */
13135 				}
13136 #endif
13137 
13138 				/* Add the buf back to the head of the waitq */
13139 				bp->av_forw = un->un_waitq_headp;
13140 				un->un_waitq_headp = bp;
13141 				if (un->un_waitq_tailp == NULL) {
13142 					un->un_waitq_tailp = bp;
13143 				}
13144 				goto exit;
13145 
13146 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
13147 				/*
13148 				 * HBA DMA resource failure. Fail the command
13149 				 * and continue processing of the queues.
13150 				 */
13151 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13152 				    "sd_start_cmds: "
13153 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
13154 				break;
13155 
13156 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
13157 				/*
13158 				 * Note:x86: Partial DMA mapping not supported
13159 				 * for USCSI commands, and all the needed DMA
13160 				 * resources were not allocated.
13161 				 */
13162 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13163 				    "sd_start_cmds: "
13164 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
13165 				break;
13166 
13167 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
13168 				/*
13169 				 * Note:x86: Request cannot fit into CDB based
13170 				 * on lba and len.
13171 				 */
13172 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13173 				    "sd_start_cmds: "
13174 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
13175 				break;
13176 
13177 			default:
13178 				/* Should NEVER get here! */
13179 				panic("scsi_initpkt error");
13180 				/*NOTREACHED*/
13181 			}
13182 
13183 			/*
13184 			 * Fatal error in allocating a scsi_pkt for this buf.
13185 			 * Update kstats & return the buf with an error code.
13186 			 * We must use sd_return_failed_command_no_restart() to
13187 			 * avoid a recursive call back into sd_start_cmds().
13188 			 * However this also means that we must keep processing
13189 			 * the waitq here in order to avoid stalling.
13190 			 */
13191 			if (statp == kstat_waitq_to_runq) {
13192 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
13193 			}
13194 			sd_return_failed_command_no_restart(un, bp, EIO);
13195 			if (bp == immed_bp) {
13196 				/* immed_bp is gone by now, so clear this */
13197 				immed_bp = NULL;
13198 			}
13199 			continue;
13200 		}
13201 got_pkt:
13202 		if (bp == immed_bp) {
13203 			/* goto the head of the class.... */
13204 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13205 		}
13206 
13207 		un->un_ncmds_in_transport++;
13208 		SD_UPDATE_KSTATS(un, statp, bp);
13209 
13210 		/*
13211 		 * Call scsi_transport() to send the command to the target.
13212 		 * According to SCSA architecture, we must drop the mutex here
13213 		 * before calling scsi_transport() in order to avoid deadlock.
13214 		 * Note that the scsi_pkt's completion routine can be executed
13215 		 * (from interrupt context) even before the call to
13216 		 * scsi_transport() returns.
13217 		 */
13218 		SD_TRACE(SD_LOG_IO_CORE, un,
13219 		    "sd_start_cmds: calling scsi_transport()\n");
13220 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
13221 
13222 		mutex_exit(SD_MUTEX(un));
13223 		rval = scsi_transport(xp->xb_pktp);
13224 		mutex_enter(SD_MUTEX(un));
13225 
13226 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13227 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
13228 
13229 		switch (rval) {
13230 		case TRAN_ACCEPT:
13231 			/* Clear this with every pkt accepted by the HBA */
13232 			un->un_tran_fatal_count = 0;
13233 			break;	/* Success; try the next cmd (if any) */
13234 
13235 		case TRAN_BUSY:
13236 			un->un_ncmds_in_transport--;
13237 			ASSERT(un->un_ncmds_in_transport >= 0);
13238 
13239 			/*
13240 			 * Don't retry request sense, the sense data
13241 			 * is lost when another request is sent.
13242 			 * Free up the rqs buf and retry
13243 			 * the original failed cmd.  Update kstat.
13244 			 */
13245 			if (bp == un->un_rqs_bp) {
13246 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13247 				bp = sd_mark_rqs_idle(un, xp);
13248 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
13249 				    NULL, NULL, EIO, SD_BSY_TIMEOUT / 500,
13250 				    kstat_waitq_enter);
13251 				goto exit;
13252 			}
13253 
13254 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13255 			/*
13256 			 * Free the DMA resources for the  scsi_pkt. This will
13257 			 * allow mpxio to select another path the next time
13258 			 * we call scsi_transport() with this scsi_pkt.
13259 			 * See sdintr() for the rationalization behind this.
13260 			 */
13261 			if ((un->un_f_is_fibre == TRUE) &&
13262 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
13263 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
13264 				scsi_dmafree(xp->xb_pktp);
13265 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
13266 			}
13267 #endif
13268 
13269 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
13270 				/*
13271 				 * Commands that are SD_PATH_DIRECT_PRIORITY
13272 				 * are for error recovery situations. These do
13273 				 * not use the normal command waitq, so if they
13274 				 * get a TRAN_BUSY we cannot put them back onto
13275 				 * the waitq for later retry. One possible
13276 				 * problem is that there could already be some
13277 				 * other command on un_retry_bp that is waiting
13278 				 * for this one to complete, so we would be
13279 				 * deadlocked if we put this command back onto
13280 				 * the waitq for later retry (since un_retry_bp
13281 				 * must complete before the driver gets back to
13282 				 * commands on the waitq).
13283 				 *
13284 				 * To avoid deadlock we must schedule a callback
13285 				 * that will restart this command after a set
13286 				 * interval.  This should keep retrying for as
13287 				 * long as the underlying transport keeps
13288 				 * returning TRAN_BUSY (just like for other
13289 				 * commands).  Use the same timeout interval as
13290 				 * for the ordinary TRAN_BUSY retry.
13291 				 */
13292 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13293 				    "sd_start_cmds: scsi_transport() returned "
13294 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
13295 
13296 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13297 				un->un_direct_priority_timeid =
13298 				    timeout(sd_start_direct_priority_command,
13299 				    bp, SD_BSY_TIMEOUT / 500);
13300 
13301 				goto exit;
13302 			}
13303 
13304 			/*
13305 			 * For TRAN_BUSY, we want to reduce the throttle value,
13306 			 * unless we are retrying a command.
13307 			 */
13308 			if (bp != un->un_retry_bp) {
13309 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
13310 			}
13311 
13312 			/*
13313 			 * Set up the bp to be tried again 10 ms later.
13314 			 * Note:x86: Is there a timeout value in the sd_lun
13315 			 * for this condition?
13316 			 */
13317 			sd_set_retry_bp(un, bp, SD_BSY_TIMEOUT / 500,
13318 			    kstat_runq_back_to_waitq);
13319 			goto exit;
13320 
13321 		case TRAN_FATAL_ERROR:
13322 			un->un_tran_fatal_count++;
13323 			/* FALLTHRU */
13324 
13325 		case TRAN_BADPKT:
13326 		default:
13327 			un->un_ncmds_in_transport--;
13328 			ASSERT(un->un_ncmds_in_transport >= 0);
13329 
13330 			/*
13331 			 * If this is our REQUEST SENSE command with a
13332 			 * transport error, we must get back the pointers
13333 			 * to the original buf, and mark the REQUEST
13334 			 * SENSE command as "available".
13335 			 */
13336 			if (bp == un->un_rqs_bp) {
13337 				bp = sd_mark_rqs_idle(un, xp);
13338 				xp = SD_GET_XBUF(bp);
13339 			} else {
13340 				/*
13341 				 * Legacy behavior: do not update transport
13342 				 * error count for request sense commands.
13343 				 */
13344 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
13345 			}
13346 
13347 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13348 			sd_print_transport_rejected_message(un, xp, rval);
13349 
13350 			/*
13351 			 * We must use sd_return_failed_command_no_restart() to
13352 			 * avoid a recursive call back into sd_start_cmds().
13353 			 * However this also means that we must keep processing
13354 			 * the waitq here in order to avoid stalling.
13355 			 */
13356 			sd_return_failed_command_no_restart(un, bp, EIO);
13357 
13358 			/*
13359 			 * Notify any threads waiting in sd_ddi_suspend() that
13360 			 * a command completion has occurred.
13361 			 */
13362 			if (un->un_state == SD_STATE_SUSPENDED) {
13363 				cv_broadcast(&un->un_disk_busy_cv);
13364 			}
13365 
13366 			if (bp == immed_bp) {
13367 				/* immed_bp is gone by now, so clear this */
13368 				immed_bp = NULL;
13369 			}
13370 			break;
13371 		}
13372 
13373 	} while (immed_bp == NULL);
13374 
13375 exit:
13376 	ASSERT(mutex_owned(SD_MUTEX(un)));
13377 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
13378 }
13379 
13380 
13381 /*
13382  *    Function: sd_return_command
13383  *
13384  * Description: Returns a command to its originator (with or without an
13385  *		error).  Also starts commands waiting to be transported
13386  *		to the target.
13387  *
13388  *     Context: May be called from interrupt, kernel, or timeout context
13389  */
13390 
13391 static void
13392 sd_return_command(struct sd_lun *un, struct buf *bp)
13393 {
13394 	struct sd_xbuf *xp;
13395 	struct scsi_pkt *pktp;
13396 
13397 	ASSERT(bp != NULL);
13398 	ASSERT(un != NULL);
13399 	ASSERT(mutex_owned(SD_MUTEX(un)));
13400 	ASSERT(bp != un->un_rqs_bp);
13401 	xp = SD_GET_XBUF(bp);
13402 	ASSERT(xp != NULL);
13403 
13404 	pktp = SD_GET_PKTP(bp);
13405 
13406 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
13407 
13408 	/*
13409 	 * Note: check for the "sdrestart failed" case.
13410 	 */
13411 	if ((un->un_partial_dma_supported == 1) &&
13412 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
13413 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
13414 	    (xp->xb_pktp->pkt_resid == 0)) {
13415 
13416 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
13417 			/*
13418 			 * Successfully set up next portion of cmd
13419 			 * transfer, try sending it
13420 			 */
13421 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
13422 			    NULL, NULL, 0, (clock_t)0, NULL);
13423 			sd_start_cmds(un, NULL);
13424 			return;	/* Note:x86: need a return here? */
13425 		}
13426 	}
13427 
13428 	/*
13429 	 * If this is the failfast bp, clear it from un_failfast_bp. This
13430 	 * can happen if upon being re-tried the failfast bp either
13431 	 * succeeded or encountered another error (possibly even a different
13432 	 * error than the one that precipitated the failfast state, but in
13433 	 * that case it would have had to exhaust retries as well). Regardless,
13434 	 * this should not occur whenever the instance is in the active
13435 	 * failfast state.
13436 	 */
13437 	if (bp == un->un_failfast_bp) {
13438 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13439 		un->un_failfast_bp = NULL;
13440 	}
13441 
13442 	/*
13443 	 * Clear the failfast state upon successful completion of ANY cmd.
13444 	 */
13445 	if (bp->b_error == 0) {
13446 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13447 	}
13448 
13449 	/*
13450 	 * This is used if the command was retried one or more times. Show that
13451 	 * we are done with it, and allow processing of the waitq to resume.
13452 	 */
13453 	if (bp == un->un_retry_bp) {
13454 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13455 		    "sd_return_command: un:0x%p: "
13456 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13457 		un->un_retry_bp = NULL;
13458 		un->un_retry_statp = NULL;
13459 	}
13460 
13461 	SD_UPDATE_RDWR_STATS(un, bp);
13462 	SD_UPDATE_PARTITION_STATS(un, bp);
13463 
13464 	switch (un->un_state) {
13465 	case SD_STATE_SUSPENDED:
13466 		/*
13467 		 * Notify any threads waiting in sd_ddi_suspend() that
13468 		 * a command completion has occurred.
13469 		 */
13470 		cv_broadcast(&un->un_disk_busy_cv);
13471 		break;
13472 	default:
13473 		sd_start_cmds(un, NULL);
13474 		break;
13475 	}
13476 
13477 	/* Return this command up the iodone chain to its originator. */
13478 	mutex_exit(SD_MUTEX(un));
13479 
13480 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13481 	xp->xb_pktp = NULL;
13482 
13483 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13484 
13485 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13486 	mutex_enter(SD_MUTEX(un));
13487 
13488 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
13489 }
13490 
13491 
13492 /*
13493  *    Function: sd_return_failed_command
13494  *
13495  * Description: Command completion when an error occurred.
13496  *
13497  *     Context: May be called from interrupt context
13498  */
13499 
13500 static void
13501 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
13502 {
13503 	ASSERT(bp != NULL);
13504 	ASSERT(un != NULL);
13505 	ASSERT(mutex_owned(SD_MUTEX(un)));
13506 
13507 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13508 	    "sd_return_failed_command: entry\n");
13509 
13510 	/*
13511 	 * b_resid could already be nonzero due to a partial data
13512 	 * transfer, so do not change it here.
13513 	 */
13514 	SD_BIOERROR(bp, errcode);
13515 
13516 	sd_return_command(un, bp);
13517 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13518 	    "sd_return_failed_command: exit\n");
13519 }
13520 
13521 
13522 /*
13523  *    Function: sd_return_failed_command_no_restart
13524  *
13525  * Description: Same as sd_return_failed_command, but ensures that no
13526  *		call back into sd_start_cmds will be issued.
13527  *
13528  *     Context: May be called from interrupt context
13529  */
13530 
13531 static void
13532 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
13533 	int errcode)
13534 {
13535 	struct sd_xbuf *xp;
13536 
13537 	ASSERT(bp != NULL);
13538 	ASSERT(un != NULL);
13539 	ASSERT(mutex_owned(SD_MUTEX(un)));
13540 	xp = SD_GET_XBUF(bp);
13541 	ASSERT(xp != NULL);
13542 	ASSERT(errcode != 0);
13543 
13544 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13545 	    "sd_return_failed_command_no_restart: entry\n");
13546 
13547 	/*
13548 	 * b_resid could already be nonzero due to a partial data
13549 	 * transfer, so do not change it here.
13550 	 */
13551 	SD_BIOERROR(bp, errcode);
13552 
13553 	/*
13554 	 * If this is the failfast bp, clear it. This can happen if the
13555 	 * failfast bp encounterd a fatal error when we attempted to
13556 	 * re-try it (such as a scsi_transport(9F) failure).  However
13557 	 * we should NOT be in an active failfast state if the failfast
13558 	 * bp is not NULL.
13559 	 */
13560 	if (bp == un->un_failfast_bp) {
13561 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13562 		un->un_failfast_bp = NULL;
13563 	}
13564 
13565 	if (bp == un->un_retry_bp) {
13566 		/*
13567 		 * This command was retried one or more times. Show that we are
13568 		 * done with it, and allow processing of the waitq to resume.
13569 		 */
13570 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13571 		    "sd_return_failed_command_no_restart: "
13572 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13573 		un->un_retry_bp = NULL;
13574 		un->un_retry_statp = NULL;
13575 	}
13576 
13577 	SD_UPDATE_RDWR_STATS(un, bp);
13578 	SD_UPDATE_PARTITION_STATS(un, bp);
13579 
13580 	mutex_exit(SD_MUTEX(un));
13581 
13582 	if (xp->xb_pktp != NULL) {
13583 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13584 		xp->xb_pktp = NULL;
13585 	}
13586 
13587 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13588 
13589 	mutex_enter(SD_MUTEX(un));
13590 
13591 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13592 	    "sd_return_failed_command_no_restart: exit\n");
13593 }
13594 
13595 
13596 /*
13597  *    Function: sd_retry_command
13598  *
13599  * Description: queue up a command for retry, or (optionally) fail it
13600  *		if retry counts are exhausted.
13601  *
13602  *   Arguments: un - Pointer to the sd_lun struct for the target.
13603  *
13604  *		bp - Pointer to the buf for the command to be retried.
13605  *
13606  *		retry_check_flag - Flag to see which (if any) of the retry
13607  *		   counts should be decremented/checked. If the indicated
13608  *		   retry count is exhausted, then the command will not be
13609  *		   retried; it will be failed instead. This should use a
13610  *		   value equal to one of the following:
13611  *
13612  *			SD_RETRIES_NOCHECK
13613  *			SD_RESD_RETRIES_STANDARD
13614  *			SD_RETRIES_VICTIM
13615  *
13616  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
13617  *		   if the check should be made to see of FLAG_ISOLATE is set
13618  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
13619  *		   not retried, it is simply failed.
13620  *
13621  *		user_funcp - Ptr to function to call before dispatching the
13622  *		   command. May be NULL if no action needs to be performed.
13623  *		   (Primarily intended for printing messages.)
13624  *
13625  *		user_arg - Optional argument to be passed along to
13626  *		   the user_funcp call.
13627  *
13628  *		failure_code - errno return code to set in the bp if the
13629  *		   command is going to be failed.
13630  *
13631  *		retry_delay - Retry delay interval in (clock_t) units. May
13632  *		   be zero which indicates that the retry should be retried
13633  *		   immediately (ie, without an intervening delay).
13634  *
13635  *		statp - Ptr to kstat function to be updated if the command
13636  *		   is queued for a delayed retry. May be NULL if no kstat
13637  *		   update is desired.
13638  *
13639  *     Context: May be called from interrupt context.
13640  */
13641 
13642 static void
13643 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
13644 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int
13645 	code), void *user_arg, int failure_code,  clock_t retry_delay,
13646 	void (*statp)(kstat_io_t *))
13647 {
13648 	struct sd_xbuf	*xp;
13649 	struct scsi_pkt	*pktp;
13650 
13651 	ASSERT(un != NULL);
13652 	ASSERT(mutex_owned(SD_MUTEX(un)));
13653 	ASSERT(bp != NULL);
13654 	xp = SD_GET_XBUF(bp);
13655 	ASSERT(xp != NULL);
13656 	pktp = SD_GET_PKTP(bp);
13657 	ASSERT(pktp != NULL);
13658 
13659 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
13660 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
13661 
13662 	/*
13663 	 * If we are syncing or dumping, fail the command to avoid
13664 	 * recursively calling back into scsi_transport().
13665 	 */
13666 	if (ddi_in_panic()) {
13667 		goto fail_command_no_log;
13668 	}
13669 
13670 	/*
13671 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
13672 	 * log an error and fail the command.
13673 	 */
13674 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
13675 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
13676 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
13677 		sd_dump_memory(un, SD_LOG_IO, "CDB",
13678 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
13679 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
13680 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
13681 		goto fail_command;
13682 	}
13683 
13684 	/*
13685 	 * If we are suspended, then put the command onto head of the
13686 	 * wait queue since we don't want to start more commands, and
13687 	 * clear the un_retry_bp. Next time when we are resumed, will
13688 	 * handle the command in the wait queue.
13689 	 */
13690 	switch (un->un_state) {
13691 	case SD_STATE_SUSPENDED:
13692 	case SD_STATE_DUMPING:
13693 		bp->av_forw = un->un_waitq_headp;
13694 		un->un_waitq_headp = bp;
13695 		if (un->un_waitq_tailp == NULL) {
13696 			un->un_waitq_tailp = bp;
13697 		}
13698 		if (bp == un->un_retry_bp) {
13699 			un->un_retry_bp = NULL;
13700 			un->un_retry_statp = NULL;
13701 		}
13702 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13703 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
13704 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
13705 		return;
13706 	default:
13707 		break;
13708 	}
13709 
13710 	/*
13711 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
13712 	 * is set; if it is then we do not want to retry the command.
13713 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
13714 	 */
13715 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
13716 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
13717 			goto fail_command;
13718 		}
13719 	}
13720 
13721 
13722 	/*
13723 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
13724 	 * command timeout or a selection timeout has occurred. This means
13725 	 * that we were unable to establish an kind of communication with
13726 	 * the target, and subsequent retries and/or commands are likely
13727 	 * to encounter similar results and take a long time to complete.
13728 	 *
13729 	 * If this is a failfast error condition, we need to update the
13730 	 * failfast state, even if this bp does not have B_FAILFAST set.
13731 	 */
13732 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
13733 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
13734 			ASSERT(un->un_failfast_bp == NULL);
13735 			/*
13736 			 * If we are already in the active failfast state, and
13737 			 * another failfast error condition has been detected,
13738 			 * then fail this command if it has B_FAILFAST set.
13739 			 * If B_FAILFAST is clear, then maintain the legacy
13740 			 * behavior of retrying heroically, even tho this will
13741 			 * take a lot more time to fail the command.
13742 			 */
13743 			if (bp->b_flags & B_FAILFAST) {
13744 				goto fail_command;
13745 			}
13746 		} else {
13747 			/*
13748 			 * We're not in the active failfast state, but we
13749 			 * have a failfast error condition, so we must begin
13750 			 * transition to the next state. We do this regardless
13751 			 * of whether or not this bp has B_FAILFAST set.
13752 			 */
13753 			if (un->un_failfast_bp == NULL) {
13754 				/*
13755 				 * This is the first bp to meet a failfast
13756 				 * condition so save it on un_failfast_bp &
13757 				 * do normal retry processing. Do not enter
13758 				 * active failfast state yet. This marks
13759 				 * entry into the "failfast pending" state.
13760 				 */
13761 				un->un_failfast_bp = bp;
13762 
13763 			} else if (un->un_failfast_bp == bp) {
13764 				/*
13765 				 * This is the second time *this* bp has
13766 				 * encountered a failfast error condition,
13767 				 * so enter active failfast state & flush
13768 				 * queues as appropriate.
13769 				 */
13770 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
13771 				un->un_failfast_bp = NULL;
13772 				sd_failfast_flushq(un);
13773 
13774 				/*
13775 				 * Fail this bp now if B_FAILFAST set;
13776 				 * otherwise continue with retries. (It would
13777 				 * be pretty ironic if this bp succeeded on a
13778 				 * subsequent retry after we just flushed all
13779 				 * the queues).
13780 				 */
13781 				if (bp->b_flags & B_FAILFAST) {
13782 					goto fail_command;
13783 				}
13784 
13785 #if !defined(lint) && !defined(__lint)
13786 			} else {
13787 				/*
13788 				 * If neither of the preceeding conditionals
13789 				 * was true, it means that there is some
13790 				 * *other* bp that has met an inital failfast
13791 				 * condition and is currently either being
13792 				 * retried or is waiting to be retried. In
13793 				 * that case we should perform normal retry
13794 				 * processing on *this* bp, since there is a
13795 				 * chance that the current failfast condition
13796 				 * is transient and recoverable. If that does
13797 				 * not turn out to be the case, then retries
13798 				 * will be cleared when the wait queue is
13799 				 * flushed anyway.
13800 				 */
13801 #endif
13802 			}
13803 		}
13804 	} else {
13805 		/*
13806 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
13807 		 * likely were able to at least establish some level of
13808 		 * communication with the target and subsequent commands
13809 		 * and/or retries are likely to get through to the target,
13810 		 * In this case we want to be aggressive about clearing
13811 		 * the failfast state. Note that this does not affect
13812 		 * the "failfast pending" condition.
13813 		 */
13814 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13815 	}
13816 
13817 
13818 	/*
13819 	 * Check the specified retry count to see if we can still do
13820 	 * any retries with this pkt before we should fail it.
13821 	 */
13822 	switch (retry_check_flag & SD_RETRIES_MASK) {
13823 	case SD_RETRIES_VICTIM:
13824 		/*
13825 		 * Check the victim retry count. If exhausted, then fall
13826 		 * thru & check against the standard retry count.
13827 		 */
13828 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
13829 			/* Increment count & proceed with the retry */
13830 			xp->xb_victim_retry_count++;
13831 			break;
13832 		}
13833 		/* Victim retries exhausted, fall back to std. retries... */
13834 		/* FALLTHRU */
13835 
13836 	case SD_RETRIES_STANDARD:
13837 		if (xp->xb_retry_count >= un->un_retry_count) {
13838 			/* Retries exhausted, fail the command */
13839 			SD_TRACE(SD_LOG_IO_CORE, un,
13840 			    "sd_retry_command: retries exhausted!\n");
13841 			/*
13842 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
13843 			 * commands with nonzero pkt_resid.
13844 			 */
13845 			if ((pktp->pkt_reason == CMD_CMPLT) &&
13846 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
13847 			    (pktp->pkt_resid != 0)) {
13848 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
13849 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
13850 					SD_UPDATE_B_RESID(bp, pktp);
13851 				}
13852 			}
13853 			goto fail_command;
13854 		}
13855 		xp->xb_retry_count++;
13856 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13857 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13858 		break;
13859 
13860 	case SD_RETRIES_UA:
13861 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
13862 			/* Retries exhausted, fail the command */
13863 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13864 			    "Unit Attention retries exhausted. "
13865 			    "Check the target.\n");
13866 			goto fail_command;
13867 		}
13868 		xp->xb_ua_retry_count++;
13869 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13870 		    "sd_retry_command: retry count:%d\n",
13871 		    xp->xb_ua_retry_count);
13872 		break;
13873 
13874 	case SD_RETRIES_BUSY:
13875 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
13876 			/* Retries exhausted, fail the command */
13877 			SD_TRACE(SD_LOG_IO_CORE, un,
13878 			    "sd_retry_command: retries exhausted!\n");
13879 			goto fail_command;
13880 		}
13881 		xp->xb_retry_count++;
13882 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13883 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13884 		break;
13885 
13886 	case SD_RETRIES_NOCHECK:
13887 	default:
13888 		/* No retry count to check. Just proceed with the retry */
13889 		break;
13890 	}
13891 
13892 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13893 
13894 	/*
13895 	 * If we were given a zero timeout, we must attempt to retry the
13896 	 * command immediately (ie, without a delay).
13897 	 */
13898 	if (retry_delay == 0) {
13899 		/*
13900 		 * Check some limiting conditions to see if we can actually
13901 		 * do the immediate retry.  If we cannot, then we must
13902 		 * fall back to queueing up a delayed retry.
13903 		 */
13904 		if (un->un_ncmds_in_transport >= un->un_throttle) {
13905 			/*
13906 			 * We are at the throttle limit for the target,
13907 			 * fall back to delayed retry.
13908 			 */
13909 			retry_delay = SD_BSY_TIMEOUT;
13910 			statp = kstat_waitq_enter;
13911 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13912 			    "sd_retry_command: immed. retry hit "
13913 			    "throttle!\n");
13914 		} else {
13915 			/*
13916 			 * We're clear to proceed with the immediate retry.
13917 			 * First call the user-provided function (if any)
13918 			 */
13919 			if (user_funcp != NULL) {
13920 				(*user_funcp)(un, bp, user_arg,
13921 				    SD_IMMEDIATE_RETRY_ISSUED);
13922 #ifdef __lock_lint
13923 				sd_print_incomplete_msg(un, bp, user_arg,
13924 				    SD_IMMEDIATE_RETRY_ISSUED);
13925 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
13926 				    SD_IMMEDIATE_RETRY_ISSUED);
13927 				sd_print_sense_failed_msg(un, bp, user_arg,
13928 				    SD_IMMEDIATE_RETRY_ISSUED);
13929 #endif
13930 			}
13931 
13932 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13933 			    "sd_retry_command: issuing immediate retry\n");
13934 
13935 			/*
13936 			 * Call sd_start_cmds() to transport the command to
13937 			 * the target.
13938 			 */
13939 			sd_start_cmds(un, bp);
13940 
13941 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13942 			    "sd_retry_command exit\n");
13943 			return;
13944 		}
13945 	}
13946 
13947 	/*
13948 	 * Set up to retry the command after a delay.
13949 	 * First call the user-provided function (if any)
13950 	 */
13951 	if (user_funcp != NULL) {
13952 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
13953 	}
13954 
13955 	sd_set_retry_bp(un, bp, retry_delay, statp);
13956 
13957 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
13958 	return;
13959 
13960 fail_command:
13961 
13962 	if (user_funcp != NULL) {
13963 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
13964 	}
13965 
13966 fail_command_no_log:
13967 
13968 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13969 	    "sd_retry_command: returning failed command\n");
13970 
13971 	sd_return_failed_command(un, bp, failure_code);
13972 
13973 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
13974 }
13975 
13976 
13977 /*
13978  *    Function: sd_set_retry_bp
13979  *
13980  * Description: Set up the given bp for retry.
13981  *
13982  *   Arguments: un - ptr to associated softstate
13983  *		bp - ptr to buf(9S) for the command
13984  *		retry_delay - time interval before issuing retry (may be 0)
13985  *		statp - optional pointer to kstat function
13986  *
13987  *     Context: May be called under interrupt context
13988  */
13989 
13990 static void
13991 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
13992 	void (*statp)(kstat_io_t *))
13993 {
13994 	ASSERT(un != NULL);
13995 	ASSERT(mutex_owned(SD_MUTEX(un)));
13996 	ASSERT(bp != NULL);
13997 
13998 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
13999 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
14000 
14001 	/*
14002 	 * Indicate that the command is being retried. This will not allow any
14003 	 * other commands on the wait queue to be transported to the target
14004 	 * until this command has been completed (success or failure). The
14005 	 * "retry command" is not transported to the target until the given
14006 	 * time delay expires, unless the user specified a 0 retry_delay.
14007 	 *
14008 	 * Note: the timeout(9F) callback routine is what actually calls
14009 	 * sd_start_cmds() to transport the command, with the exception of a
14010 	 * zero retry_delay. The only current implementor of a zero retry delay
14011 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
14012 	 */
14013 	if (un->un_retry_bp == NULL) {
14014 		ASSERT(un->un_retry_statp == NULL);
14015 		un->un_retry_bp = bp;
14016 
14017 		/*
14018 		 * If the user has not specified a delay the command should
14019 		 * be queued and no timeout should be scheduled.
14020 		 */
14021 		if (retry_delay == 0) {
14022 			/*
14023 			 * Save the kstat pointer that will be used in the
14024 			 * call to SD_UPDATE_KSTATS() below, so that
14025 			 * sd_start_cmds() can correctly decrement the waitq
14026 			 * count when it is time to transport this command.
14027 			 */
14028 			un->un_retry_statp = statp;
14029 			goto done;
14030 		}
14031 	}
14032 
14033 	if (un->un_retry_bp == bp) {
14034 		/*
14035 		 * Save the kstat pointer that will be used in the call to
14036 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
14037 		 * correctly decrement the waitq count when it is time to
14038 		 * transport this command.
14039 		 */
14040 		un->un_retry_statp = statp;
14041 
14042 		/*
14043 		 * Schedule a timeout if:
14044 		 *   1) The user has specified a delay.
14045 		 *   2) There is not a START_STOP_UNIT callback pending.
14046 		 *
14047 		 * If no delay has been specified, then it is up to the caller
14048 		 * to ensure that IO processing continues without stalling.
14049 		 * Effectively, this means that the caller will issue the
14050 		 * required call to sd_start_cmds(). The START_STOP_UNIT
14051 		 * callback does this after the START STOP UNIT command has
14052 		 * completed. In either of these cases we should not schedule
14053 		 * a timeout callback here.  Also don't schedule the timeout if
14054 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
14055 		 */
14056 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
14057 		    (un->un_direct_priority_timeid == NULL)) {
14058 			un->un_retry_timeid =
14059 			    timeout(sd_start_retry_command, un, retry_delay);
14060 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14061 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
14062 			    " bp:0x%p un_retry_timeid:0x%p\n",
14063 			    un, bp, un->un_retry_timeid);
14064 		}
14065 	} else {
14066 		/*
14067 		 * We only get in here if there is already another command
14068 		 * waiting to be retried.  In this case, we just put the
14069 		 * given command onto the wait queue, so it can be transported
14070 		 * after the current retry command has completed.
14071 		 *
14072 		 * Also we have to make sure that if the command at the head
14073 		 * of the wait queue is the un_failfast_bp, that we do not
14074 		 * put ahead of it any other commands that are to be retried.
14075 		 */
14076 		if ((un->un_failfast_bp != NULL) &&
14077 		    (un->un_failfast_bp == un->un_waitq_headp)) {
14078 			/*
14079 			 * Enqueue this command AFTER the first command on
14080 			 * the wait queue (which is also un_failfast_bp).
14081 			 */
14082 			bp->av_forw = un->un_waitq_headp->av_forw;
14083 			un->un_waitq_headp->av_forw = bp;
14084 			if (un->un_waitq_headp == un->un_waitq_tailp) {
14085 				un->un_waitq_tailp = bp;
14086 			}
14087 		} else {
14088 			/* Enqueue this command at the head of the waitq. */
14089 			bp->av_forw = un->un_waitq_headp;
14090 			un->un_waitq_headp = bp;
14091 			if (un->un_waitq_tailp == NULL) {
14092 				un->un_waitq_tailp = bp;
14093 			}
14094 		}
14095 
14096 		if (statp == NULL) {
14097 			statp = kstat_waitq_enter;
14098 		}
14099 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14100 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
14101 	}
14102 
14103 done:
14104 	if (statp != NULL) {
14105 		SD_UPDATE_KSTATS(un, statp, bp);
14106 	}
14107 
14108 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14109 	    "sd_set_retry_bp: exit un:0x%p\n", un);
14110 }
14111 
14112 
14113 /*
14114  *    Function: sd_start_retry_command
14115  *
14116  * Description: Start the command that has been waiting on the target's
14117  *		retry queue.  Called from timeout(9F) context after the
14118  *		retry delay interval has expired.
14119  *
14120  *   Arguments: arg - pointer to associated softstate for the device.
14121  *
14122  *     Context: timeout(9F) thread context.  May not sleep.
14123  */
14124 
14125 static void
14126 sd_start_retry_command(void *arg)
14127 {
14128 	struct sd_lun *un = arg;
14129 
14130 	ASSERT(un != NULL);
14131 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14132 
14133 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14134 	    "sd_start_retry_command: entry\n");
14135 
14136 	mutex_enter(SD_MUTEX(un));
14137 
14138 	un->un_retry_timeid = NULL;
14139 
14140 	if (un->un_retry_bp != NULL) {
14141 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14142 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
14143 		    un, un->un_retry_bp);
14144 		sd_start_cmds(un, un->un_retry_bp);
14145 	}
14146 
14147 	mutex_exit(SD_MUTEX(un));
14148 
14149 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14150 	    "sd_start_retry_command: exit\n");
14151 }
14152 
14153 
14154 /*
14155  *    Function: sd_start_direct_priority_command
14156  *
14157  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
14158  *		received TRAN_BUSY when we called scsi_transport() to send it
14159  *		to the underlying HBA. This function is called from timeout(9F)
14160  *		context after the delay interval has expired.
14161  *
14162  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
14163  *
14164  *     Context: timeout(9F) thread context.  May not sleep.
14165  */
14166 
14167 static void
14168 sd_start_direct_priority_command(void *arg)
14169 {
14170 	struct buf	*priority_bp = arg;
14171 	struct sd_lun	*un;
14172 
14173 	ASSERT(priority_bp != NULL);
14174 	un = SD_GET_UN(priority_bp);
14175 	ASSERT(un != NULL);
14176 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14177 
14178 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14179 	    "sd_start_direct_priority_command: entry\n");
14180 
14181 	mutex_enter(SD_MUTEX(un));
14182 	un->un_direct_priority_timeid = NULL;
14183 	sd_start_cmds(un, priority_bp);
14184 	mutex_exit(SD_MUTEX(un));
14185 
14186 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14187 	    "sd_start_direct_priority_command: exit\n");
14188 }
14189 
14190 
14191 /*
14192  *    Function: sd_send_request_sense_command
14193  *
14194  * Description: Sends a REQUEST SENSE command to the target
14195  *
14196  *     Context: May be called from interrupt context.
14197  */
14198 
14199 static void
14200 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
14201 	struct scsi_pkt *pktp)
14202 {
14203 	ASSERT(bp != NULL);
14204 	ASSERT(un != NULL);
14205 	ASSERT(mutex_owned(SD_MUTEX(un)));
14206 
14207 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
14208 	    "entry: buf:0x%p\n", bp);
14209 
14210 	/*
14211 	 * If we are syncing or dumping, then fail the command to avoid a
14212 	 * recursive callback into scsi_transport(). Also fail the command
14213 	 * if we are suspended (legacy behavior).
14214 	 */
14215 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
14216 	    (un->un_state == SD_STATE_DUMPING)) {
14217 		sd_return_failed_command(un, bp, EIO);
14218 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14219 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
14220 		return;
14221 	}
14222 
14223 	/*
14224 	 * Retry the failed command and don't issue the request sense if:
14225 	 *    1) the sense buf is busy
14226 	 *    2) we have 1 or more outstanding commands on the target
14227 	 *    (the sense data will be cleared or invalidated any way)
14228 	 *
14229 	 * Note: There could be an issue with not checking a retry limit here,
14230 	 * the problem is determining which retry limit to check.
14231 	 */
14232 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
14233 		/* Don't retry if the command is flagged as non-retryable */
14234 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
14235 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
14236 			    NULL, NULL, 0, SD_BSY_TIMEOUT, kstat_waitq_enter);
14237 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14238 			    "sd_send_request_sense_command: "
14239 			    "at full throttle, retrying exit\n");
14240 		} else {
14241 			sd_return_failed_command(un, bp, EIO);
14242 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14243 			    "sd_send_request_sense_command: "
14244 			    "at full throttle, non-retryable exit\n");
14245 		}
14246 		return;
14247 	}
14248 
14249 	sd_mark_rqs_busy(un, bp);
14250 	sd_start_cmds(un, un->un_rqs_bp);
14251 
14252 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14253 	    "sd_send_request_sense_command: exit\n");
14254 }
14255 
14256 
14257 /*
14258  *    Function: sd_mark_rqs_busy
14259  *
14260  * Description: Indicate that the request sense bp for this instance is
14261  *		in use.
14262  *
14263  *     Context: May be called under interrupt context
14264  */
14265 
14266 static void
14267 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
14268 {
14269 	struct sd_xbuf	*sense_xp;
14270 
14271 	ASSERT(un != NULL);
14272 	ASSERT(bp != NULL);
14273 	ASSERT(mutex_owned(SD_MUTEX(un)));
14274 	ASSERT(un->un_sense_isbusy == 0);
14275 
14276 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
14277 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
14278 
14279 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
14280 	ASSERT(sense_xp != NULL);
14281 
14282 	SD_INFO(SD_LOG_IO, un,
14283 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
14284 
14285 	ASSERT(sense_xp->xb_pktp != NULL);
14286 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
14287 	    == (FLAG_SENSING | FLAG_HEAD));
14288 
14289 	un->un_sense_isbusy = 1;
14290 	un->un_rqs_bp->b_resid = 0;
14291 	sense_xp->xb_pktp->pkt_resid  = 0;
14292 	sense_xp->xb_pktp->pkt_reason = 0;
14293 
14294 	/* So we can get back the bp at interrupt time! */
14295 	sense_xp->xb_sense_bp = bp;
14296 
14297 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
14298 
14299 	/*
14300 	 * Mark this buf as awaiting sense data. (This is already set in
14301 	 * the pkt_flags for the RQS packet.)
14302 	 */
14303 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
14304 
14305 	sense_xp->xb_retry_count	= 0;
14306 	sense_xp->xb_victim_retry_count = 0;
14307 	sense_xp->xb_ua_retry_count	= 0;
14308 	sense_xp->xb_nr_retry_count 	= 0;
14309 	sense_xp->xb_dma_resid  = 0;
14310 
14311 	/* Clean up the fields for auto-request sense */
14312 	sense_xp->xb_sense_status = 0;
14313 	sense_xp->xb_sense_state  = 0;
14314 	sense_xp->xb_sense_resid  = 0;
14315 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
14316 
14317 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
14318 }
14319 
14320 
14321 /*
14322  *    Function: sd_mark_rqs_idle
14323  *
14324  * Description: SD_MUTEX must be held continuously through this routine
14325  *		to prevent reuse of the rqs struct before the caller can
14326  *		complete it's processing.
14327  *
14328  * Return Code: Pointer to the RQS buf
14329  *
14330  *     Context: May be called under interrupt context
14331  */
14332 
14333 static struct buf *
14334 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
14335 {
14336 	struct buf *bp;
14337 	ASSERT(un != NULL);
14338 	ASSERT(sense_xp != NULL);
14339 	ASSERT(mutex_owned(SD_MUTEX(un)));
14340 	ASSERT(un->un_sense_isbusy != 0);
14341 
14342 	un->un_sense_isbusy = 0;
14343 	bp = sense_xp->xb_sense_bp;
14344 	sense_xp->xb_sense_bp = NULL;
14345 
14346 	/* This pkt is no longer interested in getting sense data */
14347 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
14348 
14349 	return (bp);
14350 }
14351 
14352 
14353 
14354 /*
14355  *    Function: sd_alloc_rqs
14356  *
14357  * Description: Set up the unit to receive auto request sense data
14358  *
14359  * Return Code: DDI_SUCCESS or DDI_FAILURE
14360  *
14361  *     Context: Called under attach(9E) context
14362  */
14363 
14364 static int
14365 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
14366 {
14367 	struct sd_xbuf *xp;
14368 
14369 	ASSERT(un != NULL);
14370 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14371 	ASSERT(un->un_rqs_bp == NULL);
14372 	ASSERT(un->un_rqs_pktp == NULL);
14373 
14374 	/*
14375 	 * First allocate the required buf and scsi_pkt structs, then set up
14376 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
14377 	 */
14378 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
14379 	    SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
14380 	if (un->un_rqs_bp == NULL) {
14381 		return (DDI_FAILURE);
14382 	}
14383 
14384 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
14385 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
14386 
14387 	if (un->un_rqs_pktp == NULL) {
14388 		sd_free_rqs(un);
14389 		return (DDI_FAILURE);
14390 	}
14391 
14392 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
14393 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
14394 	    SCMD_REQUEST_SENSE, 0, SENSE_LENGTH, 0);
14395 
14396 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
14397 
14398 	/* Set up the other needed members in the ARQ scsi_pkt. */
14399 	un->un_rqs_pktp->pkt_comp   = sdintr;
14400 	un->un_rqs_pktp->pkt_time   = sd_io_time;
14401 	un->un_rqs_pktp->pkt_flags |=
14402 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
14403 
14404 	/*
14405 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
14406 	 * provide any intpkt, destroypkt routines as we take care of
14407 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
14408 	 */
14409 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14410 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
14411 	xp->xb_pktp = un->un_rqs_pktp;
14412 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
14413 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
14414 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
14415 
14416 	/*
14417 	 * Save the pointer to the request sense private bp so it can
14418 	 * be retrieved in sdintr.
14419 	 */
14420 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
14421 	ASSERT(un->un_rqs_bp->b_private == xp);
14422 
14423 	/*
14424 	 * See if the HBA supports auto-request sense for the specified
14425 	 * target/lun. If it does, then try to enable it (if not already
14426 	 * enabled).
14427 	 *
14428 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
14429 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
14430 	 * return success.  However, in both of these cases ARQ is always
14431 	 * enabled and scsi_ifgetcap will always return true. The best approach
14432 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
14433 	 *
14434 	 * The 3rd case is the HBA (adp) always return enabled on
14435 	 * scsi_ifgetgetcap even when it's not enable, the best approach
14436 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
14437 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
14438 	 */
14439 
14440 	if (un->un_f_is_fibre == TRUE) {
14441 		un->un_f_arq_enabled = TRUE;
14442 	} else {
14443 #if defined(__i386) || defined(__amd64)
14444 		/*
14445 		 * Circumvent the Adaptec bug, remove this code when
14446 		 * the bug is fixed
14447 		 */
14448 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
14449 #endif
14450 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
14451 		case 0:
14452 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14453 			    "sd_alloc_rqs: HBA supports ARQ\n");
14454 			/*
14455 			 * ARQ is supported by this HBA but currently is not
14456 			 * enabled. Attempt to enable it and if successful then
14457 			 * mark this instance as ARQ enabled.
14458 			 */
14459 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
14460 			    == 1) {
14461 				/* Successfully enabled ARQ in the HBA */
14462 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14463 				    "sd_alloc_rqs: ARQ enabled\n");
14464 				un->un_f_arq_enabled = TRUE;
14465 			} else {
14466 				/* Could not enable ARQ in the HBA */
14467 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14468 				    "sd_alloc_rqs: failed ARQ enable\n");
14469 				un->un_f_arq_enabled = FALSE;
14470 			}
14471 			break;
14472 		case 1:
14473 			/*
14474 			 * ARQ is supported by this HBA and is already enabled.
14475 			 * Just mark ARQ as enabled for this instance.
14476 			 */
14477 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14478 			    "sd_alloc_rqs: ARQ already enabled\n");
14479 			un->un_f_arq_enabled = TRUE;
14480 			break;
14481 		default:
14482 			/*
14483 			 * ARQ is not supported by this HBA; disable it for this
14484 			 * instance.
14485 			 */
14486 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14487 			    "sd_alloc_rqs: HBA does not support ARQ\n");
14488 			un->un_f_arq_enabled = FALSE;
14489 			break;
14490 		}
14491 	}
14492 
14493 	return (DDI_SUCCESS);
14494 }
14495 
14496 
14497 /*
14498  *    Function: sd_free_rqs
14499  *
14500  * Description: Cleanup for the pre-instance RQS command.
14501  *
14502  *     Context: Kernel thread context
14503  */
14504 
14505 static void
14506 sd_free_rqs(struct sd_lun *un)
14507 {
14508 	ASSERT(un != NULL);
14509 
14510 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
14511 
14512 	/*
14513 	 * If consistent memory is bound to a scsi_pkt, the pkt
14514 	 * has to be destroyed *before* freeing the consistent memory.
14515 	 * Don't change the sequence of this operations.
14516 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
14517 	 * after it was freed in scsi_free_consistent_buf().
14518 	 */
14519 	if (un->un_rqs_pktp != NULL) {
14520 		scsi_destroy_pkt(un->un_rqs_pktp);
14521 		un->un_rqs_pktp = NULL;
14522 	}
14523 
14524 	if (un->un_rqs_bp != NULL) {
14525 		kmem_free(SD_GET_XBUF(un->un_rqs_bp), sizeof (struct sd_xbuf));
14526 		scsi_free_consistent_buf(un->un_rqs_bp);
14527 		un->un_rqs_bp = NULL;
14528 	}
14529 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
14530 }
14531 
14532 
14533 
14534 /*
14535  *    Function: sd_reduce_throttle
14536  *
14537  * Description: Reduces the maximum # of outstanding commands on a
14538  *		target to the current number of outstanding commands.
14539  *		Queues a tiemout(9F) callback to restore the limit
14540  *		after a specified interval has elapsed.
14541  *		Typically used when we get a TRAN_BUSY return code
14542  *		back from scsi_transport().
14543  *
14544  *   Arguments: un - ptr to the sd_lun softstate struct
14545  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
14546  *
14547  *     Context: May be called from interrupt context
14548  */
14549 
14550 static void
14551 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
14552 {
14553 	ASSERT(un != NULL);
14554 	ASSERT(mutex_owned(SD_MUTEX(un)));
14555 	ASSERT(un->un_ncmds_in_transport >= 0);
14556 
14557 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14558 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
14559 	    un, un->un_throttle, un->un_ncmds_in_transport);
14560 
14561 	if (un->un_throttle > 1) {
14562 		if (un->un_f_use_adaptive_throttle == TRUE) {
14563 			switch (throttle_type) {
14564 			case SD_THROTTLE_TRAN_BUSY:
14565 				if (un->un_busy_throttle == 0) {
14566 					un->un_busy_throttle = un->un_throttle;
14567 				}
14568 				break;
14569 			case SD_THROTTLE_QFULL:
14570 				un->un_busy_throttle = 0;
14571 				break;
14572 			default:
14573 				ASSERT(FALSE);
14574 			}
14575 
14576 			if (un->un_ncmds_in_transport > 0) {
14577 				un->un_throttle = un->un_ncmds_in_transport;
14578 			}
14579 
14580 		} else {
14581 			if (un->un_ncmds_in_transport == 0) {
14582 				un->un_throttle = 1;
14583 			} else {
14584 				un->un_throttle = un->un_ncmds_in_transport;
14585 			}
14586 		}
14587 	}
14588 
14589 	/* Reschedule the timeout if none is currently active */
14590 	if (un->un_reset_throttle_timeid == NULL) {
14591 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
14592 		    un, SD_THROTTLE_RESET_INTERVAL);
14593 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14594 		    "sd_reduce_throttle: timeout scheduled!\n");
14595 	}
14596 
14597 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14598 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14599 }
14600 
14601 
14602 
14603 /*
14604  *    Function: sd_restore_throttle
14605  *
14606  * Description: Callback function for timeout(9F).  Resets the current
14607  *		value of un->un_throttle to its default.
14608  *
14609  *   Arguments: arg - pointer to associated softstate for the device.
14610  *
14611  *     Context: May be called from interrupt context
14612  */
14613 
14614 static void
14615 sd_restore_throttle(void *arg)
14616 {
14617 	struct sd_lun	*un = arg;
14618 
14619 	ASSERT(un != NULL);
14620 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14621 
14622 	mutex_enter(SD_MUTEX(un));
14623 
14624 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14625 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14626 
14627 	un->un_reset_throttle_timeid = NULL;
14628 
14629 	if (un->un_f_use_adaptive_throttle == TRUE) {
14630 		/*
14631 		 * If un_busy_throttle is nonzero, then it contains the
14632 		 * value that un_throttle was when we got a TRAN_BUSY back
14633 		 * from scsi_transport(). We want to revert back to this
14634 		 * value.
14635 		 *
14636 		 * In the QFULL case, the throttle limit will incrementally
14637 		 * increase until it reaches max throttle.
14638 		 */
14639 		if (un->un_busy_throttle > 0) {
14640 			un->un_throttle = un->un_busy_throttle;
14641 			un->un_busy_throttle = 0;
14642 		} else {
14643 			/*
14644 			 * increase throttle by 10% open gate slowly, schedule
14645 			 * another restore if saved throttle has not been
14646 			 * reached
14647 			 */
14648 			short throttle;
14649 			if (sd_qfull_throttle_enable) {
14650 				throttle = un->un_throttle +
14651 				    max((un->un_throttle / 10), 1);
14652 				un->un_throttle =
14653 				    (throttle < un->un_saved_throttle) ?
14654 				    throttle : un->un_saved_throttle;
14655 				if (un->un_throttle < un->un_saved_throttle) {
14656 					un->un_reset_throttle_timeid =
14657 					    timeout(sd_restore_throttle,
14658 					    un,
14659 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
14660 				}
14661 			}
14662 		}
14663 
14664 		/*
14665 		 * If un_throttle has fallen below the low-water mark, we
14666 		 * restore the maximum value here (and allow it to ratchet
14667 		 * down again if necessary).
14668 		 */
14669 		if (un->un_throttle < un->un_min_throttle) {
14670 			un->un_throttle = un->un_saved_throttle;
14671 		}
14672 	} else {
14673 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14674 		    "restoring limit from 0x%x to 0x%x\n",
14675 		    un->un_throttle, un->un_saved_throttle);
14676 		un->un_throttle = un->un_saved_throttle;
14677 	}
14678 
14679 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14680 	    "sd_restore_throttle: calling sd_start_cmds!\n");
14681 
14682 	sd_start_cmds(un, NULL);
14683 
14684 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14685 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
14686 	    un, un->un_throttle);
14687 
14688 	mutex_exit(SD_MUTEX(un));
14689 
14690 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
14691 }
14692 
14693 /*
14694  *    Function: sdrunout
14695  *
14696  * Description: Callback routine for scsi_init_pkt when a resource allocation
14697  *		fails.
14698  *
14699  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
14700  *		soft state instance.
14701  *
14702  * Return Code: The scsi_init_pkt routine allows for the callback function to
14703  *		return a 0 indicating the callback should be rescheduled or a 1
14704  *		indicating not to reschedule. This routine always returns 1
14705  *		because the driver always provides a callback function to
14706  *		scsi_init_pkt. This results in a callback always being scheduled
14707  *		(via the scsi_init_pkt callback implementation) if a resource
14708  *		failure occurs.
14709  *
14710  *     Context: This callback function may not block or call routines that block
14711  *
14712  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
14713  *		request persisting at the head of the list which cannot be
14714  *		satisfied even after multiple retries. In the future the driver
14715  *		may implement some time of maximum runout count before failing
14716  *		an I/O.
14717  */
14718 
14719 static int
14720 sdrunout(caddr_t arg)
14721 {
14722 	struct sd_lun	*un = (struct sd_lun *)arg;
14723 
14724 	ASSERT(un != NULL);
14725 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14726 
14727 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
14728 
14729 	mutex_enter(SD_MUTEX(un));
14730 	sd_start_cmds(un, NULL);
14731 	mutex_exit(SD_MUTEX(un));
14732 	/*
14733 	 * This callback routine always returns 1 (i.e. do not reschedule)
14734 	 * because we always specify sdrunout as the callback handler for
14735 	 * scsi_init_pkt inside the call to sd_start_cmds.
14736 	 */
14737 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
14738 	return (1);
14739 }
14740 
14741 
14742 /*
14743  *    Function: sdintr
14744  *
14745  * Description: Completion callback routine for scsi_pkt(9S) structs
14746  *		sent to the HBA driver via scsi_transport(9F).
14747  *
14748  *     Context: Interrupt context
14749  */
14750 
14751 static void
14752 sdintr(struct scsi_pkt *pktp)
14753 {
14754 	struct buf	*bp;
14755 	struct sd_xbuf	*xp;
14756 	struct sd_lun	*un;
14757 
14758 	ASSERT(pktp != NULL);
14759 	bp = (struct buf *)pktp->pkt_private;
14760 	ASSERT(bp != NULL);
14761 	xp = SD_GET_XBUF(bp);
14762 	ASSERT(xp != NULL);
14763 	ASSERT(xp->xb_pktp != NULL);
14764 	un = SD_GET_UN(bp);
14765 	ASSERT(un != NULL);
14766 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14767 
14768 #ifdef SD_FAULT_INJECTION
14769 
14770 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
14771 	/* SD FaultInjection */
14772 	sd_faultinjection(pktp);
14773 
14774 #endif /* SD_FAULT_INJECTION */
14775 
14776 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
14777 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
14778 
14779 	mutex_enter(SD_MUTEX(un));
14780 
14781 	/* Reduce the count of the #commands currently in transport */
14782 	un->un_ncmds_in_transport--;
14783 	ASSERT(un->un_ncmds_in_transport >= 0);
14784 
14785 	/* Increment counter to indicate that the callback routine is active */
14786 	un->un_in_callback++;
14787 
14788 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14789 
14790 #ifdef	SDDEBUG
14791 	if (bp == un->un_retry_bp) {
14792 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
14793 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
14794 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
14795 	}
14796 #endif
14797 
14798 	/*
14799 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
14800 	 * state if needed.
14801 	 */
14802 	if (pktp->pkt_reason == CMD_DEV_GONE) {
14803 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
14804 		    "Device is gone\n");
14805 		if (un->un_mediastate != DKIO_DEV_GONE) {
14806 			un->un_mediastate = DKIO_DEV_GONE;
14807 			cv_broadcast(&un->un_state_cv);
14808 		}
14809 		sd_return_failed_command(un, bp, EIO);
14810 		goto exit;
14811 	}
14812 
14813 	/*
14814 	 * First see if the pkt has auto-request sense data with it....
14815 	 * Look at the packet state first so we don't take a performance
14816 	 * hit looking at the arq enabled flag unless absolutely necessary.
14817 	 */
14818 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
14819 	    (un->un_f_arq_enabled == TRUE)) {
14820 		/*
14821 		 * The HBA did an auto request sense for this command so check
14822 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
14823 		 * driver command that should not be retried.
14824 		 */
14825 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
14826 			/*
14827 			 * Save the relevant sense info into the xp for the
14828 			 * original cmd.
14829 			 */
14830 			struct scsi_arq_status *asp;
14831 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
14832 			xp->xb_sense_status =
14833 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
14834 			xp->xb_sense_state  = asp->sts_rqpkt_state;
14835 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
14836 			bcopy(&asp->sts_sensedata, xp->xb_sense_data,
14837 			    min(sizeof (struct scsi_extended_sense),
14838 			    SENSE_LENGTH));
14839 
14840 			/* fail the command */
14841 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14842 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
14843 			sd_return_failed_command(un, bp, EIO);
14844 			goto exit;
14845 		}
14846 
14847 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
14848 		/*
14849 		 * We want to either retry or fail this command, so free
14850 		 * the DMA resources here.  If we retry the command then
14851 		 * the DMA resources will be reallocated in sd_start_cmds().
14852 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
14853 		 * causes the *entire* transfer to start over again from the
14854 		 * beginning of the request, even for PARTIAL chunks that
14855 		 * have already transferred successfully.
14856 		 */
14857 		if ((un->un_f_is_fibre == TRUE) &&
14858 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14859 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
14860 			scsi_dmafree(pktp);
14861 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
14862 		}
14863 #endif
14864 
14865 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14866 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
14867 
14868 		sd_handle_auto_request_sense(un, bp, xp, pktp);
14869 		goto exit;
14870 	}
14871 
14872 	/* Next see if this is the REQUEST SENSE pkt for the instance */
14873 	if (pktp->pkt_flags & FLAG_SENSING)  {
14874 		/* This pktp is from the unit's REQUEST_SENSE command */
14875 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14876 		    "sdintr: sd_handle_request_sense\n");
14877 		sd_handle_request_sense(un, bp, xp, pktp);
14878 		goto exit;
14879 	}
14880 
14881 	/*
14882 	 * Check to see if the command successfully completed as requested;
14883 	 * this is the most common case (and also the hot performance path).
14884 	 *
14885 	 * Requirements for successful completion are:
14886 	 * pkt_reason is CMD_CMPLT and packet status is status good.
14887 	 * In addition:
14888 	 * - A residual of zero indicates successful completion no matter what
14889 	 *   the command is.
14890 	 * - If the residual is not zero and the command is not a read or
14891 	 *   write, then it's still defined as successful completion. In other
14892 	 *   words, if the command is a read or write the residual must be
14893 	 *   zero for successful completion.
14894 	 * - If the residual is not zero and the command is a read or
14895 	 *   write, and it's a USCSICMD, then it's still defined as
14896 	 *   successful completion.
14897 	 */
14898 	if ((pktp->pkt_reason == CMD_CMPLT) &&
14899 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
14900 
14901 		/*
14902 		 * Since this command is returned with a good status, we
14903 		 * can reset the count for Sonoma failover.
14904 		 */
14905 		un->un_sonoma_failure_count = 0;
14906 
14907 		/*
14908 		 * Return all USCSI commands on good status
14909 		 */
14910 		if (pktp->pkt_resid == 0) {
14911 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14912 			    "sdintr: returning command for resid == 0\n");
14913 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
14914 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
14915 			SD_UPDATE_B_RESID(bp, pktp);
14916 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14917 			    "sdintr: returning command for resid != 0\n");
14918 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
14919 			SD_UPDATE_B_RESID(bp, pktp);
14920 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14921 			    "sdintr: returning uscsi command\n");
14922 		} else {
14923 			goto not_successful;
14924 		}
14925 		sd_return_command(un, bp);
14926 
14927 		/*
14928 		 * Decrement counter to indicate that the callback routine
14929 		 * is done.
14930 		 */
14931 		un->un_in_callback--;
14932 		ASSERT(un->un_in_callback >= 0);
14933 		mutex_exit(SD_MUTEX(un));
14934 
14935 		return;
14936 	}
14937 
14938 not_successful:
14939 
14940 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
14941 	/*
14942 	 * The following is based upon knowledge of the underlying transport
14943 	 * and its use of DMA resources.  This code should be removed when
14944 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
14945 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
14946 	 * and sd_start_cmds().
14947 	 *
14948 	 * Free any DMA resources associated with this command if there
14949 	 * is a chance it could be retried or enqueued for later retry.
14950 	 * If we keep the DMA binding then mpxio cannot reissue the
14951 	 * command on another path whenever a path failure occurs.
14952 	 *
14953 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
14954 	 * causes the *entire* transfer to start over again from the
14955 	 * beginning of the request, even for PARTIAL chunks that
14956 	 * have already transferred successfully.
14957 	 *
14958 	 * This is only done for non-uscsi commands (and also skipped for the
14959 	 * driver's internal RQS command). Also just do this for Fibre Channel
14960 	 * devices as these are the only ones that support mpxio.
14961 	 */
14962 	if ((un->un_f_is_fibre == TRUE) &&
14963 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14964 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
14965 		scsi_dmafree(pktp);
14966 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
14967 	}
14968 #endif
14969 
14970 	/*
14971 	 * The command did not successfully complete as requested so check
14972 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
14973 	 * driver command that should not be retried so just return. If
14974 	 * FLAG_DIAGNOSE is not set the error will be processed below.
14975 	 */
14976 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
14977 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14978 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
14979 		/*
14980 		 * Issue a request sense if a check condition caused the error
14981 		 * (we handle the auto request sense case above), otherwise
14982 		 * just fail the command.
14983 		 */
14984 		if ((pktp->pkt_reason == CMD_CMPLT) &&
14985 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
14986 			sd_send_request_sense_command(un, bp, pktp);
14987 		} else {
14988 			sd_return_failed_command(un, bp, EIO);
14989 		}
14990 		goto exit;
14991 	}
14992 
14993 	/*
14994 	 * The command did not successfully complete as requested so process
14995 	 * the error, retry, and/or attempt recovery.
14996 	 */
14997 	switch (pktp->pkt_reason) {
14998 	case CMD_CMPLT:
14999 		switch (SD_GET_PKT_STATUS(pktp)) {
15000 		case STATUS_GOOD:
15001 			/*
15002 			 * The command completed successfully with a non-zero
15003 			 * residual
15004 			 */
15005 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15006 			    "sdintr: STATUS_GOOD \n");
15007 			sd_pkt_status_good(un, bp, xp, pktp);
15008 			break;
15009 
15010 		case STATUS_CHECK:
15011 		case STATUS_TERMINATED:
15012 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15013 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
15014 			sd_pkt_status_check_condition(un, bp, xp, pktp);
15015 			break;
15016 
15017 		case STATUS_BUSY:
15018 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15019 			    "sdintr: STATUS_BUSY\n");
15020 			sd_pkt_status_busy(un, bp, xp, pktp);
15021 			break;
15022 
15023 		case STATUS_RESERVATION_CONFLICT:
15024 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15025 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
15026 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
15027 			break;
15028 
15029 		case STATUS_QFULL:
15030 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15031 			    "sdintr: STATUS_QFULL\n");
15032 			sd_pkt_status_qfull(un, bp, xp, pktp);
15033 			break;
15034 
15035 		case STATUS_MET:
15036 		case STATUS_INTERMEDIATE:
15037 		case STATUS_SCSI2:
15038 		case STATUS_INTERMEDIATE_MET:
15039 		case STATUS_ACA_ACTIVE:
15040 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
15041 			    "Unexpected SCSI status received: 0x%x\n",
15042 			    SD_GET_PKT_STATUS(pktp));
15043 			sd_return_failed_command(un, bp, EIO);
15044 			break;
15045 
15046 		default:
15047 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
15048 			    "Invalid SCSI status received: 0x%x\n",
15049 			    SD_GET_PKT_STATUS(pktp));
15050 			sd_return_failed_command(un, bp, EIO);
15051 			break;
15052 
15053 		}
15054 		break;
15055 
15056 	case CMD_INCOMPLETE:
15057 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15058 		    "sdintr:  CMD_INCOMPLETE\n");
15059 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
15060 		break;
15061 	case CMD_TRAN_ERR:
15062 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15063 		    "sdintr: CMD_TRAN_ERR\n");
15064 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
15065 		break;
15066 	case CMD_RESET:
15067 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15068 		    "sdintr: CMD_RESET \n");
15069 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
15070 		break;
15071 	case CMD_ABORTED:
15072 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15073 		    "sdintr: CMD_ABORTED \n");
15074 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
15075 		break;
15076 	case CMD_TIMEOUT:
15077 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15078 		    "sdintr: CMD_TIMEOUT\n");
15079 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
15080 		break;
15081 	case CMD_UNX_BUS_FREE:
15082 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15083 		    "sdintr: CMD_UNX_BUS_FREE \n");
15084 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
15085 		break;
15086 	case CMD_TAG_REJECT:
15087 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15088 		    "sdintr: CMD_TAG_REJECT\n");
15089 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
15090 		break;
15091 	default:
15092 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15093 		    "sdintr: default\n");
15094 		sd_pkt_reason_default(un, bp, xp, pktp);
15095 		break;
15096 	}
15097 
15098 exit:
15099 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
15100 
15101 	/* Decrement counter to indicate that the callback routine is done. */
15102 	un->un_in_callback--;
15103 	ASSERT(un->un_in_callback >= 0);
15104 
15105 	/*
15106 	 * At this point, the pkt has been dispatched, ie, it is either
15107 	 * being re-tried or has been returned to its caller and should
15108 	 * not be referenced.
15109 	 */
15110 
15111 	mutex_exit(SD_MUTEX(un));
15112 }
15113 
15114 
15115 /*
15116  *    Function: sd_print_incomplete_msg
15117  *
15118  * Description: Prints the error message for a CMD_INCOMPLETE error.
15119  *
15120  *   Arguments: un - ptr to associated softstate for the device.
15121  *		bp - ptr to the buf(9S) for the command.
15122  *		arg - message string ptr
15123  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
15124  *			or SD_NO_RETRY_ISSUED.
15125  *
15126  *     Context: May be called under interrupt context
15127  */
15128 
15129 static void
15130 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
15131 {
15132 	struct scsi_pkt	*pktp;
15133 	char	*msgp;
15134 	char	*cmdp = arg;
15135 
15136 	ASSERT(un != NULL);
15137 	ASSERT(mutex_owned(SD_MUTEX(un)));
15138 	ASSERT(bp != NULL);
15139 	ASSERT(arg != NULL);
15140 	pktp = SD_GET_PKTP(bp);
15141 	ASSERT(pktp != NULL);
15142 
15143 	switch (code) {
15144 	case SD_DELAYED_RETRY_ISSUED:
15145 	case SD_IMMEDIATE_RETRY_ISSUED:
15146 		msgp = "retrying";
15147 		break;
15148 	case SD_NO_RETRY_ISSUED:
15149 	default:
15150 		msgp = "giving up";
15151 		break;
15152 	}
15153 
15154 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
15155 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15156 		    "incomplete %s- %s\n", cmdp, msgp);
15157 	}
15158 }
15159 
15160 
15161 
15162 /*
15163  *    Function: sd_pkt_status_good
15164  *
15165  * Description: Processing for a STATUS_GOOD code in pkt_status.
15166  *
15167  *     Context: May be called under interrupt context
15168  */
15169 
15170 static void
15171 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
15172 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15173 {
15174 	char	*cmdp;
15175 
15176 	ASSERT(un != NULL);
15177 	ASSERT(mutex_owned(SD_MUTEX(un)));
15178 	ASSERT(bp != NULL);
15179 	ASSERT(xp != NULL);
15180 	ASSERT(pktp != NULL);
15181 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
15182 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
15183 	ASSERT(pktp->pkt_resid != 0);
15184 
15185 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
15186 
15187 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
15188 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
15189 	case SCMD_READ:
15190 		cmdp = "read";
15191 		break;
15192 	case SCMD_WRITE:
15193 		cmdp = "write";
15194 		break;
15195 	default:
15196 		SD_UPDATE_B_RESID(bp, pktp);
15197 		sd_return_command(un, bp);
15198 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15199 		return;
15200 	}
15201 
15202 	/*
15203 	 * See if we can retry the read/write, preferrably immediately.
15204 	 * If retries are exhaused, then sd_retry_command() will update
15205 	 * the b_resid count.
15206 	 */
15207 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
15208 	    cmdp, EIO, (clock_t)0, NULL);
15209 
15210 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15211 }
15212 
15213 
15214 
15215 
15216 
15217 /*
15218  *    Function: sd_handle_request_sense
15219  *
15220  * Description: Processing for non-auto Request Sense command.
15221  *
15222  *   Arguments: un - ptr to associated softstate
15223  *		sense_bp - ptr to buf(9S) for the RQS command
15224  *		sense_xp - ptr to the sd_xbuf for the RQS command
15225  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
15226  *
15227  *     Context: May be called under interrupt context
15228  */
15229 
15230 static void
15231 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
15232 	struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
15233 {
15234 	struct buf	*cmd_bp;	/* buf for the original command */
15235 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
15236 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
15237 
15238 	ASSERT(un != NULL);
15239 	ASSERT(mutex_owned(SD_MUTEX(un)));
15240 	ASSERT(sense_bp != NULL);
15241 	ASSERT(sense_xp != NULL);
15242 	ASSERT(sense_pktp != NULL);
15243 
15244 	/*
15245 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
15246 	 * RQS command and not the original command.
15247 	 */
15248 	ASSERT(sense_pktp == un->un_rqs_pktp);
15249 	ASSERT(sense_bp   == un->un_rqs_bp);
15250 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
15251 	    (FLAG_SENSING | FLAG_HEAD));
15252 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
15253 	    FLAG_SENSING) == FLAG_SENSING);
15254 
15255 	/* These are the bp, xp, and pktp for the original command */
15256 	cmd_bp = sense_xp->xb_sense_bp;
15257 	cmd_xp = SD_GET_XBUF(cmd_bp);
15258 	cmd_pktp = SD_GET_PKTP(cmd_bp);
15259 
15260 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
15261 		/*
15262 		 * The REQUEST SENSE command failed.  Release the REQUEST
15263 		 * SENSE command for re-use, get back the bp for the original
15264 		 * command, and attempt to re-try the original command if
15265 		 * FLAG_DIAGNOSE is not set in the original packet.
15266 		 */
15267 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
15268 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15269 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
15270 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
15271 			    NULL, NULL, EIO, (clock_t)0, NULL);
15272 			return;
15273 		}
15274 	}
15275 
15276 	/*
15277 	 * Save the relevant sense info into the xp for the original cmd.
15278 	 *
15279 	 * Note: if the request sense failed the state info will be zero
15280 	 * as set in sd_mark_rqs_busy()
15281 	 */
15282 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
15283 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
15284 	cmd_xp->xb_sense_resid  = sense_pktp->pkt_resid;
15285 	bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data, SENSE_LENGTH);
15286 
15287 	/*
15288 	 *  Free up the RQS command....
15289 	 *  NOTE:
15290 	 *	Must do this BEFORE calling sd_validate_sense_data!
15291 	 *	sd_validate_sense_data may return the original command in
15292 	 *	which case the pkt will be freed and the flags can no
15293 	 *	longer be touched.
15294 	 *	SD_MUTEX is held through this process until the command
15295 	 *	is dispatched based upon the sense data, so there are
15296 	 *	no race conditions.
15297 	 */
15298 	(void) sd_mark_rqs_idle(un, sense_xp);
15299 
15300 	/*
15301 	 * For a retryable command see if we have valid sense data, if so then
15302 	 * turn it over to sd_decode_sense() to figure out the right course of
15303 	 * action. Just fail a non-retryable command.
15304 	 */
15305 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15306 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp) ==
15307 		    SD_SENSE_DATA_IS_VALID) {
15308 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
15309 		}
15310 	} else {
15311 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
15312 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15313 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
15314 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15315 		sd_return_failed_command(un, cmd_bp, EIO);
15316 	}
15317 }
15318 
15319 
15320 
15321 
15322 /*
15323  *    Function: sd_handle_auto_request_sense
15324  *
15325  * Description: Processing for auto-request sense information.
15326  *
15327  *   Arguments: un - ptr to associated softstate
15328  *		bp - ptr to buf(9S) for the command
15329  *		xp - ptr to the sd_xbuf for the command
15330  *		pktp - ptr to the scsi_pkt(9S) for the command
15331  *
15332  *     Context: May be called under interrupt context
15333  */
15334 
15335 static void
15336 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
15337 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15338 {
15339 	struct scsi_arq_status *asp;
15340 
15341 	ASSERT(un != NULL);
15342 	ASSERT(mutex_owned(SD_MUTEX(un)));
15343 	ASSERT(bp != NULL);
15344 	ASSERT(xp != NULL);
15345 	ASSERT(pktp != NULL);
15346 	ASSERT(pktp != un->un_rqs_pktp);
15347 	ASSERT(bp   != un->un_rqs_bp);
15348 
15349 	/*
15350 	 * For auto-request sense, we get a scsi_arq_status back from
15351 	 * the HBA, with the sense data in the sts_sensedata member.
15352 	 * The pkt_scbp of the packet points to this scsi_arq_status.
15353 	 */
15354 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
15355 
15356 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
15357 		/*
15358 		 * The auto REQUEST SENSE failed; see if we can re-try
15359 		 * the original command.
15360 		 */
15361 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15362 		    "auto request sense failed (reason=%s)\n",
15363 		    scsi_rname(asp->sts_rqpkt_reason));
15364 
15365 		sd_reset_target(un, pktp);
15366 
15367 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15368 		    NULL, NULL, EIO, (clock_t)0, NULL);
15369 		return;
15370 	}
15371 
15372 	/* Save the relevant sense info into the xp for the original cmd. */
15373 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
15374 	xp->xb_sense_state  = asp->sts_rqpkt_state;
15375 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
15376 	bcopy(&asp->sts_sensedata, xp->xb_sense_data,
15377 	    min(sizeof (struct scsi_extended_sense), SENSE_LENGTH));
15378 
15379 	/*
15380 	 * See if we have valid sense data, if so then turn it over to
15381 	 * sd_decode_sense() to figure out the right course of action.
15382 	 */
15383 	if (sd_validate_sense_data(un, bp, xp) == SD_SENSE_DATA_IS_VALID) {
15384 		sd_decode_sense(un, bp, xp, pktp);
15385 	}
15386 }
15387 
15388 
15389 /*
15390  *    Function: sd_print_sense_failed_msg
15391  *
15392  * Description: Print log message when RQS has failed.
15393  *
15394  *   Arguments: un - ptr to associated softstate
15395  *		bp - ptr to buf(9S) for the command
15396  *		arg - generic message string ptr
15397  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15398  *			or SD_NO_RETRY_ISSUED
15399  *
15400  *     Context: May be called from interrupt context
15401  */
15402 
15403 static void
15404 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
15405 	int code)
15406 {
15407 	char	*msgp = arg;
15408 
15409 	ASSERT(un != NULL);
15410 	ASSERT(mutex_owned(SD_MUTEX(un)));
15411 	ASSERT(bp != NULL);
15412 
15413 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
15414 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
15415 	}
15416 }
15417 
15418 
15419 /*
15420  *    Function: sd_validate_sense_data
15421  *
15422  * Description: Check the given sense data for validity.
15423  *		If the sense data is not valid, the command will
15424  *		be either failed or retried!
15425  *
15426  * Return Code: SD_SENSE_DATA_IS_INVALID
15427  *		SD_SENSE_DATA_IS_VALID
15428  *
15429  *     Context: May be called from interrupt context
15430  */
15431 
15432 static int
15433 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp)
15434 {
15435 	struct scsi_extended_sense *esp;
15436 	struct	scsi_pkt *pktp;
15437 	size_t	actual_len;
15438 	char	*msgp = NULL;
15439 
15440 	ASSERT(un != NULL);
15441 	ASSERT(mutex_owned(SD_MUTEX(un)));
15442 	ASSERT(bp != NULL);
15443 	ASSERT(bp != un->un_rqs_bp);
15444 	ASSERT(xp != NULL);
15445 
15446 	pktp = SD_GET_PKTP(bp);
15447 	ASSERT(pktp != NULL);
15448 
15449 	/*
15450 	 * Check the status of the RQS command (auto or manual).
15451 	 */
15452 	switch (xp->xb_sense_status & STATUS_MASK) {
15453 	case STATUS_GOOD:
15454 		break;
15455 
15456 	case STATUS_RESERVATION_CONFLICT:
15457 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
15458 		return (SD_SENSE_DATA_IS_INVALID);
15459 
15460 	case STATUS_BUSY:
15461 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15462 		    "Busy Status on REQUEST SENSE\n");
15463 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
15464 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15465 		return (SD_SENSE_DATA_IS_INVALID);
15466 
15467 	case STATUS_QFULL:
15468 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15469 		    "QFULL Status on REQUEST SENSE\n");
15470 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
15471 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15472 		return (SD_SENSE_DATA_IS_INVALID);
15473 
15474 	case STATUS_CHECK:
15475 	case STATUS_TERMINATED:
15476 		msgp = "Check Condition on REQUEST SENSE\n";
15477 		goto sense_failed;
15478 
15479 	default:
15480 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
15481 		goto sense_failed;
15482 	}
15483 
15484 	/*
15485 	 * See if we got the minimum required amount of sense data.
15486 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
15487 	 * or less.
15488 	 */
15489 	actual_len = (int)(SENSE_LENGTH - xp->xb_sense_resid);
15490 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
15491 	    (actual_len == 0)) {
15492 		msgp = "Request Sense couldn't get sense data\n";
15493 		goto sense_failed;
15494 	}
15495 
15496 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
15497 		msgp = "Not enough sense information\n";
15498 		goto sense_failed;
15499 	}
15500 
15501 	/*
15502 	 * We require the extended sense data
15503 	 */
15504 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
15505 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
15506 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
15507 			static char tmp[8];
15508 			static char buf[148];
15509 			char *p = (char *)(xp->xb_sense_data);
15510 			int i;
15511 
15512 			mutex_enter(&sd_sense_mutex);
15513 			(void) strcpy(buf, "undecodable sense information:");
15514 			for (i = 0; i < actual_len; i++) {
15515 				(void) sprintf(tmp, " 0x%x", *(p++)&0xff);
15516 				(void) strcpy(&buf[strlen(buf)], tmp);
15517 			}
15518 			i = strlen(buf);
15519 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
15520 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, buf);
15521 			mutex_exit(&sd_sense_mutex);
15522 		}
15523 		/* Note: Legacy behavior, fail the command with no retry */
15524 		sd_return_failed_command(un, bp, EIO);
15525 		return (SD_SENSE_DATA_IS_INVALID);
15526 	}
15527 
15528 	/*
15529 	 * Check that es_code is valid (es_class concatenated with es_code
15530 	 * make up the "response code" field.  es_class will always be 7, so
15531 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
15532 	 * format.
15533 	 */
15534 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
15535 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
15536 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
15537 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
15538 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
15539 		goto sense_failed;
15540 	}
15541 
15542 	return (SD_SENSE_DATA_IS_VALID);
15543 
15544 sense_failed:
15545 	/*
15546 	 * If the request sense failed (for whatever reason), attempt
15547 	 * to retry the original command.
15548 	 */
15549 #if defined(__i386) || defined(__amd64)
15550 	/*
15551 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
15552 	 * sddef.h for Sparc platform, and x86 uses 1 binary
15553 	 * for both SCSI/FC.
15554 	 * The SD_RETRY_DELAY value need to be adjusted here
15555 	 * when SD_RETRY_DELAY change in sddef.h
15556 	 */
15557 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15558 	    sd_print_sense_failed_msg, msgp, EIO,
15559 	    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0, NULL);
15560 #else
15561 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15562 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
15563 #endif
15564 
15565 	return (SD_SENSE_DATA_IS_INVALID);
15566 }
15567 
15568 
15569 
15570 /*
15571  *    Function: sd_decode_sense
15572  *
15573  * Description: Take recovery action(s) when SCSI Sense Data is received.
15574  *
15575  *     Context: Interrupt context.
15576  */
15577 
15578 static void
15579 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
15580 	struct scsi_pkt *pktp)
15581 {
15582 	uint8_t sense_key;
15583 
15584 	ASSERT(un != NULL);
15585 	ASSERT(mutex_owned(SD_MUTEX(un)));
15586 	ASSERT(bp != NULL);
15587 	ASSERT(bp != un->un_rqs_bp);
15588 	ASSERT(xp != NULL);
15589 	ASSERT(pktp != NULL);
15590 
15591 	sense_key = scsi_sense_key(xp->xb_sense_data);
15592 
15593 	switch (sense_key) {
15594 	case KEY_NO_SENSE:
15595 		sd_sense_key_no_sense(un, bp, xp, pktp);
15596 		break;
15597 	case KEY_RECOVERABLE_ERROR:
15598 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
15599 		    bp, xp, pktp);
15600 		break;
15601 	case KEY_NOT_READY:
15602 		sd_sense_key_not_ready(un, xp->xb_sense_data,
15603 		    bp, xp, pktp);
15604 		break;
15605 	case KEY_MEDIUM_ERROR:
15606 	case KEY_HARDWARE_ERROR:
15607 		sd_sense_key_medium_or_hardware_error(un,
15608 		    xp->xb_sense_data, bp, xp, pktp);
15609 		break;
15610 	case KEY_ILLEGAL_REQUEST:
15611 		sd_sense_key_illegal_request(un, bp, xp, pktp);
15612 		break;
15613 	case KEY_UNIT_ATTENTION:
15614 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
15615 		    bp, xp, pktp);
15616 		break;
15617 	case KEY_WRITE_PROTECT:
15618 	case KEY_VOLUME_OVERFLOW:
15619 	case KEY_MISCOMPARE:
15620 		sd_sense_key_fail_command(un, bp, xp, pktp);
15621 		break;
15622 	case KEY_BLANK_CHECK:
15623 		sd_sense_key_blank_check(un, bp, xp, pktp);
15624 		break;
15625 	case KEY_ABORTED_COMMAND:
15626 		sd_sense_key_aborted_command(un, bp, xp, pktp);
15627 		break;
15628 	case KEY_VENDOR_UNIQUE:
15629 	case KEY_COPY_ABORTED:
15630 	case KEY_EQUAL:
15631 	case KEY_RESERVED:
15632 	default:
15633 		sd_sense_key_default(un, xp->xb_sense_data,
15634 		    bp, xp, pktp);
15635 		break;
15636 	}
15637 }
15638 
15639 
15640 /*
15641  *    Function: sd_dump_memory
15642  *
15643  * Description: Debug logging routine to print the contents of a user provided
15644  *		buffer. The output of the buffer is broken up into 256 byte
15645  *		segments due to a size constraint of the scsi_log.
15646  *		implementation.
15647  *
15648  *   Arguments: un - ptr to softstate
15649  *		comp - component mask
15650  *		title - "title" string to preceed data when printed
15651  *		data - ptr to data block to be printed
15652  *		len - size of data block to be printed
15653  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
15654  *
15655  *     Context: May be called from interrupt context
15656  */
15657 
15658 #define	SD_DUMP_MEMORY_BUF_SIZE	256
15659 
15660 static char *sd_dump_format_string[] = {
15661 		" 0x%02x",
15662 		" %c"
15663 };
15664 
15665 static void
15666 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
15667     int len, int fmt)
15668 {
15669 	int	i, j;
15670 	int	avail_count;
15671 	int	start_offset;
15672 	int	end_offset;
15673 	size_t	entry_len;
15674 	char	*bufp;
15675 	char	*local_buf;
15676 	char	*format_string;
15677 
15678 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
15679 
15680 	/*
15681 	 * In the debug version of the driver, this function is called from a
15682 	 * number of places which are NOPs in the release driver.
15683 	 * The debug driver therefore has additional methods of filtering
15684 	 * debug output.
15685 	 */
15686 #ifdef SDDEBUG
15687 	/*
15688 	 * In the debug version of the driver we can reduce the amount of debug
15689 	 * messages by setting sd_error_level to something other than
15690 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
15691 	 * sd_component_mask.
15692 	 */
15693 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
15694 	    (sd_error_level != SCSI_ERR_ALL)) {
15695 		return;
15696 	}
15697 	if (((sd_component_mask & comp) == 0) ||
15698 	    (sd_error_level != SCSI_ERR_ALL)) {
15699 		return;
15700 	}
15701 #else
15702 	if (sd_error_level != SCSI_ERR_ALL) {
15703 		return;
15704 	}
15705 #endif
15706 
15707 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
15708 	bufp = local_buf;
15709 	/*
15710 	 * Available length is the length of local_buf[], minus the
15711 	 * length of the title string, minus one for the ":", minus
15712 	 * one for the newline, minus one for the NULL terminator.
15713 	 * This gives the #bytes available for holding the printed
15714 	 * values from the given data buffer.
15715 	 */
15716 	if (fmt == SD_LOG_HEX) {
15717 		format_string = sd_dump_format_string[0];
15718 	} else /* SD_LOG_CHAR */ {
15719 		format_string = sd_dump_format_string[1];
15720 	}
15721 	/*
15722 	 * Available count is the number of elements from the given
15723 	 * data buffer that we can fit into the available length.
15724 	 * This is based upon the size of the format string used.
15725 	 * Make one entry and find it's size.
15726 	 */
15727 	(void) sprintf(bufp, format_string, data[0]);
15728 	entry_len = strlen(bufp);
15729 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
15730 
15731 	j = 0;
15732 	while (j < len) {
15733 		bufp = local_buf;
15734 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
15735 		start_offset = j;
15736 
15737 		end_offset = start_offset + avail_count;
15738 
15739 		(void) sprintf(bufp, "%s:", title);
15740 		bufp += strlen(bufp);
15741 		for (i = start_offset; ((i < end_offset) && (j < len));
15742 		    i++, j++) {
15743 			(void) sprintf(bufp, format_string, data[i]);
15744 			bufp += entry_len;
15745 		}
15746 		(void) sprintf(bufp, "\n");
15747 
15748 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
15749 	}
15750 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
15751 }
15752 
15753 /*
15754  *    Function: sd_print_sense_msg
15755  *
15756  * Description: Log a message based upon the given sense data.
15757  *
15758  *   Arguments: un - ptr to associated softstate
15759  *		bp - ptr to buf(9S) for the command
15760  *		arg - ptr to associate sd_sense_info struct
15761  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15762  *			or SD_NO_RETRY_ISSUED
15763  *
15764  *     Context: May be called from interrupt context
15765  */
15766 
15767 static void
15768 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
15769 {
15770 	struct sd_xbuf	*xp;
15771 	struct scsi_pkt	*pktp;
15772 	uint8_t *sensep;
15773 	daddr_t request_blkno;
15774 	diskaddr_t err_blkno;
15775 	int severity;
15776 	int pfa_flag;
15777 	extern struct scsi_key_strings scsi_cmds[];
15778 
15779 	ASSERT(un != NULL);
15780 	ASSERT(mutex_owned(SD_MUTEX(un)));
15781 	ASSERT(bp != NULL);
15782 	xp = SD_GET_XBUF(bp);
15783 	ASSERT(xp != NULL);
15784 	pktp = SD_GET_PKTP(bp);
15785 	ASSERT(pktp != NULL);
15786 	ASSERT(arg != NULL);
15787 
15788 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
15789 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
15790 
15791 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
15792 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
15793 		severity = SCSI_ERR_RETRYABLE;
15794 	}
15795 
15796 	/* Use absolute block number for the request block number */
15797 	request_blkno = xp->xb_blkno;
15798 
15799 	/*
15800 	 * Now try to get the error block number from the sense data
15801 	 */
15802 	sensep = xp->xb_sense_data;
15803 
15804 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
15805 	    (uint64_t *)&err_blkno)) {
15806 		/*
15807 		 * We retrieved the error block number from the information
15808 		 * portion of the sense data.
15809 		 *
15810 		 * For USCSI commands we are better off using the error
15811 		 * block no. as the requested block no. (This is the best
15812 		 * we can estimate.)
15813 		 */
15814 		if ((SD_IS_BUFIO(xp) == FALSE) &&
15815 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
15816 			request_blkno = err_blkno;
15817 		}
15818 	} else {
15819 		/*
15820 		 * Without the es_valid bit set (for fixed format) or an
15821 		 * information descriptor (for descriptor format) we cannot
15822 		 * be certain of the error blkno, so just use the
15823 		 * request_blkno.
15824 		 */
15825 		err_blkno = (diskaddr_t)request_blkno;
15826 	}
15827 
15828 	/*
15829 	 * The following will log the buffer contents for the release driver
15830 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
15831 	 * level is set to verbose.
15832 	 */
15833 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
15834 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15835 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15836 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
15837 
15838 	if (pfa_flag == FALSE) {
15839 		/* This is normally only set for USCSI */
15840 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
15841 			return;
15842 		}
15843 
15844 		if ((SD_IS_BUFIO(xp) == TRUE) &&
15845 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
15846 		    (severity < sd_error_level))) {
15847 			return;
15848 		}
15849 	}
15850 
15851 	/*
15852 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
15853 	 */
15854 	if ((SD_IS_LSI(un)) &&
15855 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
15856 	    (scsi_sense_asc(sensep) == 0x94) &&
15857 	    (scsi_sense_ascq(sensep) == 0x01)) {
15858 		un->un_sonoma_failure_count++;
15859 		if (un->un_sonoma_failure_count > 1) {
15860 			return;
15861 		}
15862 	}
15863 
15864 	scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
15865 	    request_blkno, err_blkno, scsi_cmds,
15866 	    (struct scsi_extended_sense *)sensep,
15867 	    un->un_additional_codes, NULL);
15868 }
15869 
15870 /*
15871  *    Function: sd_sense_key_no_sense
15872  *
15873  * Description: Recovery action when sense data was not received.
15874  *
15875  *     Context: May be called from interrupt context
15876  */
15877 
15878 static void
15879 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
15880 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15881 {
15882 	struct sd_sense_info	si;
15883 
15884 	ASSERT(un != NULL);
15885 	ASSERT(mutex_owned(SD_MUTEX(un)));
15886 	ASSERT(bp != NULL);
15887 	ASSERT(xp != NULL);
15888 	ASSERT(pktp != NULL);
15889 
15890 	si.ssi_severity = SCSI_ERR_FATAL;
15891 	si.ssi_pfa_flag = FALSE;
15892 
15893 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
15894 
15895 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
15896 	    &si, EIO, (clock_t)0, NULL);
15897 }
15898 
15899 
15900 /*
15901  *    Function: sd_sense_key_recoverable_error
15902  *
15903  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
15904  *
15905  *     Context: May be called from interrupt context
15906  */
15907 
15908 static void
15909 sd_sense_key_recoverable_error(struct sd_lun *un,
15910 	uint8_t *sense_datap,
15911 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
15912 {
15913 	struct sd_sense_info	si;
15914 	uint8_t asc = scsi_sense_asc(sense_datap);
15915 
15916 	ASSERT(un != NULL);
15917 	ASSERT(mutex_owned(SD_MUTEX(un)));
15918 	ASSERT(bp != NULL);
15919 	ASSERT(xp != NULL);
15920 	ASSERT(pktp != NULL);
15921 
15922 	/*
15923 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
15924 	 */
15925 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
15926 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
15927 		si.ssi_severity = SCSI_ERR_INFO;
15928 		si.ssi_pfa_flag = TRUE;
15929 	} else {
15930 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
15931 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
15932 		si.ssi_severity = SCSI_ERR_RECOVERED;
15933 		si.ssi_pfa_flag = FALSE;
15934 	}
15935 
15936 	if (pktp->pkt_resid == 0) {
15937 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
15938 		sd_return_command(un, bp);
15939 		return;
15940 	}
15941 
15942 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
15943 	    &si, EIO, (clock_t)0, NULL);
15944 }
15945 
15946 
15947 
15948 
15949 /*
15950  *    Function: sd_sense_key_not_ready
15951  *
15952  * Description: Recovery actions for a SCSI "Not Ready" sense key.
15953  *
15954  *     Context: May be called from interrupt context
15955  */
15956 
15957 static void
15958 sd_sense_key_not_ready(struct sd_lun *un,
15959 	uint8_t *sense_datap,
15960 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
15961 {
15962 	struct sd_sense_info	si;
15963 	uint8_t asc = scsi_sense_asc(sense_datap);
15964 	uint8_t ascq = scsi_sense_ascq(sense_datap);
15965 
15966 	ASSERT(un != NULL);
15967 	ASSERT(mutex_owned(SD_MUTEX(un)));
15968 	ASSERT(bp != NULL);
15969 	ASSERT(xp != NULL);
15970 	ASSERT(pktp != NULL);
15971 
15972 	si.ssi_severity = SCSI_ERR_FATAL;
15973 	si.ssi_pfa_flag = FALSE;
15974 
15975 	/*
15976 	 * Update error stats after first NOT READY error. Disks may have
15977 	 * been powered down and may need to be restarted.  For CDROMs,
15978 	 * report NOT READY errors only if media is present.
15979 	 */
15980 	if ((ISCD(un) && (asc == 0x3A)) ||
15981 	    (xp->xb_nr_retry_count > 0)) {
15982 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
15983 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
15984 	}
15985 
15986 	/*
15987 	 * Just fail if the "not ready" retry limit has been reached.
15988 	 */
15989 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
15990 		/* Special check for error message printing for removables. */
15991 		if (un->un_f_has_removable_media && (asc == 0x04) &&
15992 		    (ascq >= 0x04)) {
15993 			si.ssi_severity = SCSI_ERR_ALL;
15994 		}
15995 		goto fail_command;
15996 	}
15997 
15998 	/*
15999 	 * Check the ASC and ASCQ in the sense data as needed, to determine
16000 	 * what to do.
16001 	 */
16002 	switch (asc) {
16003 	case 0x04:	/* LOGICAL UNIT NOT READY */
16004 		/*
16005 		 * disk drives that don't spin up result in a very long delay
16006 		 * in format without warning messages. We will log a message
16007 		 * if the error level is set to verbose.
16008 		 */
16009 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16010 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16011 			    "logical unit not ready, resetting disk\n");
16012 		}
16013 
16014 		/*
16015 		 * There are different requirements for CDROMs and disks for
16016 		 * the number of retries.  If a CD-ROM is giving this, it is
16017 		 * probably reading TOC and is in the process of getting
16018 		 * ready, so we should keep on trying for a long time to make
16019 		 * sure that all types of media are taken in account (for
16020 		 * some media the drive takes a long time to read TOC).  For
16021 		 * disks we do not want to retry this too many times as this
16022 		 * can cause a long hang in format when the drive refuses to
16023 		 * spin up (a very common failure).
16024 		 */
16025 		switch (ascq) {
16026 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
16027 			/*
16028 			 * Disk drives frequently refuse to spin up which
16029 			 * results in a very long hang in format without
16030 			 * warning messages.
16031 			 *
16032 			 * Note: This code preserves the legacy behavior of
16033 			 * comparing xb_nr_retry_count against zero for fibre
16034 			 * channel targets instead of comparing against the
16035 			 * un_reset_retry_count value.  The reason for this
16036 			 * discrepancy has been so utterly lost beneath the
16037 			 * Sands of Time that even Indiana Jones could not
16038 			 * find it.
16039 			 */
16040 			if (un->un_f_is_fibre == TRUE) {
16041 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
16042 				    (xp->xb_nr_retry_count > 0)) &&
16043 				    (un->un_startstop_timeid == NULL)) {
16044 					scsi_log(SD_DEVINFO(un), sd_label,
16045 					    CE_WARN, "logical unit not ready, "
16046 					    "resetting disk\n");
16047 					sd_reset_target(un, pktp);
16048 				}
16049 			} else {
16050 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
16051 				    (xp->xb_nr_retry_count >
16052 				    un->un_reset_retry_count)) &&
16053 				    (un->un_startstop_timeid == NULL)) {
16054 					scsi_log(SD_DEVINFO(un), sd_label,
16055 					    CE_WARN, "logical unit not ready, "
16056 					    "resetting disk\n");
16057 					sd_reset_target(un, pktp);
16058 				}
16059 			}
16060 			break;
16061 
16062 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
16063 			/*
16064 			 * If the target is in the process of becoming
16065 			 * ready, just proceed with the retry. This can
16066 			 * happen with CD-ROMs that take a long time to
16067 			 * read TOC after a power cycle or reset.
16068 			 */
16069 			goto do_retry;
16070 
16071 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
16072 			break;
16073 
16074 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
16075 			/*
16076 			 * Retries cannot help here so just fail right away.
16077 			 */
16078 			goto fail_command;
16079 
16080 		case 0x88:
16081 			/*
16082 			 * Vendor-unique code for T3/T4: it indicates a
16083 			 * path problem in a mutipathed config, but as far as
16084 			 * the target driver is concerned it equates to a fatal
16085 			 * error, so we should just fail the command right away
16086 			 * (without printing anything to the console). If this
16087 			 * is not a T3/T4, fall thru to the default recovery
16088 			 * action.
16089 			 * T3/T4 is FC only, don't need to check is_fibre
16090 			 */
16091 			if (SD_IS_T3(un) || SD_IS_T4(un)) {
16092 				sd_return_failed_command(un, bp, EIO);
16093 				return;
16094 			}
16095 			/* FALLTHRU */
16096 
16097 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
16098 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
16099 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
16100 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
16101 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
16102 		default:    /* Possible future codes in SCSI spec? */
16103 			/*
16104 			 * For removable-media devices, do not retry if
16105 			 * ASCQ > 2 as these result mostly from USCSI commands
16106 			 * on MMC devices issued to check status of an
16107 			 * operation initiated in immediate mode.  Also for
16108 			 * ASCQ >= 4 do not print console messages as these
16109 			 * mainly represent a user-initiated operation
16110 			 * instead of a system failure.
16111 			 */
16112 			if (un->un_f_has_removable_media) {
16113 				si.ssi_severity = SCSI_ERR_ALL;
16114 				goto fail_command;
16115 			}
16116 			break;
16117 		}
16118 
16119 		/*
16120 		 * As part of our recovery attempt for the NOT READY
16121 		 * condition, we issue a START STOP UNIT command. However
16122 		 * we want to wait for a short delay before attempting this
16123 		 * as there may still be more commands coming back from the
16124 		 * target with the check condition. To do this we use
16125 		 * timeout(9F) to call sd_start_stop_unit_callback() after
16126 		 * the delay interval expires. (sd_start_stop_unit_callback()
16127 		 * dispatches sd_start_stop_unit_task(), which will issue
16128 		 * the actual START STOP UNIT command. The delay interval
16129 		 * is one-half of the delay that we will use to retry the
16130 		 * command that generated the NOT READY condition.
16131 		 *
16132 		 * Note that we could just dispatch sd_start_stop_unit_task()
16133 		 * from here and allow it to sleep for the delay interval,
16134 		 * but then we would be tying up the taskq thread
16135 		 * uncesessarily for the duration of the delay.
16136 		 *
16137 		 * Do not issue the START STOP UNIT if the current command
16138 		 * is already a START STOP UNIT.
16139 		 */
16140 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
16141 			break;
16142 		}
16143 
16144 		/*
16145 		 * Do not schedule the timeout if one is already pending.
16146 		 */
16147 		if (un->un_startstop_timeid != NULL) {
16148 			SD_INFO(SD_LOG_ERROR, un,
16149 			    "sd_sense_key_not_ready: restart already issued to"
16150 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
16151 			    ddi_get_instance(SD_DEVINFO(un)));
16152 			break;
16153 		}
16154 
16155 		/*
16156 		 * Schedule the START STOP UNIT command, then queue the command
16157 		 * for a retry.
16158 		 *
16159 		 * Note: A timeout is not scheduled for this retry because we
16160 		 * want the retry to be serial with the START_STOP_UNIT. The
16161 		 * retry will be started when the START_STOP_UNIT is completed
16162 		 * in sd_start_stop_unit_task.
16163 		 */
16164 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
16165 		    un, SD_BSY_TIMEOUT / 2);
16166 		xp->xb_nr_retry_count++;
16167 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
16168 		return;
16169 
16170 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
16171 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16172 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16173 			    "unit does not respond to selection\n");
16174 		}
16175 		break;
16176 
16177 	case 0x3A:	/* MEDIUM NOT PRESENT */
16178 		if (sd_error_level >= SCSI_ERR_FATAL) {
16179 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16180 			    "Caddy not inserted in drive\n");
16181 		}
16182 
16183 		sr_ejected(un);
16184 		un->un_mediastate = DKIO_EJECTED;
16185 		/* The state has changed, inform the media watch routines */
16186 		cv_broadcast(&un->un_state_cv);
16187 		/* Just fail if no media is present in the drive. */
16188 		goto fail_command;
16189 
16190 	default:
16191 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16192 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
16193 			    "Unit not Ready. Additional sense code 0x%x\n",
16194 			    asc);
16195 		}
16196 		break;
16197 	}
16198 
16199 do_retry:
16200 
16201 	/*
16202 	 * Retry the command, as some targets may report NOT READY for
16203 	 * several seconds after being reset.
16204 	 */
16205 	xp->xb_nr_retry_count++;
16206 	si.ssi_severity = SCSI_ERR_RETRYABLE;
16207 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
16208 	    &si, EIO, SD_BSY_TIMEOUT, NULL);
16209 
16210 	return;
16211 
16212 fail_command:
16213 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16214 	sd_return_failed_command(un, bp, EIO);
16215 }
16216 
16217 
16218 
16219 /*
16220  *    Function: sd_sense_key_medium_or_hardware_error
16221  *
16222  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
16223  *		sense key.
16224  *
16225  *     Context: May be called from interrupt context
16226  */
16227 
16228 static void
16229 sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
16230 	uint8_t *sense_datap,
16231 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16232 {
16233 	struct sd_sense_info	si;
16234 	uint8_t sense_key = scsi_sense_key(sense_datap);
16235 	uint8_t asc = scsi_sense_asc(sense_datap);
16236 
16237 	ASSERT(un != NULL);
16238 	ASSERT(mutex_owned(SD_MUTEX(un)));
16239 	ASSERT(bp != NULL);
16240 	ASSERT(xp != NULL);
16241 	ASSERT(pktp != NULL);
16242 
16243 	si.ssi_severity = SCSI_ERR_FATAL;
16244 	si.ssi_pfa_flag = FALSE;
16245 
16246 	if (sense_key == KEY_MEDIUM_ERROR) {
16247 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
16248 	}
16249 
16250 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16251 
16252 	if ((un->un_reset_retry_count != 0) &&
16253 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
16254 		mutex_exit(SD_MUTEX(un));
16255 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
16256 		if (un->un_f_allow_bus_device_reset == TRUE) {
16257 
16258 			boolean_t try_resetting_target = B_TRUE;
16259 
16260 			/*
16261 			 * We need to be able to handle specific ASC when we are
16262 			 * handling a KEY_HARDWARE_ERROR. In particular
16263 			 * taking the default action of resetting the target may
16264 			 * not be the appropriate way to attempt recovery.
16265 			 * Resetting a target because of a single LUN failure
16266 			 * victimizes all LUNs on that target.
16267 			 *
16268 			 * This is true for the LSI arrays, if an LSI
16269 			 * array controller returns an ASC of 0x84 (LUN Dead) we
16270 			 * should trust it.
16271 			 */
16272 
16273 			if (sense_key == KEY_HARDWARE_ERROR) {
16274 				switch (asc) {
16275 				case 0x84:
16276 					if (SD_IS_LSI(un)) {
16277 						try_resetting_target = B_FALSE;
16278 					}
16279 					break;
16280 				default:
16281 					break;
16282 				}
16283 			}
16284 
16285 			if (try_resetting_target == B_TRUE) {
16286 				int reset_retval = 0;
16287 				if (un->un_f_lun_reset_enabled == TRUE) {
16288 					SD_TRACE(SD_LOG_IO_CORE, un,
16289 					    "sd_sense_key_medium_or_hardware_"
16290 					    "error: issuing RESET_LUN\n");
16291 					reset_retval =
16292 					    scsi_reset(SD_ADDRESS(un),
16293 					    RESET_LUN);
16294 				}
16295 				if (reset_retval == 0) {
16296 					SD_TRACE(SD_LOG_IO_CORE, un,
16297 					    "sd_sense_key_medium_or_hardware_"
16298 					    "error: issuing RESET_TARGET\n");
16299 					(void) scsi_reset(SD_ADDRESS(un),
16300 					    RESET_TARGET);
16301 				}
16302 			}
16303 		}
16304 		mutex_enter(SD_MUTEX(un));
16305 	}
16306 
16307 	/*
16308 	 * This really ought to be a fatal error, but we will retry anyway
16309 	 * as some drives report this as a spurious error.
16310 	 */
16311 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16312 	    &si, EIO, (clock_t)0, NULL);
16313 }
16314 
16315 
16316 
16317 /*
16318  *    Function: sd_sense_key_illegal_request
16319  *
16320  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
16321  *
16322  *     Context: May be called from interrupt context
16323  */
16324 
16325 static void
16326 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
16327 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16328 {
16329 	struct sd_sense_info	si;
16330 
16331 	ASSERT(un != NULL);
16332 	ASSERT(mutex_owned(SD_MUTEX(un)));
16333 	ASSERT(bp != NULL);
16334 	ASSERT(xp != NULL);
16335 	ASSERT(pktp != NULL);
16336 
16337 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
16338 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
16339 
16340 	si.ssi_severity = SCSI_ERR_INFO;
16341 	si.ssi_pfa_flag = FALSE;
16342 
16343 	/* Pointless to retry if the target thinks it's an illegal request */
16344 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16345 	sd_return_failed_command(un, bp, EIO);
16346 }
16347 
16348 
16349 
16350 
16351 /*
16352  *    Function: sd_sense_key_unit_attention
16353  *
16354  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
16355  *
16356  *     Context: May be called from interrupt context
16357  */
16358 
16359 static void
16360 sd_sense_key_unit_attention(struct sd_lun *un,
16361 	uint8_t *sense_datap,
16362 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16363 {
16364 	/*
16365 	 * For UNIT ATTENTION we allow retries for one minute. Devices
16366 	 * like Sonoma can return UNIT ATTENTION close to a minute
16367 	 * under certain conditions.
16368 	 */
16369 	int	retry_check_flag = SD_RETRIES_UA;
16370 	boolean_t	kstat_updated = B_FALSE;
16371 	struct	sd_sense_info		si;
16372 	uint8_t asc = scsi_sense_asc(sense_datap);
16373 
16374 	ASSERT(un != NULL);
16375 	ASSERT(mutex_owned(SD_MUTEX(un)));
16376 	ASSERT(bp != NULL);
16377 	ASSERT(xp != NULL);
16378 	ASSERT(pktp != NULL);
16379 
16380 	si.ssi_severity = SCSI_ERR_INFO;
16381 	si.ssi_pfa_flag = FALSE;
16382 
16383 
16384 	switch (asc) {
16385 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
16386 		if (sd_report_pfa != 0) {
16387 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
16388 			si.ssi_pfa_flag = TRUE;
16389 			retry_check_flag = SD_RETRIES_STANDARD;
16390 			goto do_retry;
16391 		}
16392 
16393 		break;
16394 
16395 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
16396 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
16397 			un->un_resvd_status |=
16398 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
16399 		}
16400 #ifdef _LP64
16401 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
16402 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
16403 			    un, KM_NOSLEEP) == 0) {
16404 				/*
16405 				 * If we can't dispatch the task we'll just
16406 				 * live without descriptor sense.  We can
16407 				 * try again on the next "unit attention"
16408 				 */
16409 				SD_ERROR(SD_LOG_ERROR, un,
16410 				    "sd_sense_key_unit_attention: "
16411 				    "Could not dispatch "
16412 				    "sd_reenable_dsense_task\n");
16413 			}
16414 		}
16415 #endif /* _LP64 */
16416 		/* FALLTHRU */
16417 
16418 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
16419 		if (!un->un_f_has_removable_media) {
16420 			break;
16421 		}
16422 
16423 		/*
16424 		 * When we get a unit attention from a removable-media device,
16425 		 * it may be in a state that will take a long time to recover
16426 		 * (e.g., from a reset).  Since we are executing in interrupt
16427 		 * context here, we cannot wait around for the device to come
16428 		 * back. So hand this command off to sd_media_change_task()
16429 		 * for deferred processing under taskq thread context. (Note
16430 		 * that the command still may be failed if a problem is
16431 		 * encountered at a later time.)
16432 		 */
16433 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
16434 		    KM_NOSLEEP) == 0) {
16435 			/*
16436 			 * Cannot dispatch the request so fail the command.
16437 			 */
16438 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
16439 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16440 			si.ssi_severity = SCSI_ERR_FATAL;
16441 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16442 			sd_return_failed_command(un, bp, EIO);
16443 		}
16444 
16445 		/*
16446 		 * If failed to dispatch sd_media_change_task(), we already
16447 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
16448 		 * we should update kstat later if it encounters an error. So,
16449 		 * we update kstat_updated flag here.
16450 		 */
16451 		kstat_updated = B_TRUE;
16452 
16453 		/*
16454 		 * Either the command has been successfully dispatched to a
16455 		 * task Q for retrying, or the dispatch failed. In either case
16456 		 * do NOT retry again by calling sd_retry_command. This sets up
16457 		 * two retries of the same command and when one completes and
16458 		 * frees the resources the other will access freed memory,
16459 		 * a bad thing.
16460 		 */
16461 		return;
16462 
16463 	default:
16464 		break;
16465 	}
16466 
16467 	/*
16468 	 * Update kstat if we haven't done that.
16469 	 */
16470 	if (!kstat_updated) {
16471 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16472 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16473 	}
16474 
16475 do_retry:
16476 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
16477 	    EIO, SD_UA_RETRY_DELAY, NULL);
16478 }
16479 
16480 
16481 
16482 /*
16483  *    Function: sd_sense_key_fail_command
16484  *
16485  * Description: Use to fail a command when we don't like the sense key that
16486  *		was returned.
16487  *
16488  *     Context: May be called from interrupt context
16489  */
16490 
16491 static void
16492 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
16493 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16494 {
16495 	struct sd_sense_info	si;
16496 
16497 	ASSERT(un != NULL);
16498 	ASSERT(mutex_owned(SD_MUTEX(un)));
16499 	ASSERT(bp != NULL);
16500 	ASSERT(xp != NULL);
16501 	ASSERT(pktp != NULL);
16502 
16503 	si.ssi_severity = SCSI_ERR_FATAL;
16504 	si.ssi_pfa_flag = FALSE;
16505 
16506 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16507 	sd_return_failed_command(un, bp, EIO);
16508 }
16509 
16510 
16511 
16512 /*
16513  *    Function: sd_sense_key_blank_check
16514  *
16515  * Description: Recovery actions for a SCSI "Blank Check" sense key.
16516  *		Has no monetary connotation.
16517  *
16518  *     Context: May be called from interrupt context
16519  */
16520 
16521 static void
16522 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
16523 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16524 {
16525 	struct sd_sense_info	si;
16526 
16527 	ASSERT(un != NULL);
16528 	ASSERT(mutex_owned(SD_MUTEX(un)));
16529 	ASSERT(bp != NULL);
16530 	ASSERT(xp != NULL);
16531 	ASSERT(pktp != NULL);
16532 
16533 	/*
16534 	 * Blank check is not fatal for removable devices, therefore
16535 	 * it does not require a console message.
16536 	 */
16537 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
16538 	    SCSI_ERR_FATAL;
16539 	si.ssi_pfa_flag = FALSE;
16540 
16541 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16542 	sd_return_failed_command(un, bp, EIO);
16543 }
16544 
16545 
16546 
16547 
16548 /*
16549  *    Function: sd_sense_key_aborted_command
16550  *
16551  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
16552  *
16553  *     Context: May be called from interrupt context
16554  */
16555 
16556 static void
16557 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
16558 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16559 {
16560 	struct sd_sense_info	si;
16561 
16562 	ASSERT(un != NULL);
16563 	ASSERT(mutex_owned(SD_MUTEX(un)));
16564 	ASSERT(bp != NULL);
16565 	ASSERT(xp != NULL);
16566 	ASSERT(pktp != NULL);
16567 
16568 	si.ssi_severity = SCSI_ERR_FATAL;
16569 	si.ssi_pfa_flag = FALSE;
16570 
16571 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16572 
16573 	/*
16574 	 * This really ought to be a fatal error, but we will retry anyway
16575 	 * as some drives report this as a spurious error.
16576 	 */
16577 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16578 	    &si, EIO, drv_usectohz(100000), NULL);
16579 }
16580 
16581 
16582 
16583 /*
16584  *    Function: sd_sense_key_default
16585  *
16586  * Description: Default recovery action for several SCSI sense keys (basically
16587  *		attempts a retry).
16588  *
16589  *     Context: May be called from interrupt context
16590  */
16591 
16592 static void
16593 sd_sense_key_default(struct sd_lun *un,
16594 	uint8_t *sense_datap,
16595 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16596 {
16597 	struct sd_sense_info	si;
16598 	uint8_t sense_key = scsi_sense_key(sense_datap);
16599 
16600 	ASSERT(un != NULL);
16601 	ASSERT(mutex_owned(SD_MUTEX(un)));
16602 	ASSERT(bp != NULL);
16603 	ASSERT(xp != NULL);
16604 	ASSERT(pktp != NULL);
16605 
16606 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16607 
16608 	/*
16609 	 * Undecoded sense key.	Attempt retries and hope that will fix
16610 	 * the problem.  Otherwise, we're dead.
16611 	 */
16612 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
16613 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16614 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
16615 	}
16616 
16617 	si.ssi_severity = SCSI_ERR_FATAL;
16618 	si.ssi_pfa_flag = FALSE;
16619 
16620 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16621 	    &si, EIO, (clock_t)0, NULL);
16622 }
16623 
16624 
16625 
16626 /*
16627  *    Function: sd_print_retry_msg
16628  *
16629  * Description: Print a message indicating the retry action being taken.
16630  *
16631  *   Arguments: un - ptr to associated softstate
16632  *		bp - ptr to buf(9S) for the command
16633  *		arg - not used.
16634  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16635  *			or SD_NO_RETRY_ISSUED
16636  *
16637  *     Context: May be called from interrupt context
16638  */
16639 /* ARGSUSED */
16640 static void
16641 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
16642 {
16643 	struct sd_xbuf	*xp;
16644 	struct scsi_pkt *pktp;
16645 	char *reasonp;
16646 	char *msgp;
16647 
16648 	ASSERT(un != NULL);
16649 	ASSERT(mutex_owned(SD_MUTEX(un)));
16650 	ASSERT(bp != NULL);
16651 	pktp = SD_GET_PKTP(bp);
16652 	ASSERT(pktp != NULL);
16653 	xp = SD_GET_XBUF(bp);
16654 	ASSERT(xp != NULL);
16655 
16656 	ASSERT(!mutex_owned(&un->un_pm_mutex));
16657 	mutex_enter(&un->un_pm_mutex);
16658 	if ((un->un_state == SD_STATE_SUSPENDED) ||
16659 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
16660 	    (pktp->pkt_flags & FLAG_SILENT)) {
16661 		mutex_exit(&un->un_pm_mutex);
16662 		goto update_pkt_reason;
16663 	}
16664 	mutex_exit(&un->un_pm_mutex);
16665 
16666 	/*
16667 	 * Suppress messages if they are all the same pkt_reason; with
16668 	 * TQ, many (up to 256) are returned with the same pkt_reason.
16669 	 * If we are in panic, then suppress the retry messages.
16670 	 */
16671 	switch (flag) {
16672 	case SD_NO_RETRY_ISSUED:
16673 		msgp = "giving up";
16674 		break;
16675 	case SD_IMMEDIATE_RETRY_ISSUED:
16676 	case SD_DELAYED_RETRY_ISSUED:
16677 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
16678 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
16679 		    (sd_error_level != SCSI_ERR_ALL))) {
16680 			return;
16681 		}
16682 		msgp = "retrying command";
16683 		break;
16684 	default:
16685 		goto update_pkt_reason;
16686 	}
16687 
16688 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
16689 	    scsi_rname(pktp->pkt_reason));
16690 
16691 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16692 	    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
16693 
16694 update_pkt_reason:
16695 	/*
16696 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
16697 	 * This is to prevent multiple console messages for the same failure
16698 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
16699 	 * when the command is retried successfully because there still may be
16700 	 * more commands coming back with the same value of pktp->pkt_reason.
16701 	 */
16702 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
16703 		un->un_last_pkt_reason = pktp->pkt_reason;
16704 	}
16705 }
16706 
16707 
16708 /*
16709  *    Function: sd_print_cmd_incomplete_msg
16710  *
16711  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
16712  *
16713  *   Arguments: un - ptr to associated softstate
16714  *		bp - ptr to buf(9S) for the command
16715  *		arg - passed to sd_print_retry_msg()
16716  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16717  *			or SD_NO_RETRY_ISSUED
16718  *
16719  *     Context: May be called from interrupt context
16720  */
16721 
16722 static void
16723 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
16724 	int code)
16725 {
16726 	dev_info_t	*dip;
16727 
16728 	ASSERT(un != NULL);
16729 	ASSERT(mutex_owned(SD_MUTEX(un)));
16730 	ASSERT(bp != NULL);
16731 
16732 	switch (code) {
16733 	case SD_NO_RETRY_ISSUED:
16734 		/* Command was failed. Someone turned off this target? */
16735 		if (un->un_state != SD_STATE_OFFLINE) {
16736 			/*
16737 			 * Suppress message if we are detaching and
16738 			 * device has been disconnected
16739 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
16740 			 * private interface and not part of the DDI
16741 			 */
16742 			dip = un->un_sd->sd_dev;
16743 			if (!(DEVI_IS_DETACHING(dip) &&
16744 			    DEVI_IS_DEVICE_REMOVED(dip))) {
16745 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16746 				"disk not responding to selection\n");
16747 			}
16748 			New_state(un, SD_STATE_OFFLINE);
16749 		}
16750 		break;
16751 
16752 	case SD_DELAYED_RETRY_ISSUED:
16753 	case SD_IMMEDIATE_RETRY_ISSUED:
16754 	default:
16755 		/* Command was successfully queued for retry */
16756 		sd_print_retry_msg(un, bp, arg, code);
16757 		break;
16758 	}
16759 }
16760 
16761 
16762 /*
16763  *    Function: sd_pkt_reason_cmd_incomplete
16764  *
16765  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
16766  *
16767  *     Context: May be called from interrupt context
16768  */
16769 
16770 static void
16771 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
16772 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16773 {
16774 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
16775 
16776 	ASSERT(un != NULL);
16777 	ASSERT(mutex_owned(SD_MUTEX(un)));
16778 	ASSERT(bp != NULL);
16779 	ASSERT(xp != NULL);
16780 	ASSERT(pktp != NULL);
16781 
16782 	/* Do not do a reset if selection did not complete */
16783 	/* Note: Should this not just check the bit? */
16784 	if (pktp->pkt_state != STATE_GOT_BUS) {
16785 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
16786 		sd_reset_target(un, pktp);
16787 	}
16788 
16789 	/*
16790 	 * If the target was not successfully selected, then set
16791 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
16792 	 * with the target, and further retries and/or commands are
16793 	 * likely to take a long time.
16794 	 */
16795 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
16796 		flag |= SD_RETRIES_FAILFAST;
16797 	}
16798 
16799 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16800 
16801 	sd_retry_command(un, bp, flag,
16802 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16803 }
16804 
16805 
16806 
16807 /*
16808  *    Function: sd_pkt_reason_cmd_tran_err
16809  *
16810  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
16811  *
16812  *     Context: May be called from interrupt context
16813  */
16814 
16815 static void
16816 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
16817 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16818 {
16819 	ASSERT(un != NULL);
16820 	ASSERT(mutex_owned(SD_MUTEX(un)));
16821 	ASSERT(bp != NULL);
16822 	ASSERT(xp != NULL);
16823 	ASSERT(pktp != NULL);
16824 
16825 	/*
16826 	 * Do not reset if we got a parity error, or if
16827 	 * selection did not complete.
16828 	 */
16829 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16830 	/* Note: Should this not just check the bit for pkt_state? */
16831 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
16832 	    (pktp->pkt_state != STATE_GOT_BUS)) {
16833 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
16834 		sd_reset_target(un, pktp);
16835 	}
16836 
16837 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16838 
16839 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
16840 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16841 }
16842 
16843 
16844 
16845 /*
16846  *    Function: sd_pkt_reason_cmd_reset
16847  *
16848  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
16849  *
16850  *     Context: May be called from interrupt context
16851  */
16852 
16853 static void
16854 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
16855 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16856 {
16857 	ASSERT(un != NULL);
16858 	ASSERT(mutex_owned(SD_MUTEX(un)));
16859 	ASSERT(bp != NULL);
16860 	ASSERT(xp != NULL);
16861 	ASSERT(pktp != NULL);
16862 
16863 	/* The target may still be running the command, so try to reset. */
16864 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16865 	sd_reset_target(un, pktp);
16866 
16867 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16868 
16869 	/*
16870 	 * If pkt_reason is CMD_RESET chances are that this pkt got
16871 	 * reset because another target on this bus caused it. The target
16872 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
16873 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
16874 	 */
16875 
16876 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
16877 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16878 }
16879 
16880 
16881 
16882 
16883 /*
16884  *    Function: sd_pkt_reason_cmd_aborted
16885  *
16886  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
16887  *
16888  *     Context: May be called from interrupt context
16889  */
16890 
16891 static void
16892 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
16893 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16894 {
16895 	ASSERT(un != NULL);
16896 	ASSERT(mutex_owned(SD_MUTEX(un)));
16897 	ASSERT(bp != NULL);
16898 	ASSERT(xp != NULL);
16899 	ASSERT(pktp != NULL);
16900 
16901 	/* The target may still be running the command, so try to reset. */
16902 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16903 	sd_reset_target(un, pktp);
16904 
16905 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16906 
16907 	/*
16908 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
16909 	 * aborted because another target on this bus caused it. The target
16910 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
16911 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
16912 	 */
16913 
16914 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
16915 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16916 }
16917 
16918 
16919 
16920 /*
16921  *    Function: sd_pkt_reason_cmd_timeout
16922  *
16923  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
16924  *
16925  *     Context: May be called from interrupt context
16926  */
16927 
16928 static void
16929 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
16930 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16931 {
16932 	ASSERT(un != NULL);
16933 	ASSERT(mutex_owned(SD_MUTEX(un)));
16934 	ASSERT(bp != NULL);
16935 	ASSERT(xp != NULL);
16936 	ASSERT(pktp != NULL);
16937 
16938 
16939 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16940 	sd_reset_target(un, pktp);
16941 
16942 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16943 
16944 	/*
16945 	 * A command timeout indicates that we could not establish
16946 	 * communication with the target, so set SD_RETRIES_FAILFAST
16947 	 * as further retries/commands are likely to take a long time.
16948 	 */
16949 	sd_retry_command(un, bp,
16950 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
16951 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16952 }
16953 
16954 
16955 
16956 /*
16957  *    Function: sd_pkt_reason_cmd_unx_bus_free
16958  *
16959  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
16960  *
16961  *     Context: May be called from interrupt context
16962  */
16963 
16964 static void
16965 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
16966 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16967 {
16968 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
16969 
16970 	ASSERT(un != NULL);
16971 	ASSERT(mutex_owned(SD_MUTEX(un)));
16972 	ASSERT(bp != NULL);
16973 	ASSERT(xp != NULL);
16974 	ASSERT(pktp != NULL);
16975 
16976 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16977 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16978 
16979 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
16980 	    sd_print_retry_msg : NULL;
16981 
16982 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
16983 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16984 }
16985 
16986 
16987 /*
16988  *    Function: sd_pkt_reason_cmd_tag_reject
16989  *
16990  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
16991  *
16992  *     Context: May be called from interrupt context
16993  */
16994 
16995 static void
16996 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
16997 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16998 {
16999 	ASSERT(un != NULL);
17000 	ASSERT(mutex_owned(SD_MUTEX(un)));
17001 	ASSERT(bp != NULL);
17002 	ASSERT(xp != NULL);
17003 	ASSERT(pktp != NULL);
17004 
17005 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17006 	pktp->pkt_flags = 0;
17007 	un->un_tagflags = 0;
17008 	if (un->un_f_opt_queueing == TRUE) {
17009 		un->un_throttle = min(un->un_throttle, 3);
17010 	} else {
17011 		un->un_throttle = 1;
17012 	}
17013 	mutex_exit(SD_MUTEX(un));
17014 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
17015 	mutex_enter(SD_MUTEX(un));
17016 
17017 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17018 
17019 	/* Legacy behavior not to check retry counts here. */
17020 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
17021 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17022 }
17023 
17024 
17025 /*
17026  *    Function: sd_pkt_reason_default
17027  *
17028  * Description: Default recovery actions for SCSA pkt_reason values that
17029  *		do not have more explicit recovery actions.
17030  *
17031  *     Context: May be called from interrupt context
17032  */
17033 
17034 static void
17035 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
17036 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17037 {
17038 	ASSERT(un != NULL);
17039 	ASSERT(mutex_owned(SD_MUTEX(un)));
17040 	ASSERT(bp != NULL);
17041 	ASSERT(xp != NULL);
17042 	ASSERT(pktp != NULL);
17043 
17044 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
17045 	sd_reset_target(un, pktp);
17046 
17047 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17048 
17049 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
17050 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17051 }
17052 
17053 
17054 
17055 /*
17056  *    Function: sd_pkt_status_check_condition
17057  *
17058  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
17059  *
17060  *     Context: May be called from interrupt context
17061  */
17062 
17063 static void
17064 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
17065 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17066 {
17067 	ASSERT(un != NULL);
17068 	ASSERT(mutex_owned(SD_MUTEX(un)));
17069 	ASSERT(bp != NULL);
17070 	ASSERT(xp != NULL);
17071 	ASSERT(pktp != NULL);
17072 
17073 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
17074 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
17075 
17076 	/*
17077 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
17078 	 * command will be retried after the request sense). Otherwise, retry
17079 	 * the command. Note: we are issuing the request sense even though the
17080 	 * retry limit may have been reached for the failed command.
17081 	 */
17082 	if (un->un_f_arq_enabled == FALSE) {
17083 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
17084 		    "no ARQ, sending request sense command\n");
17085 		sd_send_request_sense_command(un, bp, pktp);
17086 	} else {
17087 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
17088 		    "ARQ,retrying request sense command\n");
17089 #if defined(__i386) || defined(__amd64)
17090 		/*
17091 		 * The SD_RETRY_DELAY value need to be adjusted here
17092 		 * when SD_RETRY_DELAY change in sddef.h
17093 		 */
17094 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
17095 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
17096 		    NULL);
17097 #else
17098 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
17099 		    EIO, SD_RETRY_DELAY, NULL);
17100 #endif
17101 	}
17102 
17103 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
17104 }
17105 
17106 
17107 /*
17108  *    Function: sd_pkt_status_busy
17109  *
17110  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
17111  *
17112  *     Context: May be called from interrupt context
17113  */
17114 
17115 static void
17116 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17117 	struct scsi_pkt *pktp)
17118 {
17119 	ASSERT(un != NULL);
17120 	ASSERT(mutex_owned(SD_MUTEX(un)));
17121 	ASSERT(bp != NULL);
17122 	ASSERT(xp != NULL);
17123 	ASSERT(pktp != NULL);
17124 
17125 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17126 	    "sd_pkt_status_busy: entry\n");
17127 
17128 	/* If retries are exhausted, just fail the command. */
17129 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
17130 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17131 		    "device busy too long\n");
17132 		sd_return_failed_command(un, bp, EIO);
17133 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17134 		    "sd_pkt_status_busy: exit\n");
17135 		return;
17136 	}
17137 	xp->xb_retry_count++;
17138 
17139 	/*
17140 	 * Try to reset the target. However, we do not want to perform
17141 	 * more than one reset if the device continues to fail. The reset
17142 	 * will be performed when the retry count reaches the reset
17143 	 * threshold.  This threshold should be set such that at least
17144 	 * one retry is issued before the reset is performed.
17145 	 */
17146 	if (xp->xb_retry_count ==
17147 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
17148 		int rval = 0;
17149 		mutex_exit(SD_MUTEX(un));
17150 		if (un->un_f_allow_bus_device_reset == TRUE) {
17151 			/*
17152 			 * First try to reset the LUN; if we cannot then
17153 			 * try to reset the target.
17154 			 */
17155 			if (un->un_f_lun_reset_enabled == TRUE) {
17156 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17157 				    "sd_pkt_status_busy: RESET_LUN\n");
17158 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
17159 			}
17160 			if (rval == 0) {
17161 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17162 				    "sd_pkt_status_busy: RESET_TARGET\n");
17163 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
17164 			}
17165 		}
17166 		if (rval == 0) {
17167 			/*
17168 			 * If the RESET_LUN and/or RESET_TARGET failed,
17169 			 * try RESET_ALL
17170 			 */
17171 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17172 			    "sd_pkt_status_busy: RESET_ALL\n");
17173 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
17174 		}
17175 		mutex_enter(SD_MUTEX(un));
17176 		if (rval == 0) {
17177 			/*
17178 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
17179 			 * At this point we give up & fail the command.
17180 			 */
17181 			sd_return_failed_command(un, bp, EIO);
17182 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17183 			    "sd_pkt_status_busy: exit (failed cmd)\n");
17184 			return;
17185 		}
17186 	}
17187 
17188 	/*
17189 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
17190 	 * we have already checked the retry counts above.
17191 	 */
17192 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
17193 	    EIO, SD_BSY_TIMEOUT, NULL);
17194 
17195 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17196 	    "sd_pkt_status_busy: exit\n");
17197 }
17198 
17199 
17200 /*
17201  *    Function: sd_pkt_status_reservation_conflict
17202  *
17203  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
17204  *		command status.
17205  *
17206  *     Context: May be called from interrupt context
17207  */
17208 
17209 static void
17210 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
17211 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17212 {
17213 	ASSERT(un != NULL);
17214 	ASSERT(mutex_owned(SD_MUTEX(un)));
17215 	ASSERT(bp != NULL);
17216 	ASSERT(xp != NULL);
17217 	ASSERT(pktp != NULL);
17218 
17219 	/*
17220 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
17221 	 * conflict could be due to various reasons like incorrect keys, not
17222 	 * registered or not reserved etc. So, we return EACCES to the caller.
17223 	 */
17224 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
17225 		int cmd = SD_GET_PKT_OPCODE(pktp);
17226 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
17227 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
17228 			sd_return_failed_command(un, bp, EACCES);
17229 			return;
17230 		}
17231 	}
17232 
17233 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
17234 
17235 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
17236 		if (sd_failfast_enable != 0) {
17237 			/* By definition, we must panic here.... */
17238 			sd_panic_for_res_conflict(un);
17239 			/*NOTREACHED*/
17240 		}
17241 		SD_ERROR(SD_LOG_IO, un,
17242 		    "sd_handle_resv_conflict: Disk Reserved\n");
17243 		sd_return_failed_command(un, bp, EACCES);
17244 		return;
17245 	}
17246 
17247 	/*
17248 	 * 1147670: retry only if sd_retry_on_reservation_conflict
17249 	 * property is set (default is 1). Retries will not succeed
17250 	 * on a disk reserved by another initiator. HA systems
17251 	 * may reset this via sd.conf to avoid these retries.
17252 	 *
17253 	 * Note: The legacy return code for this failure is EIO, however EACCES
17254 	 * seems more appropriate for a reservation conflict.
17255 	 */
17256 	if (sd_retry_on_reservation_conflict == 0) {
17257 		SD_ERROR(SD_LOG_IO, un,
17258 		    "sd_handle_resv_conflict: Device Reserved\n");
17259 		sd_return_failed_command(un, bp, EIO);
17260 		return;
17261 	}
17262 
17263 	/*
17264 	 * Retry the command if we can.
17265 	 *
17266 	 * Note: The legacy return code for this failure is EIO, however EACCES
17267 	 * seems more appropriate for a reservation conflict.
17268 	 */
17269 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
17270 	    (clock_t)2, NULL);
17271 }
17272 
17273 
17274 
17275 /*
17276  *    Function: sd_pkt_status_qfull
17277  *
17278  * Description: Handle a QUEUE FULL condition from the target.  This can
17279  *		occur if the HBA does not handle the queue full condition.
17280  *		(Basically this means third-party HBAs as Sun HBAs will
17281  *		handle the queue full condition.)  Note that if there are
17282  *		some commands already in the transport, then the queue full
17283  *		has occurred because the queue for this nexus is actually
17284  *		full. If there are no commands in the transport, then the
17285  *		queue full is resulting from some other initiator or lun
17286  *		consuming all the resources at the target.
17287  *
17288  *     Context: May be called from interrupt context
17289  */
17290 
17291 static void
17292 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
17293 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17294 {
17295 	ASSERT(un != NULL);
17296 	ASSERT(mutex_owned(SD_MUTEX(un)));
17297 	ASSERT(bp != NULL);
17298 	ASSERT(xp != NULL);
17299 	ASSERT(pktp != NULL);
17300 
17301 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17302 	    "sd_pkt_status_qfull: entry\n");
17303 
17304 	/*
17305 	 * Just lower the QFULL throttle and retry the command.  Note that
17306 	 * we do not limit the number of retries here.
17307 	 */
17308 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
17309 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
17310 	    SD_RESTART_TIMEOUT, NULL);
17311 
17312 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17313 	    "sd_pkt_status_qfull: exit\n");
17314 }
17315 
17316 
17317 /*
17318  *    Function: sd_reset_target
17319  *
17320  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
17321  *		RESET_TARGET, or RESET_ALL.
17322  *
17323  *     Context: May be called under interrupt context.
17324  */
17325 
17326 static void
17327 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
17328 {
17329 	int rval = 0;
17330 
17331 	ASSERT(un != NULL);
17332 	ASSERT(mutex_owned(SD_MUTEX(un)));
17333 	ASSERT(pktp != NULL);
17334 
17335 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
17336 
17337 	/*
17338 	 * No need to reset if the transport layer has already done so.
17339 	 */
17340 	if ((pktp->pkt_statistics &
17341 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
17342 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17343 		    "sd_reset_target: no reset\n");
17344 		return;
17345 	}
17346 
17347 	mutex_exit(SD_MUTEX(un));
17348 
17349 	if (un->un_f_allow_bus_device_reset == TRUE) {
17350 		if (un->un_f_lun_reset_enabled == TRUE) {
17351 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17352 			    "sd_reset_target: RESET_LUN\n");
17353 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
17354 		}
17355 		if (rval == 0) {
17356 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17357 			    "sd_reset_target: RESET_TARGET\n");
17358 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
17359 		}
17360 	}
17361 
17362 	if (rval == 0) {
17363 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17364 		    "sd_reset_target: RESET_ALL\n");
17365 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
17366 	}
17367 
17368 	mutex_enter(SD_MUTEX(un));
17369 
17370 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
17371 }
17372 
17373 
17374 /*
17375  *    Function: sd_media_change_task
17376  *
17377  * Description: Recovery action for CDROM to become available.
17378  *
17379  *     Context: Executes in a taskq() thread context
17380  */
17381 
17382 static void
17383 sd_media_change_task(void *arg)
17384 {
17385 	struct	scsi_pkt	*pktp = arg;
17386 	struct	sd_lun		*un;
17387 	struct	buf		*bp;
17388 	struct	sd_xbuf		*xp;
17389 	int	err		= 0;
17390 	int	retry_count	= 0;
17391 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
17392 	struct	sd_sense_info	si;
17393 
17394 	ASSERT(pktp != NULL);
17395 	bp = (struct buf *)pktp->pkt_private;
17396 	ASSERT(bp != NULL);
17397 	xp = SD_GET_XBUF(bp);
17398 	ASSERT(xp != NULL);
17399 	un = SD_GET_UN(bp);
17400 	ASSERT(un != NULL);
17401 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17402 	ASSERT(un->un_f_monitor_media_state);
17403 
17404 	si.ssi_severity = SCSI_ERR_INFO;
17405 	si.ssi_pfa_flag = FALSE;
17406 
17407 	/*
17408 	 * When a reset is issued on a CDROM, it takes a long time to
17409 	 * recover. First few attempts to read capacity and other things
17410 	 * related to handling unit attention fail (with a ASC 0x4 and
17411 	 * ASCQ 0x1). In that case we want to do enough retries and we want
17412 	 * to limit the retries in other cases of genuine failures like
17413 	 * no media in drive.
17414 	 */
17415 	while (retry_count++ < retry_limit) {
17416 		if ((err = sd_handle_mchange(un)) == 0) {
17417 			break;
17418 		}
17419 		if (err == EAGAIN) {
17420 			retry_limit = SD_UNIT_ATTENTION_RETRY;
17421 		}
17422 		/* Sleep for 0.5 sec. & try again */
17423 		delay(drv_usectohz(500000));
17424 	}
17425 
17426 	/*
17427 	 * Dispatch (retry or fail) the original command here,
17428 	 * along with appropriate console messages....
17429 	 *
17430 	 * Must grab the mutex before calling sd_retry_command,
17431 	 * sd_print_sense_msg and sd_return_failed_command.
17432 	 */
17433 	mutex_enter(SD_MUTEX(un));
17434 	if (err != SD_CMD_SUCCESS) {
17435 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17436 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
17437 		si.ssi_severity = SCSI_ERR_FATAL;
17438 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17439 		sd_return_failed_command(un, bp, EIO);
17440 	} else {
17441 		sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
17442 		    &si, EIO, (clock_t)0, NULL);
17443 	}
17444 	mutex_exit(SD_MUTEX(un));
17445 }
17446 
17447 
17448 
17449 /*
17450  *    Function: sd_handle_mchange
17451  *
17452  * Description: Perform geometry validation & other recovery when CDROM
17453  *		has been removed from drive.
17454  *
17455  * Return Code: 0 for success
17456  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
17457  *		sd_send_scsi_READ_CAPACITY()
17458  *
17459  *     Context: Executes in a taskq() thread context
17460  */
17461 
17462 static int
17463 sd_handle_mchange(struct sd_lun *un)
17464 {
17465 	uint64_t	capacity;
17466 	uint32_t	lbasize;
17467 	int		rval;
17468 
17469 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17470 	ASSERT(un->un_f_monitor_media_state);
17471 
17472 	if ((rval = sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
17473 	    SD_PATH_DIRECT_PRIORITY)) != 0) {
17474 		return (rval);
17475 	}
17476 
17477 	mutex_enter(SD_MUTEX(un));
17478 	sd_update_block_info(un, lbasize, capacity);
17479 
17480 	if (un->un_errstats != NULL) {
17481 		struct	sd_errstats *stp =
17482 		    (struct sd_errstats *)un->un_errstats->ks_data;
17483 		stp->sd_capacity.value.ui64 = (uint64_t)
17484 		    ((uint64_t)un->un_blockcount *
17485 		    (uint64_t)un->un_tgt_blocksize);
17486 	}
17487 
17488 
17489 	/*
17490 	 * Check if the media in the device is writable or not
17491 	 */
17492 	if (ISCD(un))
17493 		sd_check_for_writable_cd(un, SD_PATH_DIRECT_PRIORITY);
17494 
17495 	/*
17496 	 * Note: Maybe let the strategy/partitioning chain worry about getting
17497 	 * valid geometry.
17498 	 */
17499 	mutex_exit(SD_MUTEX(un));
17500 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
17501 
17502 
17503 	if (cmlb_validate(un->un_cmlbhandle, 0,
17504 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
17505 		return (EIO);
17506 	} else {
17507 		if (un->un_f_pkstats_enabled) {
17508 			sd_set_pstats(un);
17509 			SD_TRACE(SD_LOG_IO_PARTITION, un,
17510 			    "sd_handle_mchange: un:0x%p pstats created and "
17511 			    "set\n", un);
17512 		}
17513 	}
17514 
17515 
17516 	/*
17517 	 * Try to lock the door
17518 	 */
17519 	return (sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
17520 	    SD_PATH_DIRECT_PRIORITY));
17521 }
17522 
17523 
17524 /*
17525  *    Function: sd_send_scsi_DOORLOCK
17526  *
17527  * Description: Issue the scsi DOOR LOCK command
17528  *
17529  *   Arguments: un    - pointer to driver soft state (unit) structure for
17530  *			this target.
17531  *		flag  - SD_REMOVAL_ALLOW
17532  *			SD_REMOVAL_PREVENT
17533  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17534  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17535  *			to use the USCSI "direct" chain and bypass the normal
17536  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17537  *			command is issued as part of an error recovery action.
17538  *
17539  * Return Code: 0   - Success
17540  *		errno return code from sd_send_scsi_cmd()
17541  *
17542  *     Context: Can sleep.
17543  */
17544 
17545 static int
17546 sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag)
17547 {
17548 	union scsi_cdb		cdb;
17549 	struct uscsi_cmd	ucmd_buf;
17550 	struct scsi_extended_sense	sense_buf;
17551 	int			status;
17552 
17553 	ASSERT(un != NULL);
17554 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17555 
17556 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
17557 
17558 	/* already determined doorlock is not supported, fake success */
17559 	if (un->un_f_doorlock_supported == FALSE) {
17560 		return (0);
17561 	}
17562 
17563 	/*
17564 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
17565 	 * ignore the command so we can complete the eject
17566 	 * operation.
17567 	 */
17568 	if (flag == SD_REMOVAL_PREVENT) {
17569 		mutex_enter(SD_MUTEX(un));
17570 		if (un->un_f_ejecting == TRUE) {
17571 			mutex_exit(SD_MUTEX(un));
17572 			return (EAGAIN);
17573 		}
17574 		mutex_exit(SD_MUTEX(un));
17575 	}
17576 
17577 	bzero(&cdb, sizeof (cdb));
17578 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17579 
17580 	cdb.scc_cmd = SCMD_DOORLOCK;
17581 	cdb.cdb_opaque[4] = (uchar_t)flag;
17582 
17583 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17584 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
17585 	ucmd_buf.uscsi_bufaddr	= NULL;
17586 	ucmd_buf.uscsi_buflen	= 0;
17587 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17588 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17589 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
17590 	ucmd_buf.uscsi_timeout	= 15;
17591 
17592 	SD_TRACE(SD_LOG_IO, un,
17593 	    "sd_send_scsi_DOORLOCK: returning sd_send_scsi_cmd()\n");
17594 
17595 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17596 	    UIO_SYSSPACE, path_flag);
17597 
17598 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
17599 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17600 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
17601 		/* fake success and skip subsequent doorlock commands */
17602 		un->un_f_doorlock_supported = FALSE;
17603 		return (0);
17604 	}
17605 
17606 	return (status);
17607 }
17608 
17609 /*
17610  *    Function: sd_send_scsi_READ_CAPACITY
17611  *
17612  * Description: This routine uses the scsi READ CAPACITY command to determine
17613  *		the device capacity in number of blocks and the device native
17614  *		block size. If this function returns a failure, then the
17615  *		values in *capp and *lbap are undefined.  If the capacity
17616  *		returned is 0xffffffff then the lun is too large for a
17617  *		normal READ CAPACITY command and the results of a
17618  *		READ CAPACITY 16 will be used instead.
17619  *
17620  *   Arguments: un   - ptr to soft state struct for the target
17621  *		capp - ptr to unsigned 64-bit variable to receive the
17622  *			capacity value from the command.
17623  *		lbap - ptr to unsigned 32-bit varaible to receive the
17624  *			block size value from the command
17625  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17626  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17627  *			to use the USCSI "direct" chain and bypass the normal
17628  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17629  *			command is issued as part of an error recovery action.
17630  *
17631  * Return Code: 0   - Success
17632  *		EIO - IO error
17633  *		EACCES - Reservation conflict detected
17634  *		EAGAIN - Device is becoming ready
17635  *		errno return code from sd_send_scsi_cmd()
17636  *
17637  *     Context: Can sleep.  Blocks until command completes.
17638  */
17639 
17640 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
17641 
17642 static int
17643 sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp, uint32_t *lbap,
17644 	int path_flag)
17645 {
17646 	struct	scsi_extended_sense	sense_buf;
17647 	struct	uscsi_cmd	ucmd_buf;
17648 	union	scsi_cdb	cdb;
17649 	uint32_t		*capacity_buf;
17650 	uint64_t		capacity;
17651 	uint32_t		lbasize;
17652 	int			status;
17653 
17654 	ASSERT(un != NULL);
17655 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17656 	ASSERT(capp != NULL);
17657 	ASSERT(lbap != NULL);
17658 
17659 	SD_TRACE(SD_LOG_IO, un,
17660 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
17661 
17662 	/*
17663 	 * First send a READ_CAPACITY command to the target.
17664 	 * (This command is mandatory under SCSI-2.)
17665 	 *
17666 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
17667 	 * Medium Indicator bit is cleared.  The address field must be
17668 	 * zero if the PMI bit is zero.
17669 	 */
17670 	bzero(&cdb, sizeof (cdb));
17671 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17672 
17673 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
17674 
17675 	cdb.scc_cmd = SCMD_READ_CAPACITY;
17676 
17677 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17678 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
17679 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
17680 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
17681 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17682 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17683 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
17684 	ucmd_buf.uscsi_timeout	= 60;
17685 
17686 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17687 	    UIO_SYSSPACE, path_flag);
17688 
17689 	switch (status) {
17690 	case 0:
17691 		/* Return failure if we did not get valid capacity data. */
17692 		if (ucmd_buf.uscsi_resid != 0) {
17693 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17694 			return (EIO);
17695 		}
17696 
17697 		/*
17698 		 * Read capacity and block size from the READ CAPACITY 10 data.
17699 		 * This data may be adjusted later due to device specific
17700 		 * issues.
17701 		 *
17702 		 * According to the SCSI spec, the READ CAPACITY 10
17703 		 * command returns the following:
17704 		 *
17705 		 *  bytes 0-3: Maximum logical block address available.
17706 		 *		(MSB in byte:0 & LSB in byte:3)
17707 		 *
17708 		 *  bytes 4-7: Block length in bytes
17709 		 *		(MSB in byte:4 & LSB in byte:7)
17710 		 *
17711 		 */
17712 		capacity = BE_32(capacity_buf[0]);
17713 		lbasize = BE_32(capacity_buf[1]);
17714 
17715 		/*
17716 		 * Done with capacity_buf
17717 		 */
17718 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17719 
17720 		/*
17721 		 * if the reported capacity is set to all 0xf's, then
17722 		 * this disk is too large and requires SBC-2 commands.
17723 		 * Reissue the request using READ CAPACITY 16.
17724 		 */
17725 		if (capacity == 0xffffffff) {
17726 			status = sd_send_scsi_READ_CAPACITY_16(un, &capacity,
17727 			    &lbasize, path_flag);
17728 			if (status != 0) {
17729 				return (status);
17730 			}
17731 		}
17732 		break;	/* Success! */
17733 	case EIO:
17734 		switch (ucmd_buf.uscsi_status) {
17735 		case STATUS_RESERVATION_CONFLICT:
17736 			status = EACCES;
17737 			break;
17738 		case STATUS_CHECK:
17739 			/*
17740 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
17741 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
17742 			 */
17743 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17744 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
17745 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
17746 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17747 				return (EAGAIN);
17748 			}
17749 			break;
17750 		default:
17751 			break;
17752 		}
17753 		/* FALLTHRU */
17754 	default:
17755 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17756 		return (status);
17757 	}
17758 
17759 	/*
17760 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
17761 	 * (2352 and 0 are common) so for these devices always force the value
17762 	 * to 2048 as required by the ATAPI specs.
17763 	 */
17764 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
17765 		lbasize = 2048;
17766 	}
17767 
17768 	/*
17769 	 * Get the maximum LBA value from the READ CAPACITY data.
17770 	 * Here we assume that the Partial Medium Indicator (PMI) bit
17771 	 * was cleared when issuing the command. This means that the LBA
17772 	 * returned from the device is the LBA of the last logical block
17773 	 * on the logical unit.  The actual logical block count will be
17774 	 * this value plus one.
17775 	 *
17776 	 * Currently the capacity is saved in terms of un->un_sys_blocksize,
17777 	 * so scale the capacity value to reflect this.
17778 	 */
17779 	capacity = (capacity + 1) * (lbasize / un->un_sys_blocksize);
17780 
17781 	/*
17782 	 * Copy the values from the READ CAPACITY command into the space
17783 	 * provided by the caller.
17784 	 */
17785 	*capp = capacity;
17786 	*lbap = lbasize;
17787 
17788 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
17789 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
17790 
17791 	/*
17792 	 * Both the lbasize and capacity from the device must be nonzero,
17793 	 * otherwise we assume that the values are not valid and return
17794 	 * failure to the caller. (4203735)
17795 	 */
17796 	if ((capacity == 0) || (lbasize == 0)) {
17797 		return (EIO);
17798 	}
17799 
17800 	return (0);
17801 }
17802 
17803 /*
17804  *    Function: sd_send_scsi_READ_CAPACITY_16
17805  *
17806  * Description: This routine uses the scsi READ CAPACITY 16 command to
17807  *		determine the device capacity in number of blocks and the
17808  *		device native block size.  If this function returns a failure,
17809  *		then the values in *capp and *lbap are undefined.
17810  *		This routine should always be called by
17811  *		sd_send_scsi_READ_CAPACITY which will appy any device
17812  *		specific adjustments to capacity and lbasize.
17813  *
17814  *   Arguments: un   - ptr to soft state struct for the target
17815  *		capp - ptr to unsigned 64-bit variable to receive the
17816  *			capacity value from the command.
17817  *		lbap - ptr to unsigned 32-bit varaible to receive the
17818  *			block size value from the command
17819  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17820  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17821  *			to use the USCSI "direct" chain and bypass the normal
17822  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
17823  *			this command is issued as part of an error recovery
17824  *			action.
17825  *
17826  * Return Code: 0   - Success
17827  *		EIO - IO error
17828  *		EACCES - Reservation conflict detected
17829  *		EAGAIN - Device is becoming ready
17830  *		errno return code from sd_send_scsi_cmd()
17831  *
17832  *     Context: Can sleep.  Blocks until command completes.
17833  */
17834 
17835 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
17836 
17837 static int
17838 sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
17839 	uint32_t *lbap, int path_flag)
17840 {
17841 	struct	scsi_extended_sense	sense_buf;
17842 	struct	uscsi_cmd	ucmd_buf;
17843 	union	scsi_cdb	cdb;
17844 	uint64_t		*capacity16_buf;
17845 	uint64_t		capacity;
17846 	uint32_t		lbasize;
17847 	int			status;
17848 
17849 	ASSERT(un != NULL);
17850 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17851 	ASSERT(capp != NULL);
17852 	ASSERT(lbap != NULL);
17853 
17854 	SD_TRACE(SD_LOG_IO, un,
17855 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
17856 
17857 	/*
17858 	 * First send a READ_CAPACITY_16 command to the target.
17859 	 *
17860 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
17861 	 * Medium Indicator bit is cleared.  The address field must be
17862 	 * zero if the PMI bit is zero.
17863 	 */
17864 	bzero(&cdb, sizeof (cdb));
17865 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17866 
17867 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
17868 
17869 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17870 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
17871 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
17872 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
17873 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17874 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17875 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
17876 	ucmd_buf.uscsi_timeout	= 60;
17877 
17878 	/*
17879 	 * Read Capacity (16) is a Service Action In command.  One
17880 	 * command byte (0x9E) is overloaded for multiple operations,
17881 	 * with the second CDB byte specifying the desired operation
17882 	 */
17883 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
17884 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
17885 
17886 	/*
17887 	 * Fill in allocation length field
17888 	 */
17889 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
17890 
17891 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17892 	    UIO_SYSSPACE, path_flag);
17893 
17894 	switch (status) {
17895 	case 0:
17896 		/* Return failure if we did not get valid capacity data. */
17897 		if (ucmd_buf.uscsi_resid > 20) {
17898 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17899 			return (EIO);
17900 		}
17901 
17902 		/*
17903 		 * Read capacity and block size from the READ CAPACITY 10 data.
17904 		 * This data may be adjusted later due to device specific
17905 		 * issues.
17906 		 *
17907 		 * According to the SCSI spec, the READ CAPACITY 10
17908 		 * command returns the following:
17909 		 *
17910 		 *  bytes 0-7: Maximum logical block address available.
17911 		 *		(MSB in byte:0 & LSB in byte:7)
17912 		 *
17913 		 *  bytes 8-11: Block length in bytes
17914 		 *		(MSB in byte:8 & LSB in byte:11)
17915 		 *
17916 		 */
17917 		capacity = BE_64(capacity16_buf[0]);
17918 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
17919 
17920 		/*
17921 		 * Done with capacity16_buf
17922 		 */
17923 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17924 
17925 		/*
17926 		 * if the reported capacity is set to all 0xf's, then
17927 		 * this disk is too large.  This could only happen with
17928 		 * a device that supports LBAs larger than 64 bits which
17929 		 * are not defined by any current T10 standards.
17930 		 */
17931 		if (capacity == 0xffffffffffffffff) {
17932 			return (EIO);
17933 		}
17934 		break;	/* Success! */
17935 	case EIO:
17936 		switch (ucmd_buf.uscsi_status) {
17937 		case STATUS_RESERVATION_CONFLICT:
17938 			status = EACCES;
17939 			break;
17940 		case STATUS_CHECK:
17941 			/*
17942 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
17943 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
17944 			 */
17945 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17946 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
17947 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
17948 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17949 				return (EAGAIN);
17950 			}
17951 			break;
17952 		default:
17953 			break;
17954 		}
17955 		/* FALLTHRU */
17956 	default:
17957 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17958 		return (status);
17959 	}
17960 
17961 	*capp = capacity;
17962 	*lbap = lbasize;
17963 
17964 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
17965 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
17966 
17967 	return (0);
17968 }
17969 
17970 
17971 /*
17972  *    Function: sd_send_scsi_START_STOP_UNIT
17973  *
17974  * Description: Issue a scsi START STOP UNIT command to the target.
17975  *
17976  *   Arguments: un    - pointer to driver soft state (unit) structure for
17977  *			this target.
17978  *		flag  - SD_TARGET_START
17979  *			SD_TARGET_STOP
17980  *			SD_TARGET_EJECT
17981  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17982  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17983  *			to use the USCSI "direct" chain and bypass the normal
17984  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17985  *			command is issued as part of an error recovery action.
17986  *
17987  * Return Code: 0   - Success
17988  *		EIO - IO error
17989  *		EACCES - Reservation conflict detected
17990  *		ENXIO  - Not Ready, medium not present
17991  *		errno return code from sd_send_scsi_cmd()
17992  *
17993  *     Context: Can sleep.
17994  */
17995 
17996 static int
17997 sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag, int path_flag)
17998 {
17999 	struct	scsi_extended_sense	sense_buf;
18000 	union scsi_cdb		cdb;
18001 	struct uscsi_cmd	ucmd_buf;
18002 	int			status;
18003 
18004 	ASSERT(un != NULL);
18005 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18006 
18007 	SD_TRACE(SD_LOG_IO, un,
18008 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
18009 
18010 	if (un->un_f_check_start_stop &&
18011 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
18012 	    (un->un_f_start_stop_supported != TRUE)) {
18013 		return (0);
18014 	}
18015 
18016 	/*
18017 	 * If we are performing an eject operation and
18018 	 * we receive any command other than SD_TARGET_EJECT
18019 	 * we should immediately return.
18020 	 */
18021 	if (flag != SD_TARGET_EJECT) {
18022 		mutex_enter(SD_MUTEX(un));
18023 		if (un->un_f_ejecting == TRUE) {
18024 			mutex_exit(SD_MUTEX(un));
18025 			return (EAGAIN);
18026 		}
18027 		mutex_exit(SD_MUTEX(un));
18028 	}
18029 
18030 	bzero(&cdb, sizeof (cdb));
18031 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18032 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18033 
18034 	cdb.scc_cmd = SCMD_START_STOP;
18035 	cdb.cdb_opaque[4] = (uchar_t)flag;
18036 
18037 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18038 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18039 	ucmd_buf.uscsi_bufaddr	= NULL;
18040 	ucmd_buf.uscsi_buflen	= 0;
18041 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18042 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18043 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18044 	ucmd_buf.uscsi_timeout	= 200;
18045 
18046 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18047 	    UIO_SYSSPACE, path_flag);
18048 
18049 	switch (status) {
18050 	case 0:
18051 		break;	/* Success! */
18052 	case EIO:
18053 		switch (ucmd_buf.uscsi_status) {
18054 		case STATUS_RESERVATION_CONFLICT:
18055 			status = EACCES;
18056 			break;
18057 		case STATUS_CHECK:
18058 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
18059 				switch (scsi_sense_key(
18060 				    (uint8_t *)&sense_buf)) {
18061 				case KEY_ILLEGAL_REQUEST:
18062 					status = ENOTSUP;
18063 					break;
18064 				case KEY_NOT_READY:
18065 					if (scsi_sense_asc(
18066 					    (uint8_t *)&sense_buf)
18067 					    == 0x3A) {
18068 						status = ENXIO;
18069 					}
18070 					break;
18071 				default:
18072 					break;
18073 				}
18074 			}
18075 			break;
18076 		default:
18077 			break;
18078 		}
18079 		break;
18080 	default:
18081 		break;
18082 	}
18083 
18084 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
18085 
18086 	return (status);
18087 }
18088 
18089 
18090 /*
18091  *    Function: sd_start_stop_unit_callback
18092  *
18093  * Description: timeout(9F) callback to begin recovery process for a
18094  *		device that has spun down.
18095  *
18096  *   Arguments: arg - pointer to associated softstate struct.
18097  *
18098  *     Context: Executes in a timeout(9F) thread context
18099  */
18100 
18101 static void
18102 sd_start_stop_unit_callback(void *arg)
18103 {
18104 	struct sd_lun	*un = arg;
18105 	ASSERT(un != NULL);
18106 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18107 
18108 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
18109 
18110 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
18111 }
18112 
18113 
18114 /*
18115  *    Function: sd_start_stop_unit_task
18116  *
18117  * Description: Recovery procedure when a drive is spun down.
18118  *
18119  *   Arguments: arg - pointer to associated softstate struct.
18120  *
18121  *     Context: Executes in a taskq() thread context
18122  */
18123 
18124 static void
18125 sd_start_stop_unit_task(void *arg)
18126 {
18127 	struct sd_lun	*un = arg;
18128 
18129 	ASSERT(un != NULL);
18130 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18131 
18132 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
18133 
18134 	/*
18135 	 * Some unformatted drives report not ready error, no need to
18136 	 * restart if format has been initiated.
18137 	 */
18138 	mutex_enter(SD_MUTEX(un));
18139 	if (un->un_f_format_in_progress == TRUE) {
18140 		mutex_exit(SD_MUTEX(un));
18141 		return;
18142 	}
18143 	mutex_exit(SD_MUTEX(un));
18144 
18145 	/*
18146 	 * When a START STOP command is issued from here, it is part of a
18147 	 * failure recovery operation and must be issued before any other
18148 	 * commands, including any pending retries. Thus it must be sent
18149 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
18150 	 * succeeds or not, we will start I/O after the attempt.
18151 	 */
18152 	(void) sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
18153 	    SD_PATH_DIRECT_PRIORITY);
18154 
18155 	/*
18156 	 * The above call blocks until the START_STOP_UNIT command completes.
18157 	 * Now that it has completed, we must re-try the original IO that
18158 	 * received the NOT READY condition in the first place. There are
18159 	 * three possible conditions here:
18160 	 *
18161 	 *  (1) The original IO is on un_retry_bp.
18162 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
18163 	 *	is NULL.
18164 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
18165 	 *	points to some other, unrelated bp.
18166 	 *
18167 	 * For each case, we must call sd_start_cmds() with un_retry_bp
18168 	 * as the argument. If un_retry_bp is NULL, this will initiate
18169 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
18170 	 * then this will process the bp on un_retry_bp. That may or may not
18171 	 * be the original IO, but that does not matter: the important thing
18172 	 * is to keep the IO processing going at this point.
18173 	 *
18174 	 * Note: This is a very specific error recovery sequence associated
18175 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
18176 	 * serialize the I/O with completion of the spin-up.
18177 	 */
18178 	mutex_enter(SD_MUTEX(un));
18179 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18180 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
18181 	    un, un->un_retry_bp);
18182 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
18183 	sd_start_cmds(un, un->un_retry_bp);
18184 	mutex_exit(SD_MUTEX(un));
18185 
18186 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
18187 }
18188 
18189 
18190 /*
18191  *    Function: sd_send_scsi_INQUIRY
18192  *
18193  * Description: Issue the scsi INQUIRY command.
18194  *
18195  *   Arguments: un
18196  *		bufaddr
18197  *		buflen
18198  *		evpd
18199  *		page_code
18200  *		page_length
18201  *
18202  * Return Code: 0   - Success
18203  *		errno return code from sd_send_scsi_cmd()
18204  *
18205  *     Context: Can sleep. Does not return until command is completed.
18206  */
18207 
18208 static int
18209 sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr, size_t buflen,
18210 	uchar_t evpd, uchar_t page_code, size_t *residp)
18211 {
18212 	union scsi_cdb		cdb;
18213 	struct uscsi_cmd	ucmd_buf;
18214 	int			status;
18215 
18216 	ASSERT(un != NULL);
18217 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18218 	ASSERT(bufaddr != NULL);
18219 
18220 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
18221 
18222 	bzero(&cdb, sizeof (cdb));
18223 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18224 	bzero(bufaddr, buflen);
18225 
18226 	cdb.scc_cmd = SCMD_INQUIRY;
18227 	cdb.cdb_opaque[1] = evpd;
18228 	cdb.cdb_opaque[2] = page_code;
18229 	FORMG0COUNT(&cdb, buflen);
18230 
18231 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18232 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18233 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
18234 	ucmd_buf.uscsi_buflen	= buflen;
18235 	ucmd_buf.uscsi_rqbuf	= NULL;
18236 	ucmd_buf.uscsi_rqlen	= 0;
18237 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
18238 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
18239 
18240 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18241 	    UIO_SYSSPACE, SD_PATH_DIRECT);
18242 
18243 	if ((status == 0) && (residp != NULL)) {
18244 		*residp = ucmd_buf.uscsi_resid;
18245 	}
18246 
18247 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
18248 
18249 	return (status);
18250 }
18251 
18252 
18253 /*
18254  *    Function: sd_send_scsi_TEST_UNIT_READY
18255  *
18256  * Description: Issue the scsi TEST UNIT READY command.
18257  *		This routine can be told to set the flag USCSI_DIAGNOSE to
18258  *		prevent retrying failed commands. Use this when the intent
18259  *		is either to check for device readiness, to clear a Unit
18260  *		Attention, or to clear any outstanding sense data.
18261  *		However under specific conditions the expected behavior
18262  *		is for retries to bring a device ready, so use the flag
18263  *		with caution.
18264  *
18265  *   Arguments: un
18266  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
18267  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
18268  *			0: dont check for media present, do retries on cmd.
18269  *
18270  * Return Code: 0   - Success
18271  *		EIO - IO error
18272  *		EACCES - Reservation conflict detected
18273  *		ENXIO  - Not Ready, medium not present
18274  *		errno return code from sd_send_scsi_cmd()
18275  *
18276  *     Context: Can sleep. Does not return until command is completed.
18277  */
18278 
18279 static int
18280 sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag)
18281 {
18282 	struct	scsi_extended_sense	sense_buf;
18283 	union scsi_cdb		cdb;
18284 	struct uscsi_cmd	ucmd_buf;
18285 	int			status;
18286 
18287 	ASSERT(un != NULL);
18288 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18289 
18290 	SD_TRACE(SD_LOG_IO, un,
18291 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
18292 
18293 	/*
18294 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
18295 	 * timeouts when they receive a TUR and the queue is not empty. Check
18296 	 * the configuration flag set during attach (indicating the drive has
18297 	 * this firmware bug) and un_ncmds_in_transport before issuing the
18298 	 * TUR. If there are
18299 	 * pending commands return success, this is a bit arbitrary but is ok
18300 	 * for non-removables (i.e. the eliteI disks) and non-clustering
18301 	 * configurations.
18302 	 */
18303 	if (un->un_f_cfg_tur_check == TRUE) {
18304 		mutex_enter(SD_MUTEX(un));
18305 		if (un->un_ncmds_in_transport != 0) {
18306 			mutex_exit(SD_MUTEX(un));
18307 			return (0);
18308 		}
18309 		mutex_exit(SD_MUTEX(un));
18310 	}
18311 
18312 	bzero(&cdb, sizeof (cdb));
18313 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18314 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18315 
18316 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
18317 
18318 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18319 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18320 	ucmd_buf.uscsi_bufaddr	= NULL;
18321 	ucmd_buf.uscsi_buflen	= 0;
18322 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18323 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18324 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18325 
18326 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
18327 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
18328 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
18329 	}
18330 	ucmd_buf.uscsi_timeout	= 60;
18331 
18332 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18333 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
18334 	    SD_PATH_STANDARD));
18335 
18336 	switch (status) {
18337 	case 0:
18338 		break;	/* Success! */
18339 	case EIO:
18340 		switch (ucmd_buf.uscsi_status) {
18341 		case STATUS_RESERVATION_CONFLICT:
18342 			status = EACCES;
18343 			break;
18344 		case STATUS_CHECK:
18345 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
18346 				break;
18347 			}
18348 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18349 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18350 			    KEY_NOT_READY) &&
18351 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
18352 				status = ENXIO;
18353 			}
18354 			break;
18355 		default:
18356 			break;
18357 		}
18358 		break;
18359 	default:
18360 		break;
18361 	}
18362 
18363 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
18364 
18365 	return (status);
18366 }
18367 
18368 
18369 /*
18370  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
18371  *
18372  * Description: Issue the scsi PERSISTENT RESERVE IN command.
18373  *
18374  *   Arguments: un
18375  *
18376  * Return Code: 0   - Success
18377  *		EACCES
18378  *		ENOTSUP
18379  *		errno return code from sd_send_scsi_cmd()
18380  *
18381  *     Context: Can sleep. Does not return until command is completed.
18382  */
18383 
18384 static int
18385 sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un, uchar_t  usr_cmd,
18386 	uint16_t data_len, uchar_t *data_bufp)
18387 {
18388 	struct scsi_extended_sense	sense_buf;
18389 	union scsi_cdb		cdb;
18390 	struct uscsi_cmd	ucmd_buf;
18391 	int			status;
18392 	int			no_caller_buf = FALSE;
18393 
18394 	ASSERT(un != NULL);
18395 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18396 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
18397 
18398 	SD_TRACE(SD_LOG_IO, un,
18399 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
18400 
18401 	bzero(&cdb, sizeof (cdb));
18402 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18403 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18404 	if (data_bufp == NULL) {
18405 		/* Allocate a default buf if the caller did not give one */
18406 		ASSERT(data_len == 0);
18407 		data_len  = MHIOC_RESV_KEY_SIZE;
18408 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
18409 		no_caller_buf = TRUE;
18410 	}
18411 
18412 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
18413 	cdb.cdb_opaque[1] = usr_cmd;
18414 	FORMG1COUNT(&cdb, data_len);
18415 
18416 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18417 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18418 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
18419 	ucmd_buf.uscsi_buflen	= data_len;
18420 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18421 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18422 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
18423 	ucmd_buf.uscsi_timeout	= 60;
18424 
18425 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18426 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18427 
18428 	switch (status) {
18429 	case 0:
18430 		break;	/* Success! */
18431 	case EIO:
18432 		switch (ucmd_buf.uscsi_status) {
18433 		case STATUS_RESERVATION_CONFLICT:
18434 			status = EACCES;
18435 			break;
18436 		case STATUS_CHECK:
18437 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18438 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18439 			    KEY_ILLEGAL_REQUEST)) {
18440 				status = ENOTSUP;
18441 			}
18442 			break;
18443 		default:
18444 			break;
18445 		}
18446 		break;
18447 	default:
18448 		break;
18449 	}
18450 
18451 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
18452 
18453 	if (no_caller_buf == TRUE) {
18454 		kmem_free(data_bufp, data_len);
18455 	}
18456 
18457 	return (status);
18458 }
18459 
18460 
18461 /*
18462  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
18463  *
18464  * Description: This routine is the driver entry point for handling CD-ROM
18465  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
18466  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
18467  *		device.
18468  *
18469  *   Arguments: un  -   Pointer to soft state struct for the target.
18470  *		usr_cmd SCSI-3 reservation facility command (one of
18471  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
18472  *			SD_SCSI3_PREEMPTANDABORT)
18473  *		usr_bufp - user provided pointer register, reserve descriptor or
18474  *			preempt and abort structure (mhioc_register_t,
18475  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
18476  *
18477  * Return Code: 0   - Success
18478  *		EACCES
18479  *		ENOTSUP
18480  *		errno return code from sd_send_scsi_cmd()
18481  *
18482  *     Context: Can sleep. Does not return until command is completed.
18483  */
18484 
18485 static int
18486 sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un, uchar_t usr_cmd,
18487 	uchar_t	*usr_bufp)
18488 {
18489 	struct scsi_extended_sense	sense_buf;
18490 	union scsi_cdb		cdb;
18491 	struct uscsi_cmd	ucmd_buf;
18492 	int			status;
18493 	uchar_t			data_len = sizeof (sd_prout_t);
18494 	sd_prout_t		*prp;
18495 
18496 	ASSERT(un != NULL);
18497 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18498 	ASSERT(data_len == 24);	/* required by scsi spec */
18499 
18500 	SD_TRACE(SD_LOG_IO, un,
18501 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
18502 
18503 	if (usr_bufp == NULL) {
18504 		return (EINVAL);
18505 	}
18506 
18507 	bzero(&cdb, sizeof (cdb));
18508 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18509 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18510 	prp = kmem_zalloc(data_len, KM_SLEEP);
18511 
18512 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
18513 	cdb.cdb_opaque[1] = usr_cmd;
18514 	FORMG1COUNT(&cdb, data_len);
18515 
18516 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18517 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18518 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
18519 	ucmd_buf.uscsi_buflen	= data_len;
18520 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18521 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18522 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
18523 	ucmd_buf.uscsi_timeout	= 60;
18524 
18525 	switch (usr_cmd) {
18526 	case SD_SCSI3_REGISTER: {
18527 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
18528 
18529 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18530 		bcopy(ptr->newkey.key, prp->service_key,
18531 		    MHIOC_RESV_KEY_SIZE);
18532 		prp->aptpl = ptr->aptpl;
18533 		break;
18534 	}
18535 	case SD_SCSI3_RESERVE:
18536 	case SD_SCSI3_RELEASE: {
18537 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
18538 
18539 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18540 		prp->scope_address = BE_32(ptr->scope_specific_addr);
18541 		cdb.cdb_opaque[2] = ptr->type;
18542 		break;
18543 	}
18544 	case SD_SCSI3_PREEMPTANDABORT: {
18545 		mhioc_preemptandabort_t *ptr =
18546 		    (mhioc_preemptandabort_t *)usr_bufp;
18547 
18548 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18549 		bcopy(ptr->victim_key.key, prp->service_key,
18550 		    MHIOC_RESV_KEY_SIZE);
18551 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
18552 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
18553 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
18554 		break;
18555 	}
18556 	case SD_SCSI3_REGISTERANDIGNOREKEY:
18557 	{
18558 		mhioc_registerandignorekey_t *ptr;
18559 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
18560 		bcopy(ptr->newkey.key,
18561 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
18562 		prp->aptpl = ptr->aptpl;
18563 		break;
18564 	}
18565 	default:
18566 		ASSERT(FALSE);
18567 		break;
18568 	}
18569 
18570 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18571 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18572 
18573 	switch (status) {
18574 	case 0:
18575 		break;	/* Success! */
18576 	case EIO:
18577 		switch (ucmd_buf.uscsi_status) {
18578 		case STATUS_RESERVATION_CONFLICT:
18579 			status = EACCES;
18580 			break;
18581 		case STATUS_CHECK:
18582 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18583 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18584 			    KEY_ILLEGAL_REQUEST)) {
18585 				status = ENOTSUP;
18586 			}
18587 			break;
18588 		default:
18589 			break;
18590 		}
18591 		break;
18592 	default:
18593 		break;
18594 	}
18595 
18596 	kmem_free(prp, data_len);
18597 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
18598 	return (status);
18599 }
18600 
18601 
18602 /*
18603  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
18604  *
18605  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
18606  *
18607  *   Arguments: un - pointer to the target's soft state struct
18608  *              dkc - pointer to the callback structure
18609  *
18610  * Return Code: 0 - success
18611  *		errno-type error code
18612  *
18613  *     Context: kernel thread context only.
18614  *
18615  *  _______________________________________________________________
18616  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
18617  * |FLUSH_VOLATILE|              | operation                       |
18618  * |______________|______________|_________________________________|
18619  * | 0            | NULL         | Synchronous flush on both       |
18620  * |              |              | volatile and non-volatile cache |
18621  * |______________|______________|_________________________________|
18622  * | 1            | NULL         | Synchronous flush on volatile   |
18623  * |              |              | cache; disk drivers may suppress|
18624  * |              |              | flush if disk table indicates   |
18625  * |              |              | non-volatile cache              |
18626  * |______________|______________|_________________________________|
18627  * | 0            | !NULL        | Asynchronous flush on both      |
18628  * |              |              | volatile and non-volatile cache;|
18629  * |______________|______________|_________________________________|
18630  * | 1            | !NULL        | Asynchronous flush on volatile  |
18631  * |              |              | cache; disk drivers may suppress|
18632  * |              |              | flush if disk table indicates   |
18633  * |              |              | non-volatile cache              |
18634  * |______________|______________|_________________________________|
18635  *
18636  */
18637 
18638 static int
18639 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
18640 {
18641 	struct sd_uscsi_info	*uip;
18642 	struct uscsi_cmd	*uscmd;
18643 	union scsi_cdb		*cdb;
18644 	struct buf		*bp;
18645 	int			rval = 0;
18646 	int			is_async;
18647 
18648 	SD_TRACE(SD_LOG_IO, un,
18649 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
18650 
18651 	ASSERT(un != NULL);
18652 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18653 
18654 	if (dkc == NULL || dkc->dkc_callback == NULL) {
18655 		is_async = FALSE;
18656 	} else {
18657 		is_async = TRUE;
18658 	}
18659 
18660 	mutex_enter(SD_MUTEX(un));
18661 	/* check whether cache flush should be suppressed */
18662 	if (un->un_f_suppress_cache_flush == TRUE) {
18663 		mutex_exit(SD_MUTEX(un));
18664 		/*
18665 		 * suppress the cache flush if the device is told to do
18666 		 * so by sd.conf or disk table
18667 		 */
18668 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
18669 		    skip the cache flush since suppress_cache_flush is %d!\n",
18670 		    un->un_f_suppress_cache_flush);
18671 
18672 		if (is_async == TRUE) {
18673 			/* invoke callback for asynchronous flush */
18674 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
18675 		}
18676 		return (rval);
18677 	}
18678 	mutex_exit(SD_MUTEX(un));
18679 
18680 	/*
18681 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
18682 	 * set properly
18683 	 */
18684 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
18685 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
18686 
18687 	mutex_enter(SD_MUTEX(un));
18688 	if (dkc != NULL && un->un_f_sync_nv_supported &&
18689 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
18690 		/*
18691 		 * if the device supports SYNC_NV bit, turn on
18692 		 * the SYNC_NV bit to only flush volatile cache
18693 		 */
18694 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
18695 	}
18696 	mutex_exit(SD_MUTEX(un));
18697 
18698 	/*
18699 	 * First get some memory for the uscsi_cmd struct and cdb
18700 	 * and initialize for SYNCHRONIZE_CACHE cmd.
18701 	 */
18702 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
18703 	uscmd->uscsi_cdblen = CDB_GROUP1;
18704 	uscmd->uscsi_cdb = (caddr_t)cdb;
18705 	uscmd->uscsi_bufaddr = NULL;
18706 	uscmd->uscsi_buflen = 0;
18707 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
18708 	uscmd->uscsi_rqlen = SENSE_LENGTH;
18709 	uscmd->uscsi_rqresid = SENSE_LENGTH;
18710 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
18711 	uscmd->uscsi_timeout = sd_io_time;
18712 
18713 	/*
18714 	 * Allocate an sd_uscsi_info struct and fill it with the info
18715 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
18716 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
18717 	 * since we allocate the buf here in this function, we do not
18718 	 * need to preserve the prior contents of b_private.
18719 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
18720 	 */
18721 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
18722 	uip->ui_flags = SD_PATH_DIRECT;
18723 	uip->ui_cmdp  = uscmd;
18724 
18725 	bp = getrbuf(KM_SLEEP);
18726 	bp->b_private = uip;
18727 
18728 	/*
18729 	 * Setup buffer to carry uscsi request.
18730 	 */
18731 	bp->b_flags  = B_BUSY;
18732 	bp->b_bcount = 0;
18733 	bp->b_blkno  = 0;
18734 
18735 	if (is_async == TRUE) {
18736 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
18737 		uip->ui_dkc = *dkc;
18738 	}
18739 
18740 	bp->b_edev = SD_GET_DEV(un);
18741 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
18742 
18743 	(void) sd_uscsi_strategy(bp);
18744 
18745 	/*
18746 	 * If synchronous request, wait for completion
18747 	 * If async just return and let b_iodone callback
18748 	 * cleanup.
18749 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
18750 	 * but it was also incremented in sd_uscsi_strategy(), so
18751 	 * we should be ok.
18752 	 */
18753 	if (is_async == FALSE) {
18754 		(void) biowait(bp);
18755 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
18756 	}
18757 
18758 	return (rval);
18759 }
18760 
18761 
18762 static int
18763 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
18764 {
18765 	struct sd_uscsi_info *uip;
18766 	struct uscsi_cmd *uscmd;
18767 	uint8_t *sense_buf;
18768 	struct sd_lun *un;
18769 	int status;
18770 	union scsi_cdb *cdb;
18771 
18772 	uip = (struct sd_uscsi_info *)(bp->b_private);
18773 	ASSERT(uip != NULL);
18774 
18775 	uscmd = uip->ui_cmdp;
18776 	ASSERT(uscmd != NULL);
18777 
18778 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
18779 	ASSERT(sense_buf != NULL);
18780 
18781 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
18782 	ASSERT(un != NULL);
18783 
18784 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
18785 
18786 	status = geterror(bp);
18787 	switch (status) {
18788 	case 0:
18789 		break;	/* Success! */
18790 	case EIO:
18791 		switch (uscmd->uscsi_status) {
18792 		case STATUS_RESERVATION_CONFLICT:
18793 			/* Ignore reservation conflict */
18794 			status = 0;
18795 			goto done;
18796 
18797 		case STATUS_CHECK:
18798 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
18799 			    (scsi_sense_key(sense_buf) ==
18800 			    KEY_ILLEGAL_REQUEST)) {
18801 				/* Ignore Illegal Request error */
18802 				if (cdb->cdb_un.tag|SD_SYNC_NV_BIT) {
18803 					mutex_enter(SD_MUTEX(un));
18804 					un->un_f_sync_nv_supported = FALSE;
18805 					mutex_exit(SD_MUTEX(un));
18806 					status = 0;
18807 					SD_TRACE(SD_LOG_IO, un,
18808 					    "un_f_sync_nv_supported \
18809 					    is set to false.\n");
18810 					goto done;
18811 				}
18812 
18813 				mutex_enter(SD_MUTEX(un));
18814 				un->un_f_sync_cache_supported = FALSE;
18815 				mutex_exit(SD_MUTEX(un));
18816 				SD_TRACE(SD_LOG_IO, un,
18817 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
18818 				    un_f_sync_cache_supported set to false \
18819 				    with asc = %x, ascq = %x\n",
18820 				    scsi_sense_asc(sense_buf),
18821 				    scsi_sense_ascq(sense_buf));
18822 				status = ENOTSUP;
18823 				goto done;
18824 			}
18825 			break;
18826 		default:
18827 			break;
18828 		}
18829 		/* FALLTHRU */
18830 	default:
18831 		/*
18832 		 * Don't log an error message if this device
18833 		 * has removable media.
18834 		 */
18835 		if (!un->un_f_has_removable_media) {
18836 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18837 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
18838 		}
18839 		break;
18840 	}
18841 
18842 done:
18843 	if (uip->ui_dkc.dkc_callback != NULL) {
18844 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
18845 	}
18846 
18847 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
18848 	freerbuf(bp);
18849 	kmem_free(uip, sizeof (struct sd_uscsi_info));
18850 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
18851 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
18852 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
18853 
18854 	return (status);
18855 }
18856 
18857 
18858 /*
18859  *    Function: sd_send_scsi_GET_CONFIGURATION
18860  *
18861  * Description: Issues the get configuration command to the device.
18862  *		Called from sd_check_for_writable_cd & sd_get_media_info
18863  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
18864  *   Arguments: un
18865  *		ucmdbuf
18866  *		rqbuf
18867  *		rqbuflen
18868  *		bufaddr
18869  *		buflen
18870  *		path_flag
18871  *
18872  * Return Code: 0   - Success
18873  *		errno return code from sd_send_scsi_cmd()
18874  *
18875  *     Context: Can sleep. Does not return until command is completed.
18876  *
18877  */
18878 
18879 static int
18880 sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un, struct uscsi_cmd *ucmdbuf,
18881 	uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
18882 	int path_flag)
18883 {
18884 	char	cdb[CDB_GROUP1];
18885 	int	status;
18886 
18887 	ASSERT(un != NULL);
18888 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18889 	ASSERT(bufaddr != NULL);
18890 	ASSERT(ucmdbuf != NULL);
18891 	ASSERT(rqbuf != NULL);
18892 
18893 	SD_TRACE(SD_LOG_IO, un,
18894 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
18895 
18896 	bzero(cdb, sizeof (cdb));
18897 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
18898 	bzero(rqbuf, rqbuflen);
18899 	bzero(bufaddr, buflen);
18900 
18901 	/*
18902 	 * Set up cdb field for the get configuration command.
18903 	 */
18904 	cdb[0] = SCMD_GET_CONFIGURATION;
18905 	cdb[1] = 0x02;  /* Requested Type */
18906 	cdb[8] = SD_PROFILE_HEADER_LEN;
18907 	ucmdbuf->uscsi_cdb = cdb;
18908 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
18909 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
18910 	ucmdbuf->uscsi_buflen = buflen;
18911 	ucmdbuf->uscsi_timeout = sd_io_time;
18912 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
18913 	ucmdbuf->uscsi_rqlen = rqbuflen;
18914 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
18915 
18916 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, FKIOCTL,
18917 	    UIO_SYSSPACE, path_flag);
18918 
18919 	switch (status) {
18920 	case 0:
18921 		break;  /* Success! */
18922 	case EIO:
18923 		switch (ucmdbuf->uscsi_status) {
18924 		case STATUS_RESERVATION_CONFLICT:
18925 			status = EACCES;
18926 			break;
18927 		default:
18928 			break;
18929 		}
18930 		break;
18931 	default:
18932 		break;
18933 	}
18934 
18935 	if (status == 0) {
18936 		SD_DUMP_MEMORY(un, SD_LOG_IO,
18937 		    "sd_send_scsi_GET_CONFIGURATION: data",
18938 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
18939 	}
18940 
18941 	SD_TRACE(SD_LOG_IO, un,
18942 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
18943 
18944 	return (status);
18945 }
18946 
18947 /*
18948  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
18949  *
18950  * Description: Issues the get configuration command to the device to
18951  *              retrieve a specific feature. Called from
18952  *		sd_check_for_writable_cd & sd_set_mmc_caps.
18953  *   Arguments: un
18954  *              ucmdbuf
18955  *              rqbuf
18956  *              rqbuflen
18957  *              bufaddr
18958  *              buflen
18959  *		feature
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 static int
18968 sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
18969 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
18970 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag)
18971 {
18972 	char    cdb[CDB_GROUP1];
18973 	int	status;
18974 
18975 	ASSERT(un != NULL);
18976 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18977 	ASSERT(bufaddr != NULL);
18978 	ASSERT(ucmdbuf != NULL);
18979 	ASSERT(rqbuf != NULL);
18980 
18981 	SD_TRACE(SD_LOG_IO, un,
18982 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
18983 
18984 	bzero(cdb, sizeof (cdb));
18985 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
18986 	bzero(rqbuf, rqbuflen);
18987 	bzero(bufaddr, buflen);
18988 
18989 	/*
18990 	 * Set up cdb field for the get configuration command.
18991 	 */
18992 	cdb[0] = SCMD_GET_CONFIGURATION;
18993 	cdb[1] = 0x02;  /* Requested Type */
18994 	cdb[3] = feature;
18995 	cdb[8] = buflen;
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_feature_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_feature_GET_CONFIGURATION: exit\n");
19032 
19033 	return (status);
19034 }
19035 
19036 
19037 /*
19038  *    Function: sd_send_scsi_MODE_SENSE
19039  *
19040  * Description: Utility function for issuing a scsi MODE SENSE command.
19041  *		Note: This routine uses a consistent implementation for Group0,
19042  *		Group1, and Group2 commands across all platforms. ATAPI devices
19043  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
19044  *
19045  *   Arguments: un - pointer to the softstate struct for the target.
19046  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
19047  *			  CDB_GROUP[1|2] (10 byte).
19048  *		bufaddr - buffer for page data retrieved from the target.
19049  *		buflen - size of page to be retrieved.
19050  *		page_code - page code of data to be retrieved from the target.
19051  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19052  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19053  *			to use the USCSI "direct" chain and bypass the normal
19054  *			command waitq.
19055  *
19056  * Return Code: 0   - Success
19057  *		errno return code from sd_send_scsi_cmd()
19058  *
19059  *     Context: Can sleep. Does not return until command is completed.
19060  */
19061 
19062 static int
19063 sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
19064 	size_t buflen,  uchar_t page_code, int path_flag)
19065 {
19066 	struct	scsi_extended_sense	sense_buf;
19067 	union scsi_cdb		cdb;
19068 	struct uscsi_cmd	ucmd_buf;
19069 	int			status;
19070 	int			headlen;
19071 
19072 	ASSERT(un != NULL);
19073 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19074 	ASSERT(bufaddr != NULL);
19075 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
19076 	    (cdbsize == CDB_GROUP2));
19077 
19078 	SD_TRACE(SD_LOG_IO, un,
19079 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
19080 
19081 	bzero(&cdb, sizeof (cdb));
19082 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19083 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19084 	bzero(bufaddr, buflen);
19085 
19086 	if (cdbsize == CDB_GROUP0) {
19087 		cdb.scc_cmd = SCMD_MODE_SENSE;
19088 		cdb.cdb_opaque[2] = page_code;
19089 		FORMG0COUNT(&cdb, buflen);
19090 		headlen = MODE_HEADER_LENGTH;
19091 	} else {
19092 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
19093 		cdb.cdb_opaque[2] = page_code;
19094 		FORMG1COUNT(&cdb, buflen);
19095 		headlen = MODE_HEADER_LENGTH_GRP2;
19096 	}
19097 
19098 	ASSERT(headlen <= buflen);
19099 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19100 
19101 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19102 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19103 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19104 	ucmd_buf.uscsi_buflen	= buflen;
19105 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19106 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19107 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19108 	ucmd_buf.uscsi_timeout	= 60;
19109 
19110 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19111 	    UIO_SYSSPACE, path_flag);
19112 
19113 	switch (status) {
19114 	case 0:
19115 		/*
19116 		 * sr_check_wp() uses 0x3f page code and check the header of
19117 		 * mode page to determine if target device is write-protected.
19118 		 * But some USB devices return 0 bytes for 0x3f page code. For
19119 		 * this case, make sure that mode page header is returned at
19120 		 * least.
19121 		 */
19122 		if (buflen - ucmd_buf.uscsi_resid <  headlen)
19123 			status = EIO;
19124 		break;	/* Success! */
19125 	case EIO:
19126 		switch (ucmd_buf.uscsi_status) {
19127 		case STATUS_RESERVATION_CONFLICT:
19128 			status = EACCES;
19129 			break;
19130 		default:
19131 			break;
19132 		}
19133 		break;
19134 	default:
19135 		break;
19136 	}
19137 
19138 	if (status == 0) {
19139 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
19140 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19141 	}
19142 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
19143 
19144 	return (status);
19145 }
19146 
19147 
19148 /*
19149  *    Function: sd_send_scsi_MODE_SELECT
19150  *
19151  * Description: Utility function for issuing a scsi MODE SELECT command.
19152  *		Note: This routine uses a consistent implementation for Group0,
19153  *		Group1, and Group2 commands across all platforms. ATAPI devices
19154  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
19155  *
19156  *   Arguments: un - pointer to the softstate struct for the target.
19157  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
19158  *			  CDB_GROUP[1|2] (10 byte).
19159  *		bufaddr - buffer for page data retrieved from the target.
19160  *		buflen - size of page to be retrieved.
19161  *		save_page - boolean to determin if SP bit should be set.
19162  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19163  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19164  *			to use the USCSI "direct" chain and bypass the normal
19165  *			command waitq.
19166  *
19167  * Return Code: 0   - Success
19168  *		errno return code from sd_send_scsi_cmd()
19169  *
19170  *     Context: Can sleep. Does not return until command is completed.
19171  */
19172 
19173 static int
19174 sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
19175 	size_t buflen,  uchar_t save_page, int path_flag)
19176 {
19177 	struct	scsi_extended_sense	sense_buf;
19178 	union scsi_cdb		cdb;
19179 	struct uscsi_cmd	ucmd_buf;
19180 	int			status;
19181 
19182 	ASSERT(un != NULL);
19183 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19184 	ASSERT(bufaddr != NULL);
19185 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
19186 	    (cdbsize == CDB_GROUP2));
19187 
19188 	SD_TRACE(SD_LOG_IO, un,
19189 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
19190 
19191 	bzero(&cdb, sizeof (cdb));
19192 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19193 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19194 
19195 	/* Set the PF bit for many third party drives */
19196 	cdb.cdb_opaque[1] = 0x10;
19197 
19198 	/* Set the savepage(SP) bit if given */
19199 	if (save_page == SD_SAVE_PAGE) {
19200 		cdb.cdb_opaque[1] |= 0x01;
19201 	}
19202 
19203 	if (cdbsize == CDB_GROUP0) {
19204 		cdb.scc_cmd = SCMD_MODE_SELECT;
19205 		FORMG0COUNT(&cdb, buflen);
19206 	} else {
19207 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
19208 		FORMG1COUNT(&cdb, buflen);
19209 	}
19210 
19211 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19212 
19213 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19214 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19215 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19216 	ucmd_buf.uscsi_buflen	= buflen;
19217 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19218 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19219 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
19220 	ucmd_buf.uscsi_timeout	= 60;
19221 
19222 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19223 	    UIO_SYSSPACE, path_flag);
19224 
19225 	switch (status) {
19226 	case 0:
19227 		break;	/* Success! */
19228 	case EIO:
19229 		switch (ucmd_buf.uscsi_status) {
19230 		case STATUS_RESERVATION_CONFLICT:
19231 			status = EACCES;
19232 			break;
19233 		default:
19234 			break;
19235 		}
19236 		break;
19237 	default:
19238 		break;
19239 	}
19240 
19241 	if (status == 0) {
19242 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
19243 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19244 	}
19245 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
19246 
19247 	return (status);
19248 }
19249 
19250 
19251 /*
19252  *    Function: sd_send_scsi_RDWR
19253  *
19254  * Description: Issue a scsi READ or WRITE command with the given parameters.
19255  *
19256  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19257  *		cmd:	 SCMD_READ or SCMD_WRITE
19258  *		bufaddr: Address of caller's buffer to receive the RDWR data
19259  *		buflen:  Length of caller's buffer receive the RDWR data.
19260  *		start_block: Block number for the start of the RDWR operation.
19261  *			 (Assumes target-native block size.)
19262  *		residp:  Pointer to variable to receive the redisual of the
19263  *			 RDWR operation (may be NULL of no residual requested).
19264  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19265  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19266  *			to use the USCSI "direct" chain and bypass the normal
19267  *			command waitq.
19268  *
19269  * Return Code: 0   - Success
19270  *		errno return code from sd_send_scsi_cmd()
19271  *
19272  *     Context: Can sleep. Does not return until command is completed.
19273  */
19274 
19275 static int
19276 sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
19277 	size_t buflen, daddr_t start_block, int path_flag)
19278 {
19279 	struct	scsi_extended_sense	sense_buf;
19280 	union scsi_cdb		cdb;
19281 	struct uscsi_cmd	ucmd_buf;
19282 	uint32_t		block_count;
19283 	int			status;
19284 	int			cdbsize;
19285 	uchar_t			flag;
19286 
19287 	ASSERT(un != NULL);
19288 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19289 	ASSERT(bufaddr != NULL);
19290 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
19291 
19292 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
19293 
19294 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
19295 		return (EINVAL);
19296 	}
19297 
19298 	mutex_enter(SD_MUTEX(un));
19299 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
19300 	mutex_exit(SD_MUTEX(un));
19301 
19302 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
19303 
19304 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
19305 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
19306 	    bufaddr, buflen, start_block, block_count);
19307 
19308 	bzero(&cdb, sizeof (cdb));
19309 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19310 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19311 
19312 	/* Compute CDB size to use */
19313 	if (start_block > 0xffffffff)
19314 		cdbsize = CDB_GROUP4;
19315 	else if ((start_block & 0xFFE00000) ||
19316 	    (un->un_f_cfg_is_atapi == TRUE))
19317 		cdbsize = CDB_GROUP1;
19318 	else
19319 		cdbsize = CDB_GROUP0;
19320 
19321 	switch (cdbsize) {
19322 	case CDB_GROUP0:	/* 6-byte CDBs */
19323 		cdb.scc_cmd = cmd;
19324 		FORMG0ADDR(&cdb, start_block);
19325 		FORMG0COUNT(&cdb, block_count);
19326 		break;
19327 	case CDB_GROUP1:	/* 10-byte CDBs */
19328 		cdb.scc_cmd = cmd | SCMD_GROUP1;
19329 		FORMG1ADDR(&cdb, start_block);
19330 		FORMG1COUNT(&cdb, block_count);
19331 		break;
19332 	case CDB_GROUP4:	/* 16-byte CDBs */
19333 		cdb.scc_cmd = cmd | SCMD_GROUP4;
19334 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
19335 		FORMG4COUNT(&cdb, block_count);
19336 		break;
19337 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
19338 	default:
19339 		/* All others reserved */
19340 		return (EINVAL);
19341 	}
19342 
19343 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
19344 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19345 
19346 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19347 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19348 	ucmd_buf.uscsi_bufaddr	= bufaddr;
19349 	ucmd_buf.uscsi_buflen	= buflen;
19350 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19351 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19352 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
19353 	ucmd_buf.uscsi_timeout	= 60;
19354 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19355 	    UIO_SYSSPACE, path_flag);
19356 	switch (status) {
19357 	case 0:
19358 		break;	/* Success! */
19359 	case EIO:
19360 		switch (ucmd_buf.uscsi_status) {
19361 		case STATUS_RESERVATION_CONFLICT:
19362 			status = EACCES;
19363 			break;
19364 		default:
19365 			break;
19366 		}
19367 		break;
19368 	default:
19369 		break;
19370 	}
19371 
19372 	if (status == 0) {
19373 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
19374 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19375 	}
19376 
19377 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
19378 
19379 	return (status);
19380 }
19381 
19382 
19383 /*
19384  *    Function: sd_send_scsi_LOG_SENSE
19385  *
19386  * Description: Issue a scsi LOG_SENSE command with the given parameters.
19387  *
19388  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19389  *
19390  * Return Code: 0   - Success
19391  *		errno return code from sd_send_scsi_cmd()
19392  *
19393  *     Context: Can sleep. Does not return until command is completed.
19394  */
19395 
19396 static int
19397 sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr, uint16_t buflen,
19398 	uchar_t page_code, uchar_t page_control, uint16_t param_ptr,
19399 	int path_flag)
19400 
19401 {
19402 	struct	scsi_extended_sense	sense_buf;
19403 	union scsi_cdb		cdb;
19404 	struct uscsi_cmd	ucmd_buf;
19405 	int			status;
19406 
19407 	ASSERT(un != NULL);
19408 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19409 
19410 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
19411 
19412 	bzero(&cdb, sizeof (cdb));
19413 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19414 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19415 
19416 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
19417 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
19418 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
19419 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
19420 	FORMG1COUNT(&cdb, buflen);
19421 
19422 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19423 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19424 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19425 	ucmd_buf.uscsi_buflen	= buflen;
19426 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19427 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19428 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19429 	ucmd_buf.uscsi_timeout	= 60;
19430 
19431 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19432 	    UIO_SYSSPACE, path_flag);
19433 
19434 	switch (status) {
19435 	case 0:
19436 		break;
19437 	case EIO:
19438 		switch (ucmd_buf.uscsi_status) {
19439 		case STATUS_RESERVATION_CONFLICT:
19440 			status = EACCES;
19441 			break;
19442 		case STATUS_CHECK:
19443 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19444 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
19445 				KEY_ILLEGAL_REQUEST) &&
19446 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
19447 				/*
19448 				 * ASC 0x24: INVALID FIELD IN CDB
19449 				 */
19450 				switch (page_code) {
19451 				case START_STOP_CYCLE_PAGE:
19452 					/*
19453 					 * The start stop cycle counter is
19454 					 * implemented as page 0x31 in earlier
19455 					 * generation disks. In new generation
19456 					 * disks the start stop cycle counter is
19457 					 * implemented as page 0xE. To properly
19458 					 * handle this case if an attempt for
19459 					 * log page 0xE is made and fails we
19460 					 * will try again using page 0x31.
19461 					 *
19462 					 * Network storage BU committed to
19463 					 * maintain the page 0x31 for this
19464 					 * purpose and will not have any other
19465 					 * page implemented with page code 0x31
19466 					 * until all disks transition to the
19467 					 * standard page.
19468 					 */
19469 					mutex_enter(SD_MUTEX(un));
19470 					un->un_start_stop_cycle_page =
19471 					    START_STOP_CYCLE_VU_PAGE;
19472 					cdb.cdb_opaque[2] =
19473 					    (char)(page_control << 6) |
19474 					    un->un_start_stop_cycle_page;
19475 					mutex_exit(SD_MUTEX(un));
19476 					status = sd_send_scsi_cmd(
19477 					    SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19478 					    UIO_SYSSPACE, path_flag);
19479 
19480 					break;
19481 				case TEMPERATURE_PAGE:
19482 					status = ENOTTY;
19483 					break;
19484 				default:
19485 					break;
19486 				}
19487 			}
19488 			break;
19489 		default:
19490 			break;
19491 		}
19492 		break;
19493 	default:
19494 		break;
19495 	}
19496 
19497 	if (status == 0) {
19498 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
19499 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19500 	}
19501 
19502 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
19503 
19504 	return (status);
19505 }
19506 
19507 
19508 /*
19509  *    Function: sdioctl
19510  *
19511  * Description: Driver's ioctl(9e) entry point function.
19512  *
19513  *   Arguments: dev     - device number
19514  *		cmd     - ioctl operation to be performed
19515  *		arg     - user argument, contains data to be set or reference
19516  *			  parameter for get
19517  *		flag    - bit flag, indicating open settings, 32/64 bit type
19518  *		cred_p  - user credential pointer
19519  *		rval_p  - calling process return value (OPT)
19520  *
19521  * Return Code: EINVAL
19522  *		ENOTTY
19523  *		ENXIO
19524  *		EIO
19525  *		EFAULT
19526  *		ENOTSUP
19527  *		EPERM
19528  *
19529  *     Context: Called from the device switch at normal priority.
19530  */
19531 
19532 static int
19533 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
19534 {
19535 	struct sd_lun	*un = NULL;
19536 	int		err = 0;
19537 	int		i = 0;
19538 	cred_t		*cr;
19539 	int		tmprval = EINVAL;
19540 	int 		is_valid;
19541 
19542 	/*
19543 	 * All device accesses go thru sdstrategy where we check on suspend
19544 	 * status
19545 	 */
19546 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
19547 		return (ENXIO);
19548 	}
19549 
19550 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19551 
19552 
19553 	is_valid = SD_IS_VALID_LABEL(un);
19554 
19555 	/*
19556 	 * Moved this wait from sd_uscsi_strategy to here for
19557 	 * reasons of deadlock prevention. Internal driver commands,
19558 	 * specifically those to change a devices power level, result
19559 	 * in a call to sd_uscsi_strategy.
19560 	 */
19561 	mutex_enter(SD_MUTEX(un));
19562 	while ((un->un_state == SD_STATE_SUSPENDED) ||
19563 	    (un->un_state == SD_STATE_PM_CHANGING)) {
19564 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
19565 	}
19566 	/*
19567 	 * Twiddling the counter here protects commands from now
19568 	 * through to the top of sd_uscsi_strategy. Without the
19569 	 * counter inc. a power down, for example, could get in
19570 	 * after the above check for state is made and before
19571 	 * execution gets to the top of sd_uscsi_strategy.
19572 	 * That would cause problems.
19573 	 */
19574 	un->un_ncmds_in_driver++;
19575 
19576 	if (!is_valid &&
19577 	    (flag & (FNDELAY | FNONBLOCK))) {
19578 		switch (cmd) {
19579 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
19580 		case DKIOCGVTOC:
19581 		case DKIOCGAPART:
19582 		case DKIOCPARTINFO:
19583 		case DKIOCSGEOM:
19584 		case DKIOCSAPART:
19585 		case DKIOCGETEFI:
19586 		case DKIOCPARTITION:
19587 		case DKIOCSVTOC:
19588 		case DKIOCSETEFI:
19589 		case DKIOCGMBOOT:
19590 		case DKIOCSMBOOT:
19591 		case DKIOCG_PHYGEOM:
19592 		case DKIOCG_VIRTGEOM:
19593 			/* let cmlb handle it */
19594 			goto skip_ready_valid;
19595 
19596 		case CDROMPAUSE:
19597 		case CDROMRESUME:
19598 		case CDROMPLAYMSF:
19599 		case CDROMPLAYTRKIND:
19600 		case CDROMREADTOCHDR:
19601 		case CDROMREADTOCENTRY:
19602 		case CDROMSTOP:
19603 		case CDROMSTART:
19604 		case CDROMVOLCTRL:
19605 		case CDROMSUBCHNL:
19606 		case CDROMREADMODE2:
19607 		case CDROMREADMODE1:
19608 		case CDROMREADOFFSET:
19609 		case CDROMSBLKMODE:
19610 		case CDROMGBLKMODE:
19611 		case CDROMGDRVSPEED:
19612 		case CDROMSDRVSPEED:
19613 		case CDROMCDDA:
19614 		case CDROMCDXA:
19615 		case CDROMSUBCODE:
19616 			if (!ISCD(un)) {
19617 				un->un_ncmds_in_driver--;
19618 				ASSERT(un->un_ncmds_in_driver >= 0);
19619 				mutex_exit(SD_MUTEX(un));
19620 				return (ENOTTY);
19621 			}
19622 			break;
19623 		case FDEJECT:
19624 		case DKIOCEJECT:
19625 		case CDROMEJECT:
19626 			if (!un->un_f_eject_media_supported) {
19627 				un->un_ncmds_in_driver--;
19628 				ASSERT(un->un_ncmds_in_driver >= 0);
19629 				mutex_exit(SD_MUTEX(un));
19630 				return (ENOTTY);
19631 			}
19632 			break;
19633 		case DKIOCFLUSHWRITECACHE:
19634 			mutex_exit(SD_MUTEX(un));
19635 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
19636 			if (err != 0) {
19637 				mutex_enter(SD_MUTEX(un));
19638 				un->un_ncmds_in_driver--;
19639 				ASSERT(un->un_ncmds_in_driver >= 0);
19640 				mutex_exit(SD_MUTEX(un));
19641 				return (EIO);
19642 			}
19643 			mutex_enter(SD_MUTEX(un));
19644 			/* FALLTHROUGH */
19645 		case DKIOCREMOVABLE:
19646 		case DKIOCHOTPLUGGABLE:
19647 		case DKIOCINFO:
19648 		case DKIOCGMEDIAINFO:
19649 		case MHIOCENFAILFAST:
19650 		case MHIOCSTATUS:
19651 		case MHIOCTKOWN:
19652 		case MHIOCRELEASE:
19653 		case MHIOCGRP_INKEYS:
19654 		case MHIOCGRP_INRESV:
19655 		case MHIOCGRP_REGISTER:
19656 		case MHIOCGRP_RESERVE:
19657 		case MHIOCGRP_PREEMPTANDABORT:
19658 		case MHIOCGRP_REGISTERANDIGNOREKEY:
19659 		case CDROMCLOSETRAY:
19660 		case USCSICMD:
19661 			goto skip_ready_valid;
19662 		default:
19663 			break;
19664 		}
19665 
19666 		mutex_exit(SD_MUTEX(un));
19667 		err = sd_ready_and_valid(un);
19668 		mutex_enter(SD_MUTEX(un));
19669 
19670 		if (err != SD_READY_VALID) {
19671 			switch (cmd) {
19672 			case DKIOCSTATE:
19673 			case CDROMGDRVSPEED:
19674 			case CDROMSDRVSPEED:
19675 			case FDEJECT:	/* for eject command */
19676 			case DKIOCEJECT:
19677 			case CDROMEJECT:
19678 			case DKIOCREMOVABLE:
19679 			case DKIOCHOTPLUGGABLE:
19680 				break;
19681 			default:
19682 				if (un->un_f_has_removable_media) {
19683 					err = ENXIO;
19684 				} else {
19685 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
19686 					if (err == SD_RESERVED_BY_OTHERS) {
19687 						err = EACCES;
19688 					} else {
19689 						err = EIO;
19690 					}
19691 				}
19692 				un->un_ncmds_in_driver--;
19693 				ASSERT(un->un_ncmds_in_driver >= 0);
19694 				mutex_exit(SD_MUTEX(un));
19695 				return (err);
19696 			}
19697 		}
19698 	}
19699 
19700 skip_ready_valid:
19701 	mutex_exit(SD_MUTEX(un));
19702 
19703 	switch (cmd) {
19704 	case DKIOCINFO:
19705 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
19706 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
19707 		break;
19708 
19709 	case DKIOCGMEDIAINFO:
19710 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
19711 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
19712 		break;
19713 
19714 	case DKIOCGGEOM:
19715 	case DKIOCGVTOC:
19716 	case DKIOCGAPART:
19717 	case DKIOCPARTINFO:
19718 	case DKIOCSGEOM:
19719 	case DKIOCSAPART:
19720 	case DKIOCGETEFI:
19721 	case DKIOCPARTITION:
19722 	case DKIOCSVTOC:
19723 	case DKIOCSETEFI:
19724 	case DKIOCGMBOOT:
19725 	case DKIOCSMBOOT:
19726 	case DKIOCG_PHYGEOM:
19727 	case DKIOCG_VIRTGEOM:
19728 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
19729 
19730 		/* TUR should spin up */
19731 
19732 		if (un->un_f_has_removable_media)
19733 			err = sd_send_scsi_TEST_UNIT_READY(un,
19734 			    SD_CHECK_FOR_MEDIA);
19735 		else
19736 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
19737 
19738 		if (err != 0)
19739 			break;
19740 
19741 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
19742 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
19743 
19744 		if ((err == 0) &&
19745 		    ((cmd == DKIOCSETEFI) ||
19746 		    (un->un_f_pkstats_enabled) &&
19747 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC))) {
19748 
19749 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
19750 			    (void *)SD_PATH_DIRECT);
19751 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
19752 				sd_set_pstats(un);
19753 				SD_TRACE(SD_LOG_IO_PARTITION, un,
19754 				    "sd_ioctl: un:0x%p pstats created and "
19755 				    "set\n", un);
19756 			}
19757 		}
19758 
19759 		if ((cmd == DKIOCSVTOC) ||
19760 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
19761 
19762 			mutex_enter(SD_MUTEX(un));
19763 			if (un->un_f_devid_supported &&
19764 			    (un->un_f_opt_fab_devid == TRUE)) {
19765 				if (un->un_devid == NULL) {
19766 					sd_register_devid(un, SD_DEVINFO(un),
19767 					    SD_TARGET_IS_UNRESERVED);
19768 				} else {
19769 					/*
19770 					 * The device id for this disk
19771 					 * has been fabricated. The
19772 					 * device id must be preserved
19773 					 * by writing it back out to
19774 					 * disk.
19775 					 */
19776 					if (sd_write_deviceid(un) != 0) {
19777 						ddi_devid_free(un->un_devid);
19778 						un->un_devid = NULL;
19779 					}
19780 				}
19781 			}
19782 			mutex_exit(SD_MUTEX(un));
19783 		}
19784 
19785 		break;
19786 
19787 	case DKIOCLOCK:
19788 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
19789 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
19790 		    SD_PATH_STANDARD);
19791 		break;
19792 
19793 	case DKIOCUNLOCK:
19794 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
19795 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
19796 		    SD_PATH_STANDARD);
19797 		break;
19798 
19799 	case DKIOCSTATE: {
19800 		enum dkio_state		state;
19801 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
19802 
19803 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
19804 			err = EFAULT;
19805 		} else {
19806 			err = sd_check_media(dev, state);
19807 			if (err == 0) {
19808 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
19809 				    sizeof (int), flag) != 0)
19810 					err = EFAULT;
19811 			}
19812 		}
19813 		break;
19814 	}
19815 
19816 	case DKIOCREMOVABLE:
19817 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
19818 		i = un->un_f_has_removable_media ? 1 : 0;
19819 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
19820 			err = EFAULT;
19821 		} else {
19822 			err = 0;
19823 		}
19824 		break;
19825 
19826 	case DKIOCHOTPLUGGABLE:
19827 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
19828 		i = un->un_f_is_hotpluggable ? 1 : 0;
19829 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
19830 			err = EFAULT;
19831 		} else {
19832 			err = 0;
19833 		}
19834 		break;
19835 
19836 	case DKIOCGTEMPERATURE:
19837 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
19838 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
19839 		break;
19840 
19841 	case MHIOCENFAILFAST:
19842 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
19843 		if ((err = drv_priv(cred_p)) == 0) {
19844 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
19845 		}
19846 		break;
19847 
19848 	case MHIOCTKOWN:
19849 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
19850 		if ((err = drv_priv(cred_p)) == 0) {
19851 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
19852 		}
19853 		break;
19854 
19855 	case MHIOCRELEASE:
19856 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
19857 		if ((err = drv_priv(cred_p)) == 0) {
19858 			err = sd_mhdioc_release(dev);
19859 		}
19860 		break;
19861 
19862 	case MHIOCSTATUS:
19863 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
19864 		if ((err = drv_priv(cred_p)) == 0) {
19865 			switch (sd_send_scsi_TEST_UNIT_READY(un, 0)) {
19866 			case 0:
19867 				err = 0;
19868 				break;
19869 			case EACCES:
19870 				*rval_p = 1;
19871 				err = 0;
19872 				break;
19873 			default:
19874 				err = EIO;
19875 				break;
19876 			}
19877 		}
19878 		break;
19879 
19880 	case MHIOCQRESERVE:
19881 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
19882 		if ((err = drv_priv(cred_p)) == 0) {
19883 			err = sd_reserve_release(dev, SD_RESERVE);
19884 		}
19885 		break;
19886 
19887 	case MHIOCREREGISTERDEVID:
19888 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
19889 		if (drv_priv(cred_p) == EPERM) {
19890 			err = EPERM;
19891 		} else if (!un->un_f_devid_supported) {
19892 			err = ENOTTY;
19893 		} else {
19894 			err = sd_mhdioc_register_devid(dev);
19895 		}
19896 		break;
19897 
19898 	case MHIOCGRP_INKEYS:
19899 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
19900 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
19901 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19902 				err = ENOTSUP;
19903 			} else {
19904 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
19905 				    flag);
19906 			}
19907 		}
19908 		break;
19909 
19910 	case MHIOCGRP_INRESV:
19911 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
19912 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
19913 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19914 				err = ENOTSUP;
19915 			} else {
19916 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
19917 			}
19918 		}
19919 		break;
19920 
19921 	case MHIOCGRP_REGISTER:
19922 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
19923 		if ((err = drv_priv(cred_p)) != EPERM) {
19924 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19925 				err = ENOTSUP;
19926 			} else if (arg != NULL) {
19927 				mhioc_register_t reg;
19928 				if (ddi_copyin((void *)arg, &reg,
19929 				    sizeof (mhioc_register_t), flag) != 0) {
19930 					err = EFAULT;
19931 				} else {
19932 					err =
19933 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
19934 					    un, SD_SCSI3_REGISTER,
19935 					    (uchar_t *)&reg);
19936 				}
19937 			}
19938 		}
19939 		break;
19940 
19941 	case MHIOCGRP_RESERVE:
19942 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
19943 		if ((err = drv_priv(cred_p)) != EPERM) {
19944 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19945 				err = ENOTSUP;
19946 			} else if (arg != NULL) {
19947 				mhioc_resv_desc_t resv_desc;
19948 				if (ddi_copyin((void *)arg, &resv_desc,
19949 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
19950 					err = EFAULT;
19951 				} else {
19952 					err =
19953 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
19954 					    un, SD_SCSI3_RESERVE,
19955 					    (uchar_t *)&resv_desc);
19956 				}
19957 			}
19958 		}
19959 		break;
19960 
19961 	case MHIOCGRP_PREEMPTANDABORT:
19962 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
19963 		if ((err = drv_priv(cred_p)) != EPERM) {
19964 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19965 				err = ENOTSUP;
19966 			} else if (arg != NULL) {
19967 				mhioc_preemptandabort_t preempt_abort;
19968 				if (ddi_copyin((void *)arg, &preempt_abort,
19969 				    sizeof (mhioc_preemptandabort_t),
19970 				    flag) != 0) {
19971 					err = EFAULT;
19972 				} else {
19973 					err =
19974 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
19975 					    un, SD_SCSI3_PREEMPTANDABORT,
19976 					    (uchar_t *)&preempt_abort);
19977 				}
19978 			}
19979 		}
19980 		break;
19981 
19982 	case MHIOCGRP_REGISTERANDIGNOREKEY:
19983 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
19984 		if ((err = drv_priv(cred_p)) != EPERM) {
19985 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19986 				err = ENOTSUP;
19987 			} else if (arg != NULL) {
19988 				mhioc_registerandignorekey_t r_and_i;
19989 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
19990 				    sizeof (mhioc_registerandignorekey_t),
19991 				    flag) != 0) {
19992 					err = EFAULT;
19993 				} else {
19994 					err =
19995 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
19996 					    un, SD_SCSI3_REGISTERANDIGNOREKEY,
19997 					    (uchar_t *)&r_and_i);
19998 				}
19999 			}
20000 		}
20001 		break;
20002 
20003 	case USCSICMD:
20004 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
20005 		cr = ddi_get_cred();
20006 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
20007 			err = EPERM;
20008 		} else {
20009 			enum uio_seg	uioseg;
20010 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
20011 			    UIO_USERSPACE;
20012 			if (un->un_f_format_in_progress == TRUE) {
20013 				err = EAGAIN;
20014 				break;
20015 			}
20016 			err = sd_send_scsi_cmd(dev, (struct uscsi_cmd *)arg,
20017 			    flag, uioseg, SD_PATH_STANDARD);
20018 		}
20019 		break;
20020 
20021 	case CDROMPAUSE:
20022 	case CDROMRESUME:
20023 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
20024 		if (!ISCD(un)) {
20025 			err = ENOTTY;
20026 		} else {
20027 			err = sr_pause_resume(dev, cmd);
20028 		}
20029 		break;
20030 
20031 	case CDROMPLAYMSF:
20032 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
20033 		if (!ISCD(un)) {
20034 			err = ENOTTY;
20035 		} else {
20036 			err = sr_play_msf(dev, (caddr_t)arg, flag);
20037 		}
20038 		break;
20039 
20040 	case CDROMPLAYTRKIND:
20041 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
20042 #if defined(__i386) || defined(__amd64)
20043 		/*
20044 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
20045 		 */
20046 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
20047 #else
20048 		if (!ISCD(un)) {
20049 #endif
20050 			err = ENOTTY;
20051 		} else {
20052 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
20053 		}
20054 		break;
20055 
20056 	case CDROMREADTOCHDR:
20057 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
20058 		if (!ISCD(un)) {
20059 			err = ENOTTY;
20060 		} else {
20061 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
20062 		}
20063 		break;
20064 
20065 	case CDROMREADTOCENTRY:
20066 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
20067 		if (!ISCD(un)) {
20068 			err = ENOTTY;
20069 		} else {
20070 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
20071 		}
20072 		break;
20073 
20074 	case CDROMSTOP:
20075 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
20076 		if (!ISCD(un)) {
20077 			err = ENOTTY;
20078 		} else {
20079 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_STOP,
20080 			    SD_PATH_STANDARD);
20081 		}
20082 		break;
20083 
20084 	case CDROMSTART:
20085 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
20086 		if (!ISCD(un)) {
20087 			err = ENOTTY;
20088 		} else {
20089 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
20090 			    SD_PATH_STANDARD);
20091 		}
20092 		break;
20093 
20094 	case CDROMCLOSETRAY:
20095 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
20096 		if (!ISCD(un)) {
20097 			err = ENOTTY;
20098 		} else {
20099 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_CLOSE,
20100 			    SD_PATH_STANDARD);
20101 		}
20102 		break;
20103 
20104 	case FDEJECT:	/* for eject command */
20105 	case DKIOCEJECT:
20106 	case CDROMEJECT:
20107 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
20108 		if (!un->un_f_eject_media_supported) {
20109 			err = ENOTTY;
20110 		} else {
20111 			err = sr_eject(dev);
20112 		}
20113 		break;
20114 
20115 	case CDROMVOLCTRL:
20116 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
20117 		if (!ISCD(un)) {
20118 			err = ENOTTY;
20119 		} else {
20120 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
20121 		}
20122 		break;
20123 
20124 	case CDROMSUBCHNL:
20125 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
20126 		if (!ISCD(un)) {
20127 			err = ENOTTY;
20128 		} else {
20129 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
20130 		}
20131 		break;
20132 
20133 	case CDROMREADMODE2:
20134 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
20135 		if (!ISCD(un)) {
20136 			err = ENOTTY;
20137 		} else if (un->un_f_cfg_is_atapi == TRUE) {
20138 			/*
20139 			 * If the drive supports READ CD, use that instead of
20140 			 * switching the LBA size via a MODE SELECT
20141 			 * Block Descriptor
20142 			 */
20143 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
20144 		} else {
20145 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
20146 		}
20147 		break;
20148 
20149 	case CDROMREADMODE1:
20150 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
20151 		if (!ISCD(un)) {
20152 			err = ENOTTY;
20153 		} else {
20154 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
20155 		}
20156 		break;
20157 
20158 	case CDROMREADOFFSET:
20159 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
20160 		if (!ISCD(un)) {
20161 			err = ENOTTY;
20162 		} else {
20163 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
20164 			    flag);
20165 		}
20166 		break;
20167 
20168 	case CDROMSBLKMODE:
20169 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
20170 		/*
20171 		 * There is no means of changing block size in case of atapi
20172 		 * drives, thus return ENOTTY if drive type is atapi
20173 		 */
20174 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
20175 			err = ENOTTY;
20176 		} else if (un->un_f_mmc_cap == TRUE) {
20177 
20178 			/*
20179 			 * MMC Devices do not support changing the
20180 			 * logical block size
20181 			 *
20182 			 * Note: EINVAL is being returned instead of ENOTTY to
20183 			 * maintain consistancy with the original mmc
20184 			 * driver update.
20185 			 */
20186 			err = EINVAL;
20187 		} else {
20188 			mutex_enter(SD_MUTEX(un));
20189 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
20190 			    (un->un_ncmds_in_transport > 0)) {
20191 				mutex_exit(SD_MUTEX(un));
20192 				err = EINVAL;
20193 			} else {
20194 				mutex_exit(SD_MUTEX(un));
20195 				err = sr_change_blkmode(dev, cmd, arg, flag);
20196 			}
20197 		}
20198 		break;
20199 
20200 	case CDROMGBLKMODE:
20201 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
20202 		if (!ISCD(un)) {
20203 			err = ENOTTY;
20204 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
20205 		    (un->un_f_blockcount_is_valid != FALSE)) {
20206 			/*
20207 			 * Drive is an ATAPI drive so return target block
20208 			 * size for ATAPI drives since we cannot change the
20209 			 * blocksize on ATAPI drives. Used primarily to detect
20210 			 * if an ATAPI cdrom is present.
20211 			 */
20212 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
20213 			    sizeof (int), flag) != 0) {
20214 				err = EFAULT;
20215 			} else {
20216 				err = 0;
20217 			}
20218 
20219 		} else {
20220 			/*
20221 			 * Drive supports changing block sizes via a Mode
20222 			 * Select.
20223 			 */
20224 			err = sr_change_blkmode(dev, cmd, arg, flag);
20225 		}
20226 		break;
20227 
20228 	case CDROMGDRVSPEED:
20229 	case CDROMSDRVSPEED:
20230 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
20231 		if (!ISCD(un)) {
20232 			err = ENOTTY;
20233 		} else if (un->un_f_mmc_cap == TRUE) {
20234 			/*
20235 			 * Note: In the future the driver implementation
20236 			 * for getting and
20237 			 * setting cd speed should entail:
20238 			 * 1) If non-mmc try the Toshiba mode page
20239 			 *    (sr_change_speed)
20240 			 * 2) If mmc but no support for Real Time Streaming try
20241 			 *    the SET CD SPEED (0xBB) command
20242 			 *   (sr_atapi_change_speed)
20243 			 * 3) If mmc and support for Real Time Streaming
20244 			 *    try the GET PERFORMANCE and SET STREAMING
20245 			 *    commands (not yet implemented, 4380808)
20246 			 */
20247 			/*
20248 			 * As per recent MMC spec, CD-ROM speed is variable
20249 			 * and changes with LBA. Since there is no such
20250 			 * things as drive speed now, fail this ioctl.
20251 			 *
20252 			 * Note: EINVAL is returned for consistancy of original
20253 			 * implementation which included support for getting
20254 			 * the drive speed of mmc devices but not setting
20255 			 * the drive speed. Thus EINVAL would be returned
20256 			 * if a set request was made for an mmc device.
20257 			 * We no longer support get or set speed for
20258 			 * mmc but need to remain consistent with regard
20259 			 * to the error code returned.
20260 			 */
20261 			err = EINVAL;
20262 		} else if (un->un_f_cfg_is_atapi == TRUE) {
20263 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
20264 		} else {
20265 			err = sr_change_speed(dev, cmd, arg, flag);
20266 		}
20267 		break;
20268 
20269 	case CDROMCDDA:
20270 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
20271 		if (!ISCD(un)) {
20272 			err = ENOTTY;
20273 		} else {
20274 			err = sr_read_cdda(dev, (void *)arg, flag);
20275 		}
20276 		break;
20277 
20278 	case CDROMCDXA:
20279 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
20280 		if (!ISCD(un)) {
20281 			err = ENOTTY;
20282 		} else {
20283 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
20284 		}
20285 		break;
20286 
20287 	case CDROMSUBCODE:
20288 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
20289 		if (!ISCD(un)) {
20290 			err = ENOTTY;
20291 		} else {
20292 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
20293 		}
20294 		break;
20295 
20296 
20297 #ifdef SDDEBUG
20298 /* RESET/ABORTS testing ioctls */
20299 	case DKIOCRESET: {
20300 		int	reset_level;
20301 
20302 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
20303 			err = EFAULT;
20304 		} else {
20305 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
20306 			    "reset_level = 0x%lx\n", reset_level);
20307 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
20308 				err = 0;
20309 			} else {
20310 				err = EIO;
20311 			}
20312 		}
20313 		break;
20314 	}
20315 
20316 	case DKIOCABORT:
20317 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
20318 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
20319 			err = 0;
20320 		} else {
20321 			err = EIO;
20322 		}
20323 		break;
20324 #endif
20325 
20326 #ifdef SD_FAULT_INJECTION
20327 /* SDIOC FaultInjection testing ioctls */
20328 	case SDIOCSTART:
20329 	case SDIOCSTOP:
20330 	case SDIOCINSERTPKT:
20331 	case SDIOCINSERTXB:
20332 	case SDIOCINSERTUN:
20333 	case SDIOCINSERTARQ:
20334 	case SDIOCPUSH:
20335 	case SDIOCRETRIEVE:
20336 	case SDIOCRUN:
20337 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
20338 		    "SDIOC detected cmd:0x%X:\n", cmd);
20339 		/* call error generator */
20340 		sd_faultinjection_ioctl(cmd, arg, un);
20341 		err = 0;
20342 		break;
20343 
20344 #endif /* SD_FAULT_INJECTION */
20345 
20346 	case DKIOCFLUSHWRITECACHE:
20347 		{
20348 			struct dk_callback *dkc = (struct dk_callback *)arg;
20349 
20350 			mutex_enter(SD_MUTEX(un));
20351 			if (!un->un_f_sync_cache_supported ||
20352 			    !un->un_f_write_cache_enabled) {
20353 				err = un->un_f_sync_cache_supported ?
20354 				    0 : ENOTSUP;
20355 				mutex_exit(SD_MUTEX(un));
20356 				if ((flag & FKIOCTL) && dkc != NULL &&
20357 				    dkc->dkc_callback != NULL) {
20358 					(*dkc->dkc_callback)(dkc->dkc_cookie,
20359 					    err);
20360 					/*
20361 					 * Did callback and reported error.
20362 					 * Since we did a callback, ioctl
20363 					 * should return 0.
20364 					 */
20365 					err = 0;
20366 				}
20367 				break;
20368 			}
20369 			mutex_exit(SD_MUTEX(un));
20370 
20371 			if ((flag & FKIOCTL) && dkc != NULL &&
20372 			    dkc->dkc_callback != NULL) {
20373 				/* async SYNC CACHE request */
20374 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
20375 			} else {
20376 				/* synchronous SYNC CACHE request */
20377 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
20378 			}
20379 		}
20380 		break;
20381 
20382 	case DKIOCGETWCE: {
20383 
20384 		int wce;
20385 
20386 		if ((err = sd_get_write_cache_enabled(un, &wce)) != 0) {
20387 			break;
20388 		}
20389 
20390 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
20391 			err = EFAULT;
20392 		}
20393 		break;
20394 	}
20395 
20396 	case DKIOCSETWCE: {
20397 
20398 		int wce, sync_supported;
20399 
20400 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
20401 			err = EFAULT;
20402 			break;
20403 		}
20404 
20405 		/*
20406 		 * Synchronize multiple threads trying to enable
20407 		 * or disable the cache via the un_f_wcc_cv
20408 		 * condition variable.
20409 		 */
20410 		mutex_enter(SD_MUTEX(un));
20411 
20412 		/*
20413 		 * Don't allow the cache to be enabled if the
20414 		 * config file has it disabled.
20415 		 */
20416 		if (un->un_f_opt_disable_cache && wce) {
20417 			mutex_exit(SD_MUTEX(un));
20418 			err = EINVAL;
20419 			break;
20420 		}
20421 
20422 		/*
20423 		 * Wait for write cache change in progress
20424 		 * bit to be clear before proceeding.
20425 		 */
20426 		while (un->un_f_wcc_inprog)
20427 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
20428 
20429 		un->un_f_wcc_inprog = 1;
20430 
20431 		if (un->un_f_write_cache_enabled && wce == 0) {
20432 			/*
20433 			 * Disable the write cache.  Don't clear
20434 			 * un_f_write_cache_enabled until after
20435 			 * the mode select and flush are complete.
20436 			 */
20437 			sync_supported = un->un_f_sync_cache_supported;
20438 
20439 			/*
20440 			 * If cache flush is suppressed, we assume that the
20441 			 * controller firmware will take care of managing the
20442 			 * write cache for us: no need to explicitly
20443 			 * disable it.
20444 			 */
20445 			if (!un->un_f_suppress_cache_flush) {
20446 				mutex_exit(SD_MUTEX(un));
20447 				if ((err = sd_cache_control(un,
20448 				    SD_CACHE_NOCHANGE,
20449 				    SD_CACHE_DISABLE)) == 0 &&
20450 				    sync_supported) {
20451 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
20452 					    NULL);
20453 				}
20454 			} else {
20455 				mutex_exit(SD_MUTEX(un));
20456 			}
20457 
20458 			mutex_enter(SD_MUTEX(un));
20459 			if (err == 0) {
20460 				un->un_f_write_cache_enabled = 0;
20461 			}
20462 
20463 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
20464 			/*
20465 			 * Set un_f_write_cache_enabled first, so there is
20466 			 * no window where the cache is enabled, but the
20467 			 * bit says it isn't.
20468 			 */
20469 			un->un_f_write_cache_enabled = 1;
20470 
20471 			/*
20472 			 * If cache flush is suppressed, we assume that the
20473 			 * controller firmware will take care of managing the
20474 			 * write cache for us: no need to explicitly
20475 			 * enable it.
20476 			 */
20477 			if (!un->un_f_suppress_cache_flush) {
20478 				mutex_exit(SD_MUTEX(un));
20479 				err = sd_cache_control(un, SD_CACHE_NOCHANGE,
20480 				    SD_CACHE_ENABLE);
20481 			} else {
20482 				mutex_exit(SD_MUTEX(un));
20483 			}
20484 
20485 			mutex_enter(SD_MUTEX(un));
20486 
20487 			if (err) {
20488 				un->un_f_write_cache_enabled = 0;
20489 			}
20490 		}
20491 
20492 		un->un_f_wcc_inprog = 0;
20493 		cv_broadcast(&un->un_wcc_cv);
20494 		mutex_exit(SD_MUTEX(un));
20495 		break;
20496 	}
20497 
20498 	default:
20499 		err = ENOTTY;
20500 		break;
20501 	}
20502 	mutex_enter(SD_MUTEX(un));
20503 	un->un_ncmds_in_driver--;
20504 	ASSERT(un->un_ncmds_in_driver >= 0);
20505 	mutex_exit(SD_MUTEX(un));
20506 
20507 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
20508 	return (err);
20509 }
20510 
20511 
20512 /*
20513  *    Function: sd_dkio_ctrl_info
20514  *
20515  * Description: This routine is the driver entry point for handling controller
20516  *		information ioctl requests (DKIOCINFO).
20517  *
20518  *   Arguments: dev  - the device number
20519  *		arg  - pointer to user provided dk_cinfo structure
20520  *		       specifying the controller type and attributes.
20521  *		flag - this argument is a pass through to ddi_copyxxx()
20522  *		       directly from the mode argument of ioctl().
20523  *
20524  * Return Code: 0
20525  *		EFAULT
20526  *		ENXIO
20527  */
20528 
20529 static int
20530 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
20531 {
20532 	struct sd_lun	*un = NULL;
20533 	struct dk_cinfo	*info;
20534 	dev_info_t	*pdip;
20535 	int		lun, tgt;
20536 
20537 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20538 		return (ENXIO);
20539 	}
20540 
20541 	info = (struct dk_cinfo *)
20542 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
20543 
20544 	switch (un->un_ctype) {
20545 	case CTYPE_CDROM:
20546 		info->dki_ctype = DKC_CDROM;
20547 		break;
20548 	default:
20549 		info->dki_ctype = DKC_SCSI_CCS;
20550 		break;
20551 	}
20552 	pdip = ddi_get_parent(SD_DEVINFO(un));
20553 	info->dki_cnum = ddi_get_instance(pdip);
20554 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
20555 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
20556 	} else {
20557 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
20558 		    DK_DEVLEN - 1);
20559 	}
20560 
20561 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20562 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
20563 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20564 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
20565 
20566 	/* Unit Information */
20567 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
20568 	info->dki_slave = ((tgt << 3) | lun);
20569 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
20570 	    DK_DEVLEN - 1);
20571 	info->dki_flags = DKI_FMTVOL;
20572 	info->dki_partition = SDPART(dev);
20573 
20574 	/* Max Transfer size of this device in blocks */
20575 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
20576 	info->dki_addr = 0;
20577 	info->dki_space = 0;
20578 	info->dki_prio = 0;
20579 	info->dki_vec = 0;
20580 
20581 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
20582 		kmem_free(info, sizeof (struct dk_cinfo));
20583 		return (EFAULT);
20584 	} else {
20585 		kmem_free(info, sizeof (struct dk_cinfo));
20586 		return (0);
20587 	}
20588 }
20589 
20590 
20591 /*
20592  *    Function: sd_get_media_info
20593  *
20594  * Description: This routine is the driver entry point for handling ioctl
20595  *		requests for the media type or command set profile used by the
20596  *		drive to operate on the media (DKIOCGMEDIAINFO).
20597  *
20598  *   Arguments: dev	- the device number
20599  *		arg	- pointer to user provided dk_minfo structure
20600  *			  specifying the media type, logical block size and
20601  *			  drive capacity.
20602  *		flag	- this argument is a pass through to ddi_copyxxx()
20603  *			  directly from the mode argument of ioctl().
20604  *
20605  * Return Code: 0
20606  *		EACCESS
20607  *		EFAULT
20608  *		ENXIO
20609  *		EIO
20610  */
20611 
20612 static int
20613 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
20614 {
20615 	struct sd_lun		*un = NULL;
20616 	struct uscsi_cmd	com;
20617 	struct scsi_inquiry	*sinq;
20618 	struct dk_minfo		media_info;
20619 	u_longlong_t		media_capacity;
20620 	uint64_t		capacity;
20621 	uint_t			lbasize;
20622 	uchar_t			*out_data;
20623 	uchar_t			*rqbuf;
20624 	int			rval = 0;
20625 	int			rtn;
20626 
20627 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
20628 	    (un->un_state == SD_STATE_OFFLINE)) {
20629 		return (ENXIO);
20630 	}
20631 
20632 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info: entry\n");
20633 
20634 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
20635 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
20636 
20637 	/* Issue a TUR to determine if the drive is ready with media present */
20638 	rval = sd_send_scsi_TEST_UNIT_READY(un, SD_CHECK_FOR_MEDIA);
20639 	if (rval == ENXIO) {
20640 		goto done;
20641 	}
20642 
20643 	/* Now get configuration data */
20644 	if (ISCD(un)) {
20645 		media_info.dki_media_type = DK_CDROM;
20646 
20647 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
20648 		if (un->un_f_mmc_cap == TRUE) {
20649 			rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf,
20650 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
20651 			    SD_PATH_STANDARD);
20652 
20653 			if (rtn) {
20654 				/*
20655 				 * Failed for other than an illegal request
20656 				 * or command not supported
20657 				 */
20658 				if ((com.uscsi_status == STATUS_CHECK) &&
20659 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
20660 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
20661 					    (rqbuf[12] != 0x20)) {
20662 						rval = EIO;
20663 						goto done;
20664 					}
20665 				}
20666 			} else {
20667 				/*
20668 				 * The GET CONFIGURATION command succeeded
20669 				 * so set the media type according to the
20670 				 * returned data
20671 				 */
20672 				media_info.dki_media_type = out_data[6];
20673 				media_info.dki_media_type <<= 8;
20674 				media_info.dki_media_type |= out_data[7];
20675 			}
20676 		}
20677 	} else {
20678 		/*
20679 		 * The profile list is not available, so we attempt to identify
20680 		 * the media type based on the inquiry data
20681 		 */
20682 		sinq = un->un_sd->sd_inq;
20683 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
20684 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
20685 			/* This is a direct access device  or optical disk */
20686 			media_info.dki_media_type = DK_FIXED_DISK;
20687 
20688 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
20689 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
20690 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
20691 					media_info.dki_media_type = DK_ZIP;
20692 				} else if (
20693 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
20694 					media_info.dki_media_type = DK_JAZ;
20695 				}
20696 			}
20697 		} else {
20698 			/*
20699 			 * Not a CD, direct access or optical disk so return
20700 			 * unknown media
20701 			 */
20702 			media_info.dki_media_type = DK_UNKNOWN;
20703 		}
20704 	}
20705 
20706 	/* Now read the capacity so we can provide the lbasize and capacity */
20707 	switch (sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
20708 	    SD_PATH_DIRECT)) {
20709 	case 0:
20710 		break;
20711 	case EACCES:
20712 		rval = EACCES;
20713 		goto done;
20714 	default:
20715 		rval = EIO;
20716 		goto done;
20717 	}
20718 
20719 	media_info.dki_lbsize = lbasize;
20720 	media_capacity = capacity;
20721 
20722 	/*
20723 	 * sd_send_scsi_READ_CAPACITY() reports capacity in
20724 	 * un->un_sys_blocksize chunks. So we need to convert it into
20725 	 * cap.lbasize chunks.
20726 	 */
20727 	media_capacity *= un->un_sys_blocksize;
20728 	media_capacity /= lbasize;
20729 	media_info.dki_capacity = media_capacity;
20730 
20731 	if (ddi_copyout(&media_info, arg, sizeof (struct dk_minfo), flag)) {
20732 		rval = EFAULT;
20733 		/* Put goto. Anybody might add some code below in future */
20734 		goto done;
20735 	}
20736 done:
20737 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
20738 	kmem_free(rqbuf, SENSE_LENGTH);
20739 	return (rval);
20740 }
20741 
20742 
20743 /*
20744  *    Function: sd_check_media
20745  *
20746  * Description: This utility routine implements the functionality for the
20747  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
20748  *		driver state changes from that specified by the user
20749  *		(inserted or ejected). For example, if the user specifies
20750  *		DKIO_EJECTED and the current media state is inserted this
20751  *		routine will immediately return DKIO_INSERTED. However, if the
20752  *		current media state is not inserted the user thread will be
20753  *		blocked until the drive state changes. If DKIO_NONE is specified
20754  *		the user thread will block until a drive state change occurs.
20755  *
20756  *   Arguments: dev  - the device number
20757  *		state  - user pointer to a dkio_state, updated with the current
20758  *			drive state at return.
20759  *
20760  * Return Code: ENXIO
20761  *		EIO
20762  *		EAGAIN
20763  *		EINTR
20764  */
20765 
20766 static int
20767 sd_check_media(dev_t dev, enum dkio_state state)
20768 {
20769 	struct sd_lun		*un = NULL;
20770 	enum dkio_state		prev_state;
20771 	opaque_t		token = NULL;
20772 	int			rval = 0;
20773 
20774 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20775 		return (ENXIO);
20776 	}
20777 
20778 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
20779 
20780 	mutex_enter(SD_MUTEX(un));
20781 
20782 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
20783 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
20784 
20785 	prev_state = un->un_mediastate;
20786 
20787 	/* is there anything to do? */
20788 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
20789 		/*
20790 		 * submit the request to the scsi_watch service;
20791 		 * scsi_media_watch_cb() does the real work
20792 		 */
20793 		mutex_exit(SD_MUTEX(un));
20794 
20795 		/*
20796 		 * This change handles the case where a scsi watch request is
20797 		 * added to a device that is powered down. To accomplish this
20798 		 * we power up the device before adding the scsi watch request,
20799 		 * since the scsi watch sends a TUR directly to the device
20800 		 * which the device cannot handle if it is powered down.
20801 		 */
20802 		if (sd_pm_entry(un) != DDI_SUCCESS) {
20803 			mutex_enter(SD_MUTEX(un));
20804 			goto done;
20805 		}
20806 
20807 		token = scsi_watch_request_submit(SD_SCSI_DEVP(un),
20808 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
20809 		    (caddr_t)dev);
20810 
20811 		sd_pm_exit(un);
20812 
20813 		mutex_enter(SD_MUTEX(un));
20814 		if (token == NULL) {
20815 			rval = EAGAIN;
20816 			goto done;
20817 		}
20818 
20819 		/*
20820 		 * This is a special case IOCTL that doesn't return
20821 		 * until the media state changes. Routine sdpower
20822 		 * knows about and handles this so don't count it
20823 		 * as an active cmd in the driver, which would
20824 		 * keep the device busy to the pm framework.
20825 		 * If the count isn't decremented the device can't
20826 		 * be powered down.
20827 		 */
20828 		un->un_ncmds_in_driver--;
20829 		ASSERT(un->un_ncmds_in_driver >= 0);
20830 
20831 		/*
20832 		 * if a prior request had been made, this will be the same
20833 		 * token, as scsi_watch was designed that way.
20834 		 */
20835 		un->un_swr_token = token;
20836 		un->un_specified_mediastate = state;
20837 
20838 		/*
20839 		 * now wait for media change
20840 		 * we will not be signalled unless mediastate == state but it is
20841 		 * still better to test for this condition, since there is a
20842 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
20843 		 */
20844 		SD_TRACE(SD_LOG_COMMON, un,
20845 		    "sd_check_media: waiting for media state change\n");
20846 		while (un->un_mediastate == state) {
20847 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
20848 				SD_TRACE(SD_LOG_COMMON, un,
20849 				    "sd_check_media: waiting for media state "
20850 				    "was interrupted\n");
20851 				un->un_ncmds_in_driver++;
20852 				rval = EINTR;
20853 				goto done;
20854 			}
20855 			SD_TRACE(SD_LOG_COMMON, un,
20856 			    "sd_check_media: received signal, state=%x\n",
20857 			    un->un_mediastate);
20858 		}
20859 		/*
20860 		 * Inc the counter to indicate the device once again
20861 		 * has an active outstanding cmd.
20862 		 */
20863 		un->un_ncmds_in_driver++;
20864 	}
20865 
20866 	/* invalidate geometry */
20867 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
20868 		sr_ejected(un);
20869 	}
20870 
20871 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
20872 		uint64_t	capacity;
20873 		uint_t		lbasize;
20874 
20875 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
20876 		mutex_exit(SD_MUTEX(un));
20877 		/*
20878 		 * Since the following routines use SD_PATH_DIRECT, we must
20879 		 * call PM directly before the upcoming disk accesses. This
20880 		 * may cause the disk to be power/spin up.
20881 		 */
20882 
20883 		if (sd_pm_entry(un) == DDI_SUCCESS) {
20884 			rval = sd_send_scsi_READ_CAPACITY(un,
20885 			    &capacity,
20886 			    &lbasize, SD_PATH_DIRECT);
20887 			if (rval != 0) {
20888 				sd_pm_exit(un);
20889 				mutex_enter(SD_MUTEX(un));
20890 				goto done;
20891 			}
20892 		} else {
20893 			rval = EIO;
20894 			mutex_enter(SD_MUTEX(un));
20895 			goto done;
20896 		}
20897 		mutex_enter(SD_MUTEX(un));
20898 
20899 		sd_update_block_info(un, lbasize, capacity);
20900 
20901 		/*
20902 		 *  Check if the media in the device is writable or not
20903 		 */
20904 		if (ISCD(un))
20905 			sd_check_for_writable_cd(un, SD_PATH_DIRECT);
20906 
20907 		mutex_exit(SD_MUTEX(un));
20908 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
20909 		if ((cmlb_validate(un->un_cmlbhandle, 0,
20910 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
20911 			sd_set_pstats(un);
20912 			SD_TRACE(SD_LOG_IO_PARTITION, un,
20913 			    "sd_check_media: un:0x%p pstats created and "
20914 			    "set\n", un);
20915 		}
20916 
20917 		rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
20918 		    SD_PATH_DIRECT);
20919 		sd_pm_exit(un);
20920 
20921 		mutex_enter(SD_MUTEX(un));
20922 	}
20923 done:
20924 	un->un_f_watcht_stopped = FALSE;
20925 	if (un->un_swr_token) {
20926 		/*
20927 		 * Use of this local token and the mutex ensures that we avoid
20928 		 * some race conditions associated with terminating the
20929 		 * scsi watch.
20930 		 */
20931 		token = un->un_swr_token;
20932 		un->un_swr_token = (opaque_t)NULL;
20933 		mutex_exit(SD_MUTEX(un));
20934 		(void) scsi_watch_request_terminate(token,
20935 		    SCSI_WATCH_TERMINATE_WAIT);
20936 		mutex_enter(SD_MUTEX(un));
20937 	}
20938 
20939 	/*
20940 	 * Update the capacity kstat value, if no media previously
20941 	 * (capacity kstat is 0) and a media has been inserted
20942 	 * (un_f_blockcount_is_valid == TRUE)
20943 	 */
20944 	if (un->un_errstats) {
20945 		struct sd_errstats	*stp = NULL;
20946 
20947 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
20948 		if ((stp->sd_capacity.value.ui64 == 0) &&
20949 		    (un->un_f_blockcount_is_valid == TRUE)) {
20950 			stp->sd_capacity.value.ui64 =
20951 			    (uint64_t)((uint64_t)un->un_blockcount *
20952 			    un->un_sys_blocksize);
20953 		}
20954 	}
20955 	mutex_exit(SD_MUTEX(un));
20956 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
20957 	return (rval);
20958 }
20959 
20960 
20961 /*
20962  *    Function: sd_delayed_cv_broadcast
20963  *
20964  * Description: Delayed cv_broadcast to allow for target to recover from media
20965  *		insertion.
20966  *
20967  *   Arguments: arg - driver soft state (unit) structure
20968  */
20969 
20970 static void
20971 sd_delayed_cv_broadcast(void *arg)
20972 {
20973 	struct sd_lun *un = arg;
20974 
20975 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
20976 
20977 	mutex_enter(SD_MUTEX(un));
20978 	un->un_dcvb_timeid = NULL;
20979 	cv_broadcast(&un->un_state_cv);
20980 	mutex_exit(SD_MUTEX(un));
20981 }
20982 
20983 
20984 /*
20985  *    Function: sd_media_watch_cb
20986  *
20987  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
20988  *		routine processes the TUR sense data and updates the driver
20989  *		state if a transition has occurred. The user thread
20990  *		(sd_check_media) is then signalled.
20991  *
20992  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
20993  *			among multiple watches that share this callback function
20994  *		resultp - scsi watch facility result packet containing scsi
20995  *			  packet, status byte and sense data
20996  *
20997  * Return Code: 0 for success, -1 for failure
20998  */
20999 
21000 static int
21001 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
21002 {
21003 	struct sd_lun			*un;
21004 	struct scsi_status		*statusp = resultp->statusp;
21005 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
21006 	enum dkio_state			state = DKIO_NONE;
21007 	dev_t				dev = (dev_t)arg;
21008 	uchar_t				actual_sense_length;
21009 	uint8_t				skey, asc, ascq;
21010 
21011 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21012 		return (-1);
21013 	}
21014 	actual_sense_length = resultp->actual_sense_length;
21015 
21016 	mutex_enter(SD_MUTEX(un));
21017 	SD_TRACE(SD_LOG_COMMON, un,
21018 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
21019 	    *((char *)statusp), (void *)sensep, actual_sense_length);
21020 
21021 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
21022 		un->un_mediastate = DKIO_DEV_GONE;
21023 		cv_broadcast(&un->un_state_cv);
21024 		mutex_exit(SD_MUTEX(un));
21025 
21026 		return (0);
21027 	}
21028 
21029 	/*
21030 	 * If there was a check condition then sensep points to valid sense data
21031 	 * If status was not a check condition but a reservation or busy status
21032 	 * then the new state is DKIO_NONE
21033 	 */
21034 	if (sensep != NULL) {
21035 		skey = scsi_sense_key(sensep);
21036 		asc = scsi_sense_asc(sensep);
21037 		ascq = scsi_sense_ascq(sensep);
21038 
21039 		SD_INFO(SD_LOG_COMMON, un,
21040 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
21041 		    skey, asc, ascq);
21042 		/* This routine only uses up to 13 bytes of sense data. */
21043 		if (actual_sense_length >= 13) {
21044 			if (skey == KEY_UNIT_ATTENTION) {
21045 				if (asc == 0x28) {
21046 					state = DKIO_INSERTED;
21047 				}
21048 			} else if (skey == KEY_NOT_READY) {
21049 				/*
21050 				 * if 02/04/02  means that the host
21051 				 * should send start command. Explicitly
21052 				 * leave the media state as is
21053 				 * (inserted) as the media is inserted
21054 				 * and host has stopped device for PM
21055 				 * reasons. Upon next true read/write
21056 				 * to this media will bring the
21057 				 * device to the right state good for
21058 				 * media access.
21059 				 */
21060 				if (asc == 0x3a) {
21061 					state = DKIO_EJECTED;
21062 				} else {
21063 					/*
21064 					 * If the drive is busy with an
21065 					 * operation or long write, keep the
21066 					 * media in an inserted state.
21067 					 */
21068 
21069 					if ((asc == 0x04) &&
21070 					    ((ascq == 0x02) ||
21071 					    (ascq == 0x07) ||
21072 					    (ascq == 0x08))) {
21073 						state = DKIO_INSERTED;
21074 					}
21075 				}
21076 			} else if (skey == KEY_NO_SENSE) {
21077 				if ((asc == 0x00) && (ascq == 0x00)) {
21078 					/*
21079 					 * Sense Data 00/00/00 does not provide
21080 					 * any information about the state of
21081 					 * the media. Ignore it.
21082 					 */
21083 					mutex_exit(SD_MUTEX(un));
21084 					return (0);
21085 				}
21086 			}
21087 		}
21088 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
21089 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
21090 		state = DKIO_INSERTED;
21091 	}
21092 
21093 	SD_TRACE(SD_LOG_COMMON, un,
21094 	    "sd_media_watch_cb: state=%x, specified=%x\n",
21095 	    state, un->un_specified_mediastate);
21096 
21097 	/*
21098 	 * now signal the waiting thread if this is *not* the specified state;
21099 	 * delay the signal if the state is DKIO_INSERTED to allow the target
21100 	 * to recover
21101 	 */
21102 	if (state != un->un_specified_mediastate) {
21103 		un->un_mediastate = state;
21104 		if (state == DKIO_INSERTED) {
21105 			/*
21106 			 * delay the signal to give the drive a chance
21107 			 * to do what it apparently needs to do
21108 			 */
21109 			SD_TRACE(SD_LOG_COMMON, un,
21110 			    "sd_media_watch_cb: delayed cv_broadcast\n");
21111 			if (un->un_dcvb_timeid == NULL) {
21112 				un->un_dcvb_timeid =
21113 				    timeout(sd_delayed_cv_broadcast, un,
21114 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
21115 			}
21116 		} else {
21117 			SD_TRACE(SD_LOG_COMMON, un,
21118 			    "sd_media_watch_cb: immediate cv_broadcast\n");
21119 			cv_broadcast(&un->un_state_cv);
21120 		}
21121 	}
21122 	mutex_exit(SD_MUTEX(un));
21123 	return (0);
21124 }
21125 
21126 
21127 /*
21128  *    Function: sd_dkio_get_temp
21129  *
21130  * Description: This routine is the driver entry point for handling ioctl
21131  *		requests to get the disk temperature.
21132  *
21133  *   Arguments: dev  - the device number
21134  *		arg  - pointer to user provided dk_temperature structure.
21135  *		flag - this argument is a pass through to ddi_copyxxx()
21136  *		       directly from the mode argument of ioctl().
21137  *
21138  * Return Code: 0
21139  *		EFAULT
21140  *		ENXIO
21141  *		EAGAIN
21142  */
21143 
21144 static int
21145 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
21146 {
21147 	struct sd_lun		*un = NULL;
21148 	struct dk_temperature	*dktemp = NULL;
21149 	uchar_t			*temperature_page;
21150 	int			rval = 0;
21151 	int			path_flag = SD_PATH_STANDARD;
21152 
21153 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21154 		return (ENXIO);
21155 	}
21156 
21157 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
21158 
21159 	/* copyin the disk temp argument to get the user flags */
21160 	if (ddi_copyin((void *)arg, dktemp,
21161 	    sizeof (struct dk_temperature), flag) != 0) {
21162 		rval = EFAULT;
21163 		goto done;
21164 	}
21165 
21166 	/* Initialize the temperature to invalid. */
21167 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
21168 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
21169 
21170 	/*
21171 	 * Note: Investigate removing the "bypass pm" semantic.
21172 	 * Can we just bypass PM always?
21173 	 */
21174 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
21175 		path_flag = SD_PATH_DIRECT;
21176 		ASSERT(!mutex_owned(&un->un_pm_mutex));
21177 		mutex_enter(&un->un_pm_mutex);
21178 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
21179 			/*
21180 			 * If DKT_BYPASS_PM is set, and the drive happens to be
21181 			 * in low power mode, we can not wake it up, Need to
21182 			 * return EAGAIN.
21183 			 */
21184 			mutex_exit(&un->un_pm_mutex);
21185 			rval = EAGAIN;
21186 			goto done;
21187 		} else {
21188 			/*
21189 			 * Indicate to PM the device is busy. This is required
21190 			 * to avoid a race - i.e. the ioctl is issuing a
21191 			 * command and the pm framework brings down the device
21192 			 * to low power mode (possible power cut-off on some
21193 			 * platforms).
21194 			 */
21195 			mutex_exit(&un->un_pm_mutex);
21196 			if (sd_pm_entry(un) != DDI_SUCCESS) {
21197 				rval = EAGAIN;
21198 				goto done;
21199 			}
21200 		}
21201 	}
21202 
21203 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
21204 
21205 	if ((rval = sd_send_scsi_LOG_SENSE(un, temperature_page,
21206 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag)) != 0) {
21207 		goto done2;
21208 	}
21209 
21210 	/*
21211 	 * For the current temperature verify that the parameter length is 0x02
21212 	 * and the parameter code is 0x00
21213 	 */
21214 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
21215 	    (temperature_page[5] == 0x00)) {
21216 		if (temperature_page[9] == 0xFF) {
21217 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
21218 		} else {
21219 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
21220 		}
21221 	}
21222 
21223 	/*
21224 	 * For the reference temperature verify that the parameter
21225 	 * length is 0x02 and the parameter code is 0x01
21226 	 */
21227 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
21228 	    (temperature_page[11] == 0x01)) {
21229 		if (temperature_page[15] == 0xFF) {
21230 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
21231 		} else {
21232 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
21233 		}
21234 	}
21235 
21236 	/* Do the copyout regardless of the temperature commands status. */
21237 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
21238 	    flag) != 0) {
21239 		rval = EFAULT;
21240 	}
21241 
21242 done2:
21243 	if (path_flag == SD_PATH_DIRECT) {
21244 		sd_pm_exit(un);
21245 	}
21246 
21247 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
21248 done:
21249 	if (dktemp != NULL) {
21250 		kmem_free(dktemp, sizeof (struct dk_temperature));
21251 	}
21252 
21253 	return (rval);
21254 }
21255 
21256 
21257 /*
21258  *    Function: sd_log_page_supported
21259  *
21260  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
21261  *		supported log pages.
21262  *
21263  *   Arguments: un -
21264  *		log_page -
21265  *
21266  * Return Code: -1 - on error (log sense is optional and may not be supported).
21267  *		0  - log page not found.
21268  *  		1  - log page found.
21269  */
21270 
21271 static int
21272 sd_log_page_supported(struct sd_lun *un, int log_page)
21273 {
21274 	uchar_t *log_page_data;
21275 	int	i;
21276 	int	match = 0;
21277 	int	log_size;
21278 
21279 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
21280 
21281 	if (sd_send_scsi_LOG_SENSE(un, log_page_data, 0xFF, 0, 0x01, 0,
21282 	    SD_PATH_DIRECT) != 0) {
21283 		SD_ERROR(SD_LOG_COMMON, un,
21284 		    "sd_log_page_supported: failed log page retrieval\n");
21285 		kmem_free(log_page_data, 0xFF);
21286 		return (-1);
21287 	}
21288 	log_size = log_page_data[3];
21289 
21290 	/*
21291 	 * The list of supported log pages start from the fourth byte. Check
21292 	 * until we run out of log pages or a match is found.
21293 	 */
21294 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
21295 		if (log_page_data[i] == log_page) {
21296 			match++;
21297 		}
21298 	}
21299 	kmem_free(log_page_data, 0xFF);
21300 	return (match);
21301 }
21302 
21303 
21304 /*
21305  *    Function: sd_mhdioc_failfast
21306  *
21307  * Description: This routine is the driver entry point for handling ioctl
21308  *		requests to enable/disable the multihost failfast option.
21309  *		(MHIOCENFAILFAST)
21310  *
21311  *   Arguments: dev	- the device number
21312  *		arg	- user specified probing interval.
21313  *		flag	- this argument is a pass through to ddi_copyxxx()
21314  *			  directly from the mode argument of ioctl().
21315  *
21316  * Return Code: 0
21317  *		EFAULT
21318  *		ENXIO
21319  */
21320 
21321 static int
21322 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
21323 {
21324 	struct sd_lun	*un = NULL;
21325 	int		mh_time;
21326 	int		rval = 0;
21327 
21328 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21329 		return (ENXIO);
21330 	}
21331 
21332 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
21333 		return (EFAULT);
21334 
21335 	if (mh_time) {
21336 		mutex_enter(SD_MUTEX(un));
21337 		un->un_resvd_status |= SD_FAILFAST;
21338 		mutex_exit(SD_MUTEX(un));
21339 		/*
21340 		 * If mh_time is INT_MAX, then this ioctl is being used for
21341 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
21342 		 */
21343 		if (mh_time != INT_MAX) {
21344 			rval = sd_check_mhd(dev, mh_time);
21345 		}
21346 	} else {
21347 		(void) sd_check_mhd(dev, 0);
21348 		mutex_enter(SD_MUTEX(un));
21349 		un->un_resvd_status &= ~SD_FAILFAST;
21350 		mutex_exit(SD_MUTEX(un));
21351 	}
21352 	return (rval);
21353 }
21354 
21355 
21356 /*
21357  *    Function: sd_mhdioc_takeown
21358  *
21359  * Description: This routine is the driver entry point for handling ioctl
21360  *		requests to forcefully acquire exclusive access rights to the
21361  *		multihost disk (MHIOCTKOWN).
21362  *
21363  *   Arguments: dev	- the device number
21364  *		arg	- user provided structure specifying the delay
21365  *			  parameters in milliseconds
21366  *		flag	- this argument is a pass through to ddi_copyxxx()
21367  *			  directly from the mode argument of ioctl().
21368  *
21369  * Return Code: 0
21370  *		EFAULT
21371  *		ENXIO
21372  */
21373 
21374 static int
21375 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
21376 {
21377 	struct sd_lun		*un = NULL;
21378 	struct mhioctkown	*tkown = NULL;
21379 	int			rval = 0;
21380 
21381 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21382 		return (ENXIO);
21383 	}
21384 
21385 	if (arg != NULL) {
21386 		tkown = (struct mhioctkown *)
21387 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
21388 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
21389 		if (rval != 0) {
21390 			rval = EFAULT;
21391 			goto error;
21392 		}
21393 	}
21394 
21395 	rval = sd_take_ownership(dev, tkown);
21396 	mutex_enter(SD_MUTEX(un));
21397 	if (rval == 0) {
21398 		un->un_resvd_status |= SD_RESERVE;
21399 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
21400 			sd_reinstate_resv_delay =
21401 			    tkown->reinstate_resv_delay * 1000;
21402 		} else {
21403 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
21404 		}
21405 		/*
21406 		 * Give the scsi_watch routine interval set by
21407 		 * the MHIOCENFAILFAST ioctl precedence here.
21408 		 */
21409 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
21410 			mutex_exit(SD_MUTEX(un));
21411 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
21412 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
21413 			    "sd_mhdioc_takeown : %d\n",
21414 			    sd_reinstate_resv_delay);
21415 		} else {
21416 			mutex_exit(SD_MUTEX(un));
21417 		}
21418 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
21419 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21420 	} else {
21421 		un->un_resvd_status &= ~SD_RESERVE;
21422 		mutex_exit(SD_MUTEX(un));
21423 	}
21424 
21425 error:
21426 	if (tkown != NULL) {
21427 		kmem_free(tkown, sizeof (struct mhioctkown));
21428 	}
21429 	return (rval);
21430 }
21431 
21432 
21433 /*
21434  *    Function: sd_mhdioc_release
21435  *
21436  * Description: This routine is the driver entry point for handling ioctl
21437  *		requests to release exclusive access rights to the multihost
21438  *		disk (MHIOCRELEASE).
21439  *
21440  *   Arguments: dev	- the device number
21441  *
21442  * Return Code: 0
21443  *		ENXIO
21444  */
21445 
21446 static int
21447 sd_mhdioc_release(dev_t dev)
21448 {
21449 	struct sd_lun		*un = NULL;
21450 	timeout_id_t		resvd_timeid_save;
21451 	int			resvd_status_save;
21452 	int			rval = 0;
21453 
21454 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21455 		return (ENXIO);
21456 	}
21457 
21458 	mutex_enter(SD_MUTEX(un));
21459 	resvd_status_save = un->un_resvd_status;
21460 	un->un_resvd_status &=
21461 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
21462 	if (un->un_resvd_timeid) {
21463 		resvd_timeid_save = un->un_resvd_timeid;
21464 		un->un_resvd_timeid = NULL;
21465 		mutex_exit(SD_MUTEX(un));
21466 		(void) untimeout(resvd_timeid_save);
21467 	} else {
21468 		mutex_exit(SD_MUTEX(un));
21469 	}
21470 
21471 	/*
21472 	 * destroy any pending timeout thread that may be attempting to
21473 	 * reinstate reservation on this device.
21474 	 */
21475 	sd_rmv_resv_reclaim_req(dev);
21476 
21477 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
21478 		mutex_enter(SD_MUTEX(un));
21479 		if ((un->un_mhd_token) &&
21480 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
21481 			mutex_exit(SD_MUTEX(un));
21482 			(void) sd_check_mhd(dev, 0);
21483 		} else {
21484 			mutex_exit(SD_MUTEX(un));
21485 		}
21486 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
21487 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21488 	} else {
21489 		/*
21490 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
21491 		 */
21492 		mutex_enter(SD_MUTEX(un));
21493 		un->un_resvd_status = resvd_status_save;
21494 		mutex_exit(SD_MUTEX(un));
21495 	}
21496 	return (rval);
21497 }
21498 
21499 
21500 /*
21501  *    Function: sd_mhdioc_register_devid
21502  *
21503  * Description: This routine is the driver entry point for handling ioctl
21504  *		requests to register the device id (MHIOCREREGISTERDEVID).
21505  *
21506  *		Note: The implementation for this ioctl has been updated to
21507  *		be consistent with the original PSARC case (1999/357)
21508  *		(4375899, 4241671, 4220005)
21509  *
21510  *   Arguments: dev	- the device number
21511  *
21512  * Return Code: 0
21513  *		ENXIO
21514  */
21515 
21516 static int
21517 sd_mhdioc_register_devid(dev_t dev)
21518 {
21519 	struct sd_lun	*un = NULL;
21520 	int		rval = 0;
21521 
21522 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21523 		return (ENXIO);
21524 	}
21525 
21526 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21527 
21528 	mutex_enter(SD_MUTEX(un));
21529 
21530 	/* If a devid already exists, de-register it */
21531 	if (un->un_devid != NULL) {
21532 		ddi_devid_unregister(SD_DEVINFO(un));
21533 		/*
21534 		 * After unregister devid, needs to free devid memory
21535 		 */
21536 		ddi_devid_free(un->un_devid);
21537 		un->un_devid = NULL;
21538 	}
21539 
21540 	/* Check for reservation conflict */
21541 	mutex_exit(SD_MUTEX(un));
21542 	rval = sd_send_scsi_TEST_UNIT_READY(un, 0);
21543 	mutex_enter(SD_MUTEX(un));
21544 
21545 	switch (rval) {
21546 	case 0:
21547 		sd_register_devid(un, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
21548 		break;
21549 	case EACCES:
21550 		break;
21551 	default:
21552 		rval = EIO;
21553 	}
21554 
21555 	mutex_exit(SD_MUTEX(un));
21556 	return (rval);
21557 }
21558 
21559 
21560 /*
21561  *    Function: sd_mhdioc_inkeys
21562  *
21563  * Description: This routine is the driver entry point for handling ioctl
21564  *		requests to issue the SCSI-3 Persistent In Read Keys command
21565  *		to the device (MHIOCGRP_INKEYS).
21566  *
21567  *   Arguments: dev	- the device number
21568  *		arg	- user provided in_keys structure
21569  *		flag	- this argument is a pass through to ddi_copyxxx()
21570  *			  directly from the mode argument of ioctl().
21571  *
21572  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
21573  *		ENXIO
21574  *		EFAULT
21575  */
21576 
21577 static int
21578 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
21579 {
21580 	struct sd_lun		*un;
21581 	mhioc_inkeys_t		inkeys;
21582 	int			rval = 0;
21583 
21584 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21585 		return (ENXIO);
21586 	}
21587 
21588 #ifdef _MULTI_DATAMODEL
21589 	switch (ddi_model_convert_from(flag & FMODELS)) {
21590 	case DDI_MODEL_ILP32: {
21591 		struct mhioc_inkeys32	inkeys32;
21592 
21593 		if (ddi_copyin(arg, &inkeys32,
21594 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
21595 			return (EFAULT);
21596 		}
21597 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
21598 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21599 		    &inkeys, flag)) != 0) {
21600 			return (rval);
21601 		}
21602 		inkeys32.generation = inkeys.generation;
21603 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
21604 		    flag) != 0) {
21605 			return (EFAULT);
21606 		}
21607 		break;
21608 	}
21609 	case DDI_MODEL_NONE:
21610 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
21611 		    flag) != 0) {
21612 			return (EFAULT);
21613 		}
21614 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21615 		    &inkeys, flag)) != 0) {
21616 			return (rval);
21617 		}
21618 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
21619 		    flag) != 0) {
21620 			return (EFAULT);
21621 		}
21622 		break;
21623 	}
21624 
21625 #else /* ! _MULTI_DATAMODEL */
21626 
21627 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
21628 		return (EFAULT);
21629 	}
21630 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
21631 	if (rval != 0) {
21632 		return (rval);
21633 	}
21634 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
21635 		return (EFAULT);
21636 	}
21637 
21638 #endif /* _MULTI_DATAMODEL */
21639 
21640 	return (rval);
21641 }
21642 
21643 
21644 /*
21645  *    Function: sd_mhdioc_inresv
21646  *
21647  * Description: This routine is the driver entry point for handling ioctl
21648  *		requests to issue the SCSI-3 Persistent In Read Reservations
21649  *		command to the device (MHIOCGRP_INKEYS).
21650  *
21651  *   Arguments: dev	- the device number
21652  *		arg	- user provided in_resv structure
21653  *		flag	- this argument is a pass through to ddi_copyxxx()
21654  *			  directly from the mode argument of ioctl().
21655  *
21656  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
21657  *		ENXIO
21658  *		EFAULT
21659  */
21660 
21661 static int
21662 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
21663 {
21664 	struct sd_lun		*un;
21665 	mhioc_inresvs_t		inresvs;
21666 	int			rval = 0;
21667 
21668 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21669 		return (ENXIO);
21670 	}
21671 
21672 #ifdef _MULTI_DATAMODEL
21673 
21674 	switch (ddi_model_convert_from(flag & FMODELS)) {
21675 	case DDI_MODEL_ILP32: {
21676 		struct mhioc_inresvs32	inresvs32;
21677 
21678 		if (ddi_copyin(arg, &inresvs32,
21679 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21680 			return (EFAULT);
21681 		}
21682 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
21683 		if ((rval = sd_persistent_reservation_in_read_resv(un,
21684 		    &inresvs, flag)) != 0) {
21685 			return (rval);
21686 		}
21687 		inresvs32.generation = inresvs.generation;
21688 		if (ddi_copyout(&inresvs32, arg,
21689 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21690 			return (EFAULT);
21691 		}
21692 		break;
21693 	}
21694 	case DDI_MODEL_NONE:
21695 		if (ddi_copyin(arg, &inresvs,
21696 		    sizeof (mhioc_inresvs_t), flag) != 0) {
21697 			return (EFAULT);
21698 		}
21699 		if ((rval = sd_persistent_reservation_in_read_resv(un,
21700 		    &inresvs, flag)) != 0) {
21701 			return (rval);
21702 		}
21703 		if (ddi_copyout(&inresvs, arg,
21704 		    sizeof (mhioc_inresvs_t), flag) != 0) {
21705 			return (EFAULT);
21706 		}
21707 		break;
21708 	}
21709 
21710 #else /* ! _MULTI_DATAMODEL */
21711 
21712 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
21713 		return (EFAULT);
21714 	}
21715 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
21716 	if (rval != 0) {
21717 		return (rval);
21718 	}
21719 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
21720 		return (EFAULT);
21721 	}
21722 
21723 #endif /* ! _MULTI_DATAMODEL */
21724 
21725 	return (rval);
21726 }
21727 
21728 
21729 /*
21730  * The following routines support the clustering functionality described below
21731  * and implement lost reservation reclaim functionality.
21732  *
21733  * Clustering
21734  * ----------
21735  * The clustering code uses two different, independent forms of SCSI
21736  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
21737  * Persistent Group Reservations. For any particular disk, it will use either
21738  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
21739  *
21740  * SCSI-2
21741  * The cluster software takes ownership of a multi-hosted disk by issuing the
21742  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
21743  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
21744  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
21745  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
21746  * driver. The meaning of failfast is that if the driver (on this host) ever
21747  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
21748  * it should immediately panic the host. The motivation for this ioctl is that
21749  * if this host does encounter reservation conflict, the underlying cause is
21750  * that some other host of the cluster has decided that this host is no longer
21751  * in the cluster and has seized control of the disks for itself. Since this
21752  * host is no longer in the cluster, it ought to panic itself. The
21753  * MHIOCENFAILFAST ioctl does two things:
21754  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
21755  *      error to panic the host
21756  *      (b) it sets up a periodic timer to test whether this host still has
21757  *      "access" (in that no other host has reserved the device):  if the
21758  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
21759  *      purpose of that periodic timer is to handle scenarios where the host is
21760  *      otherwise temporarily quiescent, temporarily doing no real i/o.
21761  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
21762  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
21763  * the device itself.
21764  *
21765  * SCSI-3 PGR
21766  * A direct semantic implementation of the SCSI-3 Persistent Reservation
21767  * facility is supported through the shared multihost disk ioctls
21768  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
21769  * MHIOCGRP_PREEMPTANDABORT)
21770  *
21771  * Reservation Reclaim:
21772  * --------------------
21773  * To support the lost reservation reclaim operations this driver creates a
21774  * single thread to handle reinstating reservations on all devices that have
21775  * lost reservations sd_resv_reclaim_requests are logged for all devices that
21776  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
21777  * and the reservation reclaim thread loops through the requests to regain the
21778  * lost reservations.
21779  */
21780 
21781 /*
21782  *    Function: sd_check_mhd()
21783  *
21784  * Description: This function sets up and submits a scsi watch request or
21785  *		terminates an existing watch request. This routine is used in
21786  *		support of reservation reclaim.
21787  *
21788  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
21789  *			 among multiple watches that share the callback function
21790  *		interval - the number of microseconds specifying the watch
21791  *			   interval for issuing TEST UNIT READY commands. If
21792  *			   set to 0 the watch should be terminated. If the
21793  *			   interval is set to 0 and if the device is required
21794  *			   to hold reservation while disabling failfast, the
21795  *			   watch is restarted with an interval of
21796  *			   reinstate_resv_delay.
21797  *
21798  * Return Code: 0	   - Successful submit/terminate of scsi watch request
21799  *		ENXIO      - Indicates an invalid device was specified
21800  *		EAGAIN     - Unable to submit the scsi watch request
21801  */
21802 
21803 static int
21804 sd_check_mhd(dev_t dev, int interval)
21805 {
21806 	struct sd_lun	*un;
21807 	opaque_t	token;
21808 
21809 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21810 		return (ENXIO);
21811 	}
21812 
21813 	/* is this a watch termination request? */
21814 	if (interval == 0) {
21815 		mutex_enter(SD_MUTEX(un));
21816 		/* if there is an existing watch task then terminate it */
21817 		if (un->un_mhd_token) {
21818 			token = un->un_mhd_token;
21819 			un->un_mhd_token = NULL;
21820 			mutex_exit(SD_MUTEX(un));
21821 			(void) scsi_watch_request_terminate(token,
21822 			    SCSI_WATCH_TERMINATE_WAIT);
21823 			mutex_enter(SD_MUTEX(un));
21824 		} else {
21825 			mutex_exit(SD_MUTEX(un));
21826 			/*
21827 			 * Note: If we return here we don't check for the
21828 			 * failfast case. This is the original legacy
21829 			 * implementation but perhaps we should be checking
21830 			 * the failfast case.
21831 			 */
21832 			return (0);
21833 		}
21834 		/*
21835 		 * If the device is required to hold reservation while
21836 		 * disabling failfast, we need to restart the scsi_watch
21837 		 * routine with an interval of reinstate_resv_delay.
21838 		 */
21839 		if (un->un_resvd_status & SD_RESERVE) {
21840 			interval = sd_reinstate_resv_delay/1000;
21841 		} else {
21842 			/* no failfast so bail */
21843 			mutex_exit(SD_MUTEX(un));
21844 			return (0);
21845 		}
21846 		mutex_exit(SD_MUTEX(un));
21847 	}
21848 
21849 	/*
21850 	 * adjust minimum time interval to 1 second,
21851 	 * and convert from msecs to usecs
21852 	 */
21853 	if (interval > 0 && interval < 1000) {
21854 		interval = 1000;
21855 	}
21856 	interval *= 1000;
21857 
21858 	/*
21859 	 * submit the request to the scsi_watch service
21860 	 */
21861 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
21862 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
21863 	if (token == NULL) {
21864 		return (EAGAIN);
21865 	}
21866 
21867 	/*
21868 	 * save token for termination later on
21869 	 */
21870 	mutex_enter(SD_MUTEX(un));
21871 	un->un_mhd_token = token;
21872 	mutex_exit(SD_MUTEX(un));
21873 	return (0);
21874 }
21875 
21876 
21877 /*
21878  *    Function: sd_mhd_watch_cb()
21879  *
21880  * Description: This function is the call back function used by the scsi watch
21881  *		facility. The scsi watch facility sends the "Test Unit Ready"
21882  *		and processes the status. If applicable (i.e. a "Unit Attention"
21883  *		status and automatic "Request Sense" not used) the scsi watch
21884  *		facility will send a "Request Sense" and retrieve the sense data
21885  *		to be passed to this callback function. In either case the
21886  *		automatic "Request Sense" or the facility submitting one, this
21887  *		callback is passed the status and sense data.
21888  *
21889  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
21890  *			among multiple watches that share this callback function
21891  *		resultp - scsi watch facility result packet containing scsi
21892  *			  packet, status byte and sense data
21893  *
21894  * Return Code: 0 - continue the watch task
21895  *		non-zero - terminate the watch task
21896  */
21897 
21898 static int
21899 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
21900 {
21901 	struct sd_lun			*un;
21902 	struct scsi_status		*statusp;
21903 	uint8_t				*sensep;
21904 	struct scsi_pkt			*pkt;
21905 	uchar_t				actual_sense_length;
21906 	dev_t  				dev = (dev_t)arg;
21907 
21908 	ASSERT(resultp != NULL);
21909 	statusp			= resultp->statusp;
21910 	sensep			= (uint8_t *)resultp->sensep;
21911 	pkt			= resultp->pkt;
21912 	actual_sense_length	= resultp->actual_sense_length;
21913 
21914 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21915 		return (ENXIO);
21916 	}
21917 
21918 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
21919 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
21920 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
21921 
21922 	/* Begin processing of the status and/or sense data */
21923 	if (pkt->pkt_reason != CMD_CMPLT) {
21924 		/* Handle the incomplete packet */
21925 		sd_mhd_watch_incomplete(un, pkt);
21926 		return (0);
21927 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
21928 		if (*((unsigned char *)statusp)
21929 		    == STATUS_RESERVATION_CONFLICT) {
21930 			/*
21931 			 * Handle a reservation conflict by panicking if
21932 			 * configured for failfast or by logging the conflict
21933 			 * and updating the reservation status
21934 			 */
21935 			mutex_enter(SD_MUTEX(un));
21936 			if ((un->un_resvd_status & SD_FAILFAST) &&
21937 			    (sd_failfast_enable)) {
21938 				sd_panic_for_res_conflict(un);
21939 				/*NOTREACHED*/
21940 			}
21941 			SD_INFO(SD_LOG_IOCTL_MHD, un,
21942 			    "sd_mhd_watch_cb: Reservation Conflict\n");
21943 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
21944 			mutex_exit(SD_MUTEX(un));
21945 		}
21946 	}
21947 
21948 	if (sensep != NULL) {
21949 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
21950 			mutex_enter(SD_MUTEX(un));
21951 			if ((scsi_sense_asc(sensep) ==
21952 			    SD_SCSI_RESET_SENSE_CODE) &&
21953 			    (un->un_resvd_status & SD_RESERVE)) {
21954 				/*
21955 				 * The additional sense code indicates a power
21956 				 * on or bus device reset has occurred; update
21957 				 * the reservation status.
21958 				 */
21959 				un->un_resvd_status |=
21960 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
21961 				SD_INFO(SD_LOG_IOCTL_MHD, un,
21962 				    "sd_mhd_watch_cb: Lost Reservation\n");
21963 			}
21964 		} else {
21965 			return (0);
21966 		}
21967 	} else {
21968 		mutex_enter(SD_MUTEX(un));
21969 	}
21970 
21971 	if ((un->un_resvd_status & SD_RESERVE) &&
21972 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
21973 		if (un->un_resvd_status & SD_WANT_RESERVE) {
21974 			/*
21975 			 * A reset occurred in between the last probe and this
21976 			 * one so if a timeout is pending cancel it.
21977 			 */
21978 			if (un->un_resvd_timeid) {
21979 				timeout_id_t temp_id = un->un_resvd_timeid;
21980 				un->un_resvd_timeid = NULL;
21981 				mutex_exit(SD_MUTEX(un));
21982 				(void) untimeout(temp_id);
21983 				mutex_enter(SD_MUTEX(un));
21984 			}
21985 			un->un_resvd_status &= ~SD_WANT_RESERVE;
21986 		}
21987 		if (un->un_resvd_timeid == 0) {
21988 			/* Schedule a timeout to handle the lost reservation */
21989 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
21990 			    (void *)dev,
21991 			    drv_usectohz(sd_reinstate_resv_delay));
21992 		}
21993 	}
21994 	mutex_exit(SD_MUTEX(un));
21995 	return (0);
21996 }
21997 
21998 
21999 /*
22000  *    Function: sd_mhd_watch_incomplete()
22001  *
22002  * Description: This function is used to find out why a scsi pkt sent by the
22003  *		scsi watch facility was not completed. Under some scenarios this
22004  *		routine will return. Otherwise it will send a bus reset to see
22005  *		if the drive is still online.
22006  *
22007  *   Arguments: un  - driver soft state (unit) structure
22008  *		pkt - incomplete scsi pkt
22009  */
22010 
22011 static void
22012 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
22013 {
22014 	int	be_chatty;
22015 	int	perr;
22016 
22017 	ASSERT(pkt != NULL);
22018 	ASSERT(un != NULL);
22019 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
22020 	perr		= (pkt->pkt_statistics & STAT_PERR);
22021 
22022 	mutex_enter(SD_MUTEX(un));
22023 	if (un->un_state == SD_STATE_DUMPING) {
22024 		mutex_exit(SD_MUTEX(un));
22025 		return;
22026 	}
22027 
22028 	switch (pkt->pkt_reason) {
22029 	case CMD_UNX_BUS_FREE:
22030 		/*
22031 		 * If we had a parity error that caused the target to drop BSY*,
22032 		 * don't be chatty about it.
22033 		 */
22034 		if (perr && be_chatty) {
22035 			be_chatty = 0;
22036 		}
22037 		break;
22038 	case CMD_TAG_REJECT:
22039 		/*
22040 		 * The SCSI-2 spec states that a tag reject will be sent by the
22041 		 * target if tagged queuing is not supported. A tag reject may
22042 		 * also be sent during certain initialization periods or to
22043 		 * control internal resources. For the latter case the target
22044 		 * may also return Queue Full.
22045 		 *
22046 		 * If this driver receives a tag reject from a target that is
22047 		 * going through an init period or controlling internal
22048 		 * resources tagged queuing will be disabled. This is a less
22049 		 * than optimal behavior but the driver is unable to determine
22050 		 * the target state and assumes tagged queueing is not supported
22051 		 */
22052 		pkt->pkt_flags = 0;
22053 		un->un_tagflags = 0;
22054 
22055 		if (un->un_f_opt_queueing == TRUE) {
22056 			un->un_throttle = min(un->un_throttle, 3);
22057 		} else {
22058 			un->un_throttle = 1;
22059 		}
22060 		mutex_exit(SD_MUTEX(un));
22061 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
22062 		mutex_enter(SD_MUTEX(un));
22063 		break;
22064 	case CMD_INCOMPLETE:
22065 		/*
22066 		 * The transport stopped with an abnormal state, fallthrough and
22067 		 * reset the target and/or bus unless selection did not complete
22068 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
22069 		 * go through a target/bus reset
22070 		 */
22071 		if (pkt->pkt_state == STATE_GOT_BUS) {
22072 			break;
22073 		}
22074 		/*FALLTHROUGH*/
22075 
22076 	case CMD_TIMEOUT:
22077 	default:
22078 		/*
22079 		 * The lun may still be running the command, so a lun reset
22080 		 * should be attempted. If the lun reset fails or cannot be
22081 		 * issued, than try a target reset. Lastly try a bus reset.
22082 		 */
22083 		if ((pkt->pkt_statistics &
22084 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
22085 			int reset_retval = 0;
22086 			mutex_exit(SD_MUTEX(un));
22087 			if (un->un_f_allow_bus_device_reset == TRUE) {
22088 				if (un->un_f_lun_reset_enabled == TRUE) {
22089 					reset_retval =
22090 					    scsi_reset(SD_ADDRESS(un),
22091 					    RESET_LUN);
22092 				}
22093 				if (reset_retval == 0) {
22094 					reset_retval =
22095 					    scsi_reset(SD_ADDRESS(un),
22096 					    RESET_TARGET);
22097 				}
22098 			}
22099 			if (reset_retval == 0) {
22100 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
22101 			}
22102 			mutex_enter(SD_MUTEX(un));
22103 		}
22104 		break;
22105 	}
22106 
22107 	/* A device/bus reset has occurred; update the reservation status. */
22108 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
22109 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
22110 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22111 			un->un_resvd_status |=
22112 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
22113 			SD_INFO(SD_LOG_IOCTL_MHD, un,
22114 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
22115 		}
22116 	}
22117 
22118 	/*
22119 	 * The disk has been turned off; Update the device state.
22120 	 *
22121 	 * Note: Should we be offlining the disk here?
22122 	 */
22123 	if (pkt->pkt_state == STATE_GOT_BUS) {
22124 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
22125 		    "Disk not responding to selection\n");
22126 		if (un->un_state != SD_STATE_OFFLINE) {
22127 			New_state(un, SD_STATE_OFFLINE);
22128 		}
22129 	} else if (be_chatty) {
22130 		/*
22131 		 * suppress messages if they are all the same pkt reason;
22132 		 * with TQ, many (up to 256) are returned with the same
22133 		 * pkt_reason
22134 		 */
22135 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
22136 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
22137 			    "sd_mhd_watch_incomplete: "
22138 			    "SCSI transport failed: reason '%s'\n",
22139 			    scsi_rname(pkt->pkt_reason));
22140 		}
22141 	}
22142 	un->un_last_pkt_reason = pkt->pkt_reason;
22143 	mutex_exit(SD_MUTEX(un));
22144 }
22145 
22146 
22147 /*
22148  *    Function: sd_sname()
22149  *
22150  * Description: This is a simple little routine to return a string containing
22151  *		a printable description of command status byte for use in
22152  *		logging.
22153  *
22154  *   Arguments: status - pointer to a status byte
22155  *
22156  * Return Code: char * - string containing status description.
22157  */
22158 
22159 static char *
22160 sd_sname(uchar_t status)
22161 {
22162 	switch (status & STATUS_MASK) {
22163 	case STATUS_GOOD:
22164 		return ("good status");
22165 	case STATUS_CHECK:
22166 		return ("check condition");
22167 	case STATUS_MET:
22168 		return ("condition met");
22169 	case STATUS_BUSY:
22170 		return ("busy");
22171 	case STATUS_INTERMEDIATE:
22172 		return ("intermediate");
22173 	case STATUS_INTERMEDIATE_MET:
22174 		return ("intermediate - condition met");
22175 	case STATUS_RESERVATION_CONFLICT:
22176 		return ("reservation_conflict");
22177 	case STATUS_TERMINATED:
22178 		return ("command terminated");
22179 	case STATUS_QFULL:
22180 		return ("queue full");
22181 	default:
22182 		return ("<unknown status>");
22183 	}
22184 }
22185 
22186 
22187 /*
22188  *    Function: sd_mhd_resvd_recover()
22189  *
22190  * Description: This function adds a reservation entry to the
22191  *		sd_resv_reclaim_request list and signals the reservation
22192  *		reclaim thread that there is work pending. If the reservation
22193  *		reclaim thread has not been previously created this function
22194  *		will kick it off.
22195  *
22196  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
22197  *			among multiple watches that share this callback function
22198  *
22199  *     Context: This routine is called by timeout() and is run in interrupt
22200  *		context. It must not sleep or call other functions which may
22201  *		sleep.
22202  */
22203 
22204 static void
22205 sd_mhd_resvd_recover(void *arg)
22206 {
22207 	dev_t			dev = (dev_t)arg;
22208 	struct sd_lun		*un;
22209 	struct sd_thr_request	*sd_treq = NULL;
22210 	struct sd_thr_request	*sd_cur = NULL;
22211 	struct sd_thr_request	*sd_prev = NULL;
22212 	int			already_there = 0;
22213 
22214 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22215 		return;
22216 	}
22217 
22218 	mutex_enter(SD_MUTEX(un));
22219 	un->un_resvd_timeid = NULL;
22220 	if (un->un_resvd_status & SD_WANT_RESERVE) {
22221 		/*
22222 		 * There was a reset so don't issue the reserve, allow the
22223 		 * sd_mhd_watch_cb callback function to notice this and
22224 		 * reschedule the timeout for reservation.
22225 		 */
22226 		mutex_exit(SD_MUTEX(un));
22227 		return;
22228 	}
22229 	mutex_exit(SD_MUTEX(un));
22230 
22231 	/*
22232 	 * Add this device to the sd_resv_reclaim_request list and the
22233 	 * sd_resv_reclaim_thread should take care of the rest.
22234 	 *
22235 	 * Note: We can't sleep in this context so if the memory allocation
22236 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
22237 	 * reschedule the timeout for reservation.  (4378460)
22238 	 */
22239 	sd_treq = (struct sd_thr_request *)
22240 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
22241 	if (sd_treq == NULL) {
22242 		return;
22243 	}
22244 
22245 	sd_treq->sd_thr_req_next = NULL;
22246 	sd_treq->dev = dev;
22247 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22248 	if (sd_tr.srq_thr_req_head == NULL) {
22249 		sd_tr.srq_thr_req_head = sd_treq;
22250 	} else {
22251 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
22252 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
22253 			if (sd_cur->dev == dev) {
22254 				/*
22255 				 * already in Queue so don't log
22256 				 * another request for the device
22257 				 */
22258 				already_there = 1;
22259 				break;
22260 			}
22261 			sd_prev = sd_cur;
22262 		}
22263 		if (!already_there) {
22264 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
22265 			    "logging request for %lx\n", dev);
22266 			sd_prev->sd_thr_req_next = sd_treq;
22267 		} else {
22268 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
22269 		}
22270 	}
22271 
22272 	/*
22273 	 * Create a kernel thread to do the reservation reclaim and free up this
22274 	 * thread. We cannot block this thread while we go away to do the
22275 	 * reservation reclaim
22276 	 */
22277 	if (sd_tr.srq_resv_reclaim_thread == NULL)
22278 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
22279 		    sd_resv_reclaim_thread, NULL,
22280 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
22281 
22282 	/* Tell the reservation reclaim thread that it has work to do */
22283 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
22284 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22285 }
22286 
22287 /*
22288  *    Function: sd_resv_reclaim_thread()
22289  *
22290  * Description: This function implements the reservation reclaim operations
22291  *
22292  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
22293  *		      among multiple watches that share this callback function
22294  */
22295 
22296 static void
22297 sd_resv_reclaim_thread()
22298 {
22299 	struct sd_lun		*un;
22300 	struct sd_thr_request	*sd_mhreq;
22301 
22302 	/* Wait for work */
22303 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22304 	if (sd_tr.srq_thr_req_head == NULL) {
22305 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
22306 		    &sd_tr.srq_resv_reclaim_mutex);
22307 	}
22308 
22309 	/* Loop while we have work */
22310 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
22311 		un = ddi_get_soft_state(sd_state,
22312 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
22313 		if (un == NULL) {
22314 			/*
22315 			 * softstate structure is NULL so just
22316 			 * dequeue the request and continue
22317 			 */
22318 			sd_tr.srq_thr_req_head =
22319 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22320 			kmem_free(sd_tr.srq_thr_cur_req,
22321 			    sizeof (struct sd_thr_request));
22322 			continue;
22323 		}
22324 
22325 		/* dequeue the request */
22326 		sd_mhreq = sd_tr.srq_thr_cur_req;
22327 		sd_tr.srq_thr_req_head =
22328 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22329 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22330 
22331 		/*
22332 		 * Reclaim reservation only if SD_RESERVE is still set. There
22333 		 * may have been a call to MHIOCRELEASE before we got here.
22334 		 */
22335 		mutex_enter(SD_MUTEX(un));
22336 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22337 			/*
22338 			 * Note: The SD_LOST_RESERVE flag is cleared before
22339 			 * reclaiming the reservation. If this is done after the
22340 			 * call to sd_reserve_release a reservation loss in the
22341 			 * window between pkt completion of reserve cmd and
22342 			 * mutex_enter below may not be recognized
22343 			 */
22344 			un->un_resvd_status &= ~SD_LOST_RESERVE;
22345 			mutex_exit(SD_MUTEX(un));
22346 
22347 			if (sd_reserve_release(sd_mhreq->dev,
22348 			    SD_RESERVE) == 0) {
22349 				mutex_enter(SD_MUTEX(un));
22350 				un->un_resvd_status |= SD_RESERVE;
22351 				mutex_exit(SD_MUTEX(un));
22352 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22353 				    "sd_resv_reclaim_thread: "
22354 				    "Reservation Recovered\n");
22355 			} else {
22356 				mutex_enter(SD_MUTEX(un));
22357 				un->un_resvd_status |= SD_LOST_RESERVE;
22358 				mutex_exit(SD_MUTEX(un));
22359 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22360 				    "sd_resv_reclaim_thread: Failed "
22361 				    "Reservation Recovery\n");
22362 			}
22363 		} else {
22364 			mutex_exit(SD_MUTEX(un));
22365 		}
22366 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22367 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
22368 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22369 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
22370 		/*
22371 		 * wakeup the destroy thread if anyone is waiting on
22372 		 * us to complete.
22373 		 */
22374 		cv_signal(&sd_tr.srq_inprocess_cv);
22375 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
22376 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
22377 	}
22378 
22379 	/*
22380 	 * cleanup the sd_tr structure now that this thread will not exist
22381 	 */
22382 	ASSERT(sd_tr.srq_thr_req_head == NULL);
22383 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
22384 	sd_tr.srq_resv_reclaim_thread = NULL;
22385 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22386 	thread_exit();
22387 }
22388 
22389 
22390 /*
22391  *    Function: sd_rmv_resv_reclaim_req()
22392  *
22393  * Description: This function removes any pending reservation reclaim requests
22394  *		for the specified device.
22395  *
22396  *   Arguments: dev - the device 'dev_t'
22397  */
22398 
22399 static void
22400 sd_rmv_resv_reclaim_req(dev_t dev)
22401 {
22402 	struct sd_thr_request *sd_mhreq;
22403 	struct sd_thr_request *sd_prev;
22404 
22405 	/* Remove a reservation reclaim request from the list */
22406 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22407 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
22408 		/*
22409 		 * We are attempting to reinstate reservation for
22410 		 * this device. We wait for sd_reserve_release()
22411 		 * to return before we return.
22412 		 */
22413 		cv_wait(&sd_tr.srq_inprocess_cv,
22414 		    &sd_tr.srq_resv_reclaim_mutex);
22415 	} else {
22416 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
22417 		if (sd_mhreq && sd_mhreq->dev == dev) {
22418 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
22419 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22420 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22421 			return;
22422 		}
22423 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
22424 			if (sd_mhreq && sd_mhreq->dev == dev) {
22425 				break;
22426 			}
22427 			sd_prev = sd_mhreq;
22428 		}
22429 		if (sd_mhreq != NULL) {
22430 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
22431 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22432 		}
22433 	}
22434 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22435 }
22436 
22437 
22438 /*
22439  *    Function: sd_mhd_reset_notify_cb()
22440  *
22441  * Description: This is a call back function for scsi_reset_notify. This
22442  *		function updates the softstate reserved status and logs the
22443  *		reset. The driver scsi watch facility callback function
22444  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
22445  *		will reclaim the reservation.
22446  *
22447  *   Arguments: arg  - driver soft state (unit) structure
22448  */
22449 
22450 static void
22451 sd_mhd_reset_notify_cb(caddr_t arg)
22452 {
22453 	struct sd_lun *un = (struct sd_lun *)arg;
22454 
22455 	mutex_enter(SD_MUTEX(un));
22456 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22457 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
22458 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22459 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
22460 	}
22461 	mutex_exit(SD_MUTEX(un));
22462 }
22463 
22464 
22465 /*
22466  *    Function: sd_take_ownership()
22467  *
22468  * Description: This routine implements an algorithm to achieve a stable
22469  *		reservation on disks which don't implement priority reserve,
22470  *		and makes sure that other host lose re-reservation attempts.
22471  *		This algorithm contains of a loop that keeps issuing the RESERVE
22472  *		for some period of time (min_ownership_delay, default 6 seconds)
22473  *		During that loop, it looks to see if there has been a bus device
22474  *		reset or bus reset (both of which cause an existing reservation
22475  *		to be lost). If the reservation is lost issue RESERVE until a
22476  *		period of min_ownership_delay with no resets has gone by, or
22477  *		until max_ownership_delay has expired. This loop ensures that
22478  *		the host really did manage to reserve the device, in spite of
22479  *		resets. The looping for min_ownership_delay (default six
22480  *		seconds) is important to early generation clustering products,
22481  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
22482  *		MHIOCENFAILFAST periodic timer of two seconds. By having
22483  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
22484  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
22485  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
22486  *		have already noticed, via the MHIOCENFAILFAST polling, that it
22487  *		no longer "owns" the disk and will have panicked itself.  Thus,
22488  *		the host issuing the MHIOCTKOWN is assured (with timing
22489  *		dependencies) that by the time it actually starts to use the
22490  *		disk for real work, the old owner is no longer accessing it.
22491  *
22492  *		min_ownership_delay is the minimum amount of time for which the
22493  *		disk must be reserved continuously devoid of resets before the
22494  *		MHIOCTKOWN ioctl will return success.
22495  *
22496  *		max_ownership_delay indicates the amount of time by which the
22497  *		take ownership should succeed or timeout with an error.
22498  *
22499  *   Arguments: dev - the device 'dev_t'
22500  *		*p  - struct containing timing info.
22501  *
22502  * Return Code: 0 for success or error code
22503  */
22504 
22505 static int
22506 sd_take_ownership(dev_t dev, struct mhioctkown *p)
22507 {
22508 	struct sd_lun	*un;
22509 	int		rval;
22510 	int		err;
22511 	int		reservation_count   = 0;
22512 	int		min_ownership_delay =  6000000; /* in usec */
22513 	int		max_ownership_delay = 30000000; /* in usec */
22514 	clock_t		start_time;	/* starting time of this algorithm */
22515 	clock_t		end_time;	/* time limit for giving up */
22516 	clock_t		ownership_time;	/* time limit for stable ownership */
22517 	clock_t		current_time;
22518 	clock_t		previous_current_time;
22519 
22520 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22521 		return (ENXIO);
22522 	}
22523 
22524 	/*
22525 	 * Attempt a device reservation. A priority reservation is requested.
22526 	 */
22527 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
22528 	    != SD_SUCCESS) {
22529 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
22530 		    "sd_take_ownership: return(1)=%d\n", rval);
22531 		return (rval);
22532 	}
22533 
22534 	/* Update the softstate reserved status to indicate the reservation */
22535 	mutex_enter(SD_MUTEX(un));
22536 	un->un_resvd_status |= SD_RESERVE;
22537 	un->un_resvd_status &=
22538 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
22539 	mutex_exit(SD_MUTEX(un));
22540 
22541 	if (p != NULL) {
22542 		if (p->min_ownership_delay != 0) {
22543 			min_ownership_delay = p->min_ownership_delay * 1000;
22544 		}
22545 		if (p->max_ownership_delay != 0) {
22546 			max_ownership_delay = p->max_ownership_delay * 1000;
22547 		}
22548 	}
22549 	SD_INFO(SD_LOG_IOCTL_MHD, un,
22550 	    "sd_take_ownership: min, max delays: %d, %d\n",
22551 	    min_ownership_delay, max_ownership_delay);
22552 
22553 	start_time = ddi_get_lbolt();
22554 	current_time	= start_time;
22555 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
22556 	end_time	= start_time + drv_usectohz(max_ownership_delay);
22557 
22558 	while (current_time - end_time < 0) {
22559 		delay(drv_usectohz(500000));
22560 
22561 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
22562 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
22563 				mutex_enter(SD_MUTEX(un));
22564 				rval = (un->un_resvd_status &
22565 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
22566 				mutex_exit(SD_MUTEX(un));
22567 				break;
22568 			}
22569 		}
22570 		previous_current_time = current_time;
22571 		current_time = ddi_get_lbolt();
22572 		mutex_enter(SD_MUTEX(un));
22573 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
22574 			ownership_time = ddi_get_lbolt() +
22575 			    drv_usectohz(min_ownership_delay);
22576 			reservation_count = 0;
22577 		} else {
22578 			reservation_count++;
22579 		}
22580 		un->un_resvd_status |= SD_RESERVE;
22581 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
22582 		mutex_exit(SD_MUTEX(un));
22583 
22584 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22585 		    "sd_take_ownership: ticks for loop iteration=%ld, "
22586 		    "reservation=%s\n", (current_time - previous_current_time),
22587 		    reservation_count ? "ok" : "reclaimed");
22588 
22589 		if (current_time - ownership_time >= 0 &&
22590 		    reservation_count >= 4) {
22591 			rval = 0; /* Achieved a stable ownership */
22592 			break;
22593 		}
22594 		if (current_time - end_time >= 0) {
22595 			rval = EACCES; /* No ownership in max possible time */
22596 			break;
22597 		}
22598 	}
22599 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
22600 	    "sd_take_ownership: return(2)=%d\n", rval);
22601 	return (rval);
22602 }
22603 
22604 
22605 /*
22606  *    Function: sd_reserve_release()
22607  *
22608  * Description: This function builds and sends scsi RESERVE, RELEASE, and
22609  *		PRIORITY RESERVE commands based on a user specified command type
22610  *
22611  *   Arguments: dev - the device 'dev_t'
22612  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
22613  *		      SD_RESERVE, SD_RELEASE
22614  *
22615  * Return Code: 0 or Error Code
22616  */
22617 
22618 static int
22619 sd_reserve_release(dev_t dev, int cmd)
22620 {
22621 	struct uscsi_cmd	*com = NULL;
22622 	struct sd_lun		*un = NULL;
22623 	char			cdb[CDB_GROUP0];
22624 	int			rval;
22625 
22626 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
22627 	    (cmd == SD_PRIORITY_RESERVE));
22628 
22629 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22630 		return (ENXIO);
22631 	}
22632 
22633 	/* instantiate and initialize the command and cdb */
22634 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
22635 	bzero(cdb, CDB_GROUP0);
22636 	com->uscsi_flags   = USCSI_SILENT;
22637 	com->uscsi_timeout = un->un_reserve_release_time;
22638 	com->uscsi_cdblen  = CDB_GROUP0;
22639 	com->uscsi_cdb	   = cdb;
22640 	if (cmd == SD_RELEASE) {
22641 		cdb[0] = SCMD_RELEASE;
22642 	} else {
22643 		cdb[0] = SCMD_RESERVE;
22644 	}
22645 
22646 	/* Send the command. */
22647 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22648 	    SD_PATH_STANDARD);
22649 
22650 	/*
22651 	 * "break" a reservation that is held by another host, by issuing a
22652 	 * reset if priority reserve is desired, and we could not get the
22653 	 * device.
22654 	 */
22655 	if ((cmd == SD_PRIORITY_RESERVE) &&
22656 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22657 		/*
22658 		 * First try to reset the LUN. If we cannot, then try a target
22659 		 * reset, followed by a bus reset if the target reset fails.
22660 		 */
22661 		int reset_retval = 0;
22662 		if (un->un_f_lun_reset_enabled == TRUE) {
22663 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
22664 		}
22665 		if (reset_retval == 0) {
22666 			/* The LUN reset either failed or was not issued */
22667 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
22668 		}
22669 		if ((reset_retval == 0) &&
22670 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
22671 			rval = EIO;
22672 			kmem_free(com, sizeof (*com));
22673 			return (rval);
22674 		}
22675 
22676 		bzero(com, sizeof (struct uscsi_cmd));
22677 		com->uscsi_flags   = USCSI_SILENT;
22678 		com->uscsi_cdb	   = cdb;
22679 		com->uscsi_cdblen  = CDB_GROUP0;
22680 		com->uscsi_timeout = 5;
22681 
22682 		/*
22683 		 * Reissue the last reserve command, this time without request
22684 		 * sense.  Assume that it is just a regular reserve command.
22685 		 */
22686 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22687 		    SD_PATH_STANDARD);
22688 	}
22689 
22690 	/* Return an error if still getting a reservation conflict. */
22691 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22692 		rval = EACCES;
22693 	}
22694 
22695 	kmem_free(com, sizeof (*com));
22696 	return (rval);
22697 }
22698 
22699 
22700 #define	SD_NDUMP_RETRIES	12
22701 /*
22702  *	System Crash Dump routine
22703  */
22704 
22705 static int
22706 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
22707 {
22708 	int		instance;
22709 	int		partition;
22710 	int		i;
22711 	int		err;
22712 	struct sd_lun	*un;
22713 	struct scsi_pkt *wr_pktp;
22714 	struct buf	*wr_bp;
22715 	struct buf	wr_buf;
22716 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
22717 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
22718 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
22719 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
22720 	size_t		io_start_offset;
22721 	int		doing_rmw = FALSE;
22722 	int		rval;
22723 	ssize_t		dma_resid;
22724 	daddr_t		oblkno;
22725 	diskaddr_t	nblks = 0;
22726 	diskaddr_t	start_block;
22727 
22728 	instance = SDUNIT(dev);
22729 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
22730 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
22731 		return (ENXIO);
22732 	}
22733 
22734 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
22735 
22736 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
22737 
22738 	partition = SDPART(dev);
22739 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
22740 
22741 	/* Validate blocks to dump at against partition size. */
22742 
22743 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
22744 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
22745 
22746 	if ((blkno + nblk) > nblks) {
22747 		SD_TRACE(SD_LOG_DUMP, un,
22748 		    "sddump: dump range larger than partition: "
22749 		    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
22750 		    blkno, nblk, nblks);
22751 		return (EINVAL);
22752 	}
22753 
22754 	mutex_enter(&un->un_pm_mutex);
22755 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
22756 		struct scsi_pkt *start_pktp;
22757 
22758 		mutex_exit(&un->un_pm_mutex);
22759 
22760 		/*
22761 		 * use pm framework to power on HBA 1st
22762 		 */
22763 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
22764 
22765 		/*
22766 		 * Dump no long uses sdpower to power on a device, it's
22767 		 * in-line here so it can be done in polled mode.
22768 		 */
22769 
22770 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
22771 
22772 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
22773 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
22774 
22775 		if (start_pktp == NULL) {
22776 			/* We were not given a SCSI packet, fail. */
22777 			return (EIO);
22778 		}
22779 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
22780 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
22781 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
22782 		start_pktp->pkt_flags = FLAG_NOINTR;
22783 
22784 		mutex_enter(SD_MUTEX(un));
22785 		SD_FILL_SCSI1_LUN(un, start_pktp);
22786 		mutex_exit(SD_MUTEX(un));
22787 		/*
22788 		 * Scsi_poll returns 0 (success) if the command completes and
22789 		 * the status block is STATUS_GOOD.
22790 		 */
22791 		if (sd_scsi_poll(un, start_pktp) != 0) {
22792 			scsi_destroy_pkt(start_pktp);
22793 			return (EIO);
22794 		}
22795 		scsi_destroy_pkt(start_pktp);
22796 		(void) sd_ddi_pm_resume(un);
22797 	} else {
22798 		mutex_exit(&un->un_pm_mutex);
22799 	}
22800 
22801 	mutex_enter(SD_MUTEX(un));
22802 	un->un_throttle = 0;
22803 
22804 	/*
22805 	 * The first time through, reset the specific target device.
22806 	 * However, when cpr calls sddump we know that sd is in a
22807 	 * a good state so no bus reset is required.
22808 	 * Clear sense data via Request Sense cmd.
22809 	 * In sddump we don't care about allow_bus_device_reset anymore
22810 	 */
22811 
22812 	if ((un->un_state != SD_STATE_SUSPENDED) &&
22813 	    (un->un_state != SD_STATE_DUMPING)) {
22814 
22815 		New_state(un, SD_STATE_DUMPING);
22816 
22817 		if (un->un_f_is_fibre == FALSE) {
22818 			mutex_exit(SD_MUTEX(un));
22819 			/*
22820 			 * Attempt a bus reset for parallel scsi.
22821 			 *
22822 			 * Note: A bus reset is required because on some host
22823 			 * systems (i.e. E420R) a bus device reset is
22824 			 * insufficient to reset the state of the target.
22825 			 *
22826 			 * Note: Don't issue the reset for fibre-channel,
22827 			 * because this tends to hang the bus (loop) for
22828 			 * too long while everyone is logging out and in
22829 			 * and the deadman timer for dumping will fire
22830 			 * before the dump is complete.
22831 			 */
22832 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
22833 				mutex_enter(SD_MUTEX(un));
22834 				Restore_state(un);
22835 				mutex_exit(SD_MUTEX(un));
22836 				return (EIO);
22837 			}
22838 
22839 			/* Delay to give the device some recovery time. */
22840 			drv_usecwait(10000);
22841 
22842 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
22843 				SD_INFO(SD_LOG_DUMP, un,
22844 				    "sddump: sd_send_polled_RQS failed\n");
22845 			}
22846 			mutex_enter(SD_MUTEX(un));
22847 		}
22848 	}
22849 
22850 	/*
22851 	 * Convert the partition-relative block number to a
22852 	 * disk physical block number.
22853 	 */
22854 	blkno += start_block;
22855 
22856 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
22857 
22858 
22859 	/*
22860 	 * Check if the device has a non-512 block size.
22861 	 */
22862 	wr_bp = NULL;
22863 	if (NOT_DEVBSIZE(un)) {
22864 		tgt_byte_offset = blkno * un->un_sys_blocksize;
22865 		tgt_byte_count = nblk * un->un_sys_blocksize;
22866 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
22867 		    (tgt_byte_count % un->un_tgt_blocksize)) {
22868 			doing_rmw = TRUE;
22869 			/*
22870 			 * Calculate the block number and number of block
22871 			 * in terms of the media block size.
22872 			 */
22873 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
22874 			tgt_nblk =
22875 			    ((tgt_byte_offset + tgt_byte_count +
22876 			    (un->un_tgt_blocksize - 1)) /
22877 			    un->un_tgt_blocksize) - tgt_blkno;
22878 
22879 			/*
22880 			 * Invoke the routine which is going to do read part
22881 			 * of read-modify-write.
22882 			 * Note that this routine returns a pointer to
22883 			 * a valid bp in wr_bp.
22884 			 */
22885 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
22886 			    &wr_bp);
22887 			if (err) {
22888 				mutex_exit(SD_MUTEX(un));
22889 				return (err);
22890 			}
22891 			/*
22892 			 * Offset is being calculated as -
22893 			 * (original block # * system block size) -
22894 			 * (new block # * target block size)
22895 			 */
22896 			io_start_offset =
22897 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
22898 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
22899 
22900 			ASSERT((io_start_offset >= 0) &&
22901 			    (io_start_offset < un->un_tgt_blocksize));
22902 			/*
22903 			 * Do the modify portion of read modify write.
22904 			 */
22905 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
22906 			    (size_t)nblk * un->un_sys_blocksize);
22907 		} else {
22908 			doing_rmw = FALSE;
22909 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
22910 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
22911 		}
22912 
22913 		/* Convert blkno and nblk to target blocks */
22914 		blkno = tgt_blkno;
22915 		nblk = tgt_nblk;
22916 	} else {
22917 		wr_bp = &wr_buf;
22918 		bzero(wr_bp, sizeof (struct buf));
22919 		wr_bp->b_flags		= B_BUSY;
22920 		wr_bp->b_un.b_addr	= addr;
22921 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
22922 		wr_bp->b_resid		= 0;
22923 	}
22924 
22925 	mutex_exit(SD_MUTEX(un));
22926 
22927 	/*
22928 	 * Obtain a SCSI packet for the write command.
22929 	 * It should be safe to call the allocator here without
22930 	 * worrying about being locked for DVMA mapping because
22931 	 * the address we're passed is already a DVMA mapping
22932 	 *
22933 	 * We are also not going to worry about semaphore ownership
22934 	 * in the dump buffer. Dumping is single threaded at present.
22935 	 */
22936 
22937 	wr_pktp = NULL;
22938 
22939 	dma_resid = wr_bp->b_bcount;
22940 	oblkno = blkno;
22941 
22942 	while (dma_resid != 0) {
22943 
22944 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
22945 		wr_bp->b_flags &= ~B_ERROR;
22946 
22947 		if (un->un_partial_dma_supported == 1) {
22948 			blkno = oblkno +
22949 			    ((wr_bp->b_bcount - dma_resid) /
22950 			    un->un_tgt_blocksize);
22951 			nblk = dma_resid / un->un_tgt_blocksize;
22952 
22953 			if (wr_pktp) {
22954 				/*
22955 				 * Partial DMA transfers after initial transfer
22956 				 */
22957 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
22958 				    blkno, nblk);
22959 			} else {
22960 				/* Initial transfer */
22961 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
22962 				    un->un_pkt_flags, NULL_FUNC, NULL,
22963 				    blkno, nblk);
22964 			}
22965 		} else {
22966 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
22967 			    0, NULL_FUNC, NULL, blkno, nblk);
22968 		}
22969 
22970 		if (rval == 0) {
22971 			/* We were given a SCSI packet, continue. */
22972 			break;
22973 		}
22974 
22975 		if (i == 0) {
22976 			if (wr_bp->b_flags & B_ERROR) {
22977 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
22978 				    "no resources for dumping; "
22979 				    "error code: 0x%x, retrying",
22980 				    geterror(wr_bp));
22981 			} else {
22982 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
22983 				    "no resources for dumping; retrying");
22984 			}
22985 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
22986 			if (wr_bp->b_flags & B_ERROR) {
22987 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
22988 				    "no resources for dumping; error code: "
22989 				    "0x%x, retrying\n", geterror(wr_bp));
22990 			}
22991 		} else {
22992 			if (wr_bp->b_flags & B_ERROR) {
22993 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
22994 				    "no resources for dumping; "
22995 				    "error code: 0x%x, retries failed, "
22996 				    "giving up.\n", geterror(wr_bp));
22997 			} else {
22998 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
22999 				    "no resources for dumping; "
23000 				    "retries failed, giving up.\n");
23001 			}
23002 			mutex_enter(SD_MUTEX(un));
23003 			Restore_state(un);
23004 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
23005 				mutex_exit(SD_MUTEX(un));
23006 				scsi_free_consistent_buf(wr_bp);
23007 			} else {
23008 				mutex_exit(SD_MUTEX(un));
23009 			}
23010 			return (EIO);
23011 		}
23012 		drv_usecwait(10000);
23013 	}
23014 
23015 	if (un->un_partial_dma_supported == 1) {
23016 		/*
23017 		 * save the resid from PARTIAL_DMA
23018 		 */
23019 		dma_resid = wr_pktp->pkt_resid;
23020 		if (dma_resid != 0)
23021 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
23022 		wr_pktp->pkt_resid = 0;
23023 	} else {
23024 		dma_resid = 0;
23025 	}
23026 
23027 	/* SunBug 1222170 */
23028 	wr_pktp->pkt_flags = FLAG_NOINTR;
23029 
23030 	err = EIO;
23031 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
23032 
23033 		/*
23034 		 * Scsi_poll returns 0 (success) if the command completes and
23035 		 * the status block is STATUS_GOOD.  We should only check
23036 		 * errors if this condition is not true.  Even then we should
23037 		 * send our own request sense packet only if we have a check
23038 		 * condition and auto request sense has not been performed by
23039 		 * the hba.
23040 		 */
23041 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
23042 
23043 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
23044 		    (wr_pktp->pkt_resid == 0)) {
23045 			err = SD_SUCCESS;
23046 			break;
23047 		}
23048 
23049 		/*
23050 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
23051 		 */
23052 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
23053 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23054 			    "Device is gone\n");
23055 			break;
23056 		}
23057 
23058 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
23059 			SD_INFO(SD_LOG_DUMP, un,
23060 			    "sddump: write failed with CHECK, try # %d\n", i);
23061 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
23062 				(void) sd_send_polled_RQS(un);
23063 			}
23064 
23065 			continue;
23066 		}
23067 
23068 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
23069 			int reset_retval = 0;
23070 
23071 			SD_INFO(SD_LOG_DUMP, un,
23072 			    "sddump: write failed with BUSY, try # %d\n", i);
23073 
23074 			if (un->un_f_lun_reset_enabled == TRUE) {
23075 				reset_retval = scsi_reset(SD_ADDRESS(un),
23076 				    RESET_LUN);
23077 			}
23078 			if (reset_retval == 0) {
23079 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
23080 			}
23081 			(void) sd_send_polled_RQS(un);
23082 
23083 		} else {
23084 			SD_INFO(SD_LOG_DUMP, un,
23085 			    "sddump: write failed with 0x%x, try # %d\n",
23086 			    SD_GET_PKT_STATUS(wr_pktp), i);
23087 			mutex_enter(SD_MUTEX(un));
23088 			sd_reset_target(un, wr_pktp);
23089 			mutex_exit(SD_MUTEX(un));
23090 		}
23091 
23092 		/*
23093 		 * If we are not getting anywhere with lun/target resets,
23094 		 * let's reset the bus.
23095 		 */
23096 		if (i == SD_NDUMP_RETRIES/2) {
23097 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
23098 			(void) sd_send_polled_RQS(un);
23099 		}
23100 	}
23101 	}
23102 
23103 	scsi_destroy_pkt(wr_pktp);
23104 	mutex_enter(SD_MUTEX(un));
23105 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
23106 		mutex_exit(SD_MUTEX(un));
23107 		scsi_free_consistent_buf(wr_bp);
23108 	} else {
23109 		mutex_exit(SD_MUTEX(un));
23110 	}
23111 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
23112 	return (err);
23113 }
23114 
23115 /*
23116  *    Function: sd_scsi_poll()
23117  *
23118  * Description: This is a wrapper for the scsi_poll call.
23119  *
23120  *   Arguments: sd_lun - The unit structure
23121  *              scsi_pkt - The scsi packet being sent to the device.
23122  *
23123  * Return Code: 0 - Command completed successfully with good status
23124  *             -1 - Command failed.  This could indicate a check condition
23125  *                  or other status value requiring recovery action.
23126  *
23127  */
23128 
23129 static int
23130 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
23131 {
23132 	int status;
23133 
23134 	ASSERT(un != NULL);
23135 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23136 	ASSERT(pktp != NULL);
23137 
23138 	status = SD_SUCCESS;
23139 
23140 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
23141 		pktp->pkt_flags |= un->un_tagflags;
23142 		pktp->pkt_flags &= ~FLAG_NODISCON;
23143 	}
23144 
23145 	status = sd_ddi_scsi_poll(pktp);
23146 	/*
23147 	 * Scsi_poll returns 0 (success) if the command completes and the
23148 	 * status block is STATUS_GOOD.  We should only check errors if this
23149 	 * condition is not true.  Even then we should send our own request
23150 	 * sense packet only if we have a check condition and auto
23151 	 * request sense has not been performed by the hba.
23152 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
23153 	 */
23154 	if ((status != SD_SUCCESS) &&
23155 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
23156 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
23157 	    (pktp->pkt_reason != CMD_DEV_GONE))
23158 		(void) sd_send_polled_RQS(un);
23159 
23160 	return (status);
23161 }
23162 
23163 /*
23164  *    Function: sd_send_polled_RQS()
23165  *
23166  * Description: This sends the request sense command to a device.
23167  *
23168  *   Arguments: sd_lun - The unit structure
23169  *
23170  * Return Code: 0 - Command completed successfully with good status
23171  *             -1 - Command failed.
23172  *
23173  */
23174 
23175 static int
23176 sd_send_polled_RQS(struct sd_lun *un)
23177 {
23178 	int	ret_val;
23179 	struct	scsi_pkt	*rqs_pktp;
23180 	struct	buf		*rqs_bp;
23181 
23182 	ASSERT(un != NULL);
23183 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23184 
23185 	ret_val = SD_SUCCESS;
23186 
23187 	rqs_pktp = un->un_rqs_pktp;
23188 	rqs_bp	 = un->un_rqs_bp;
23189 
23190 	mutex_enter(SD_MUTEX(un));
23191 
23192 	if (un->un_sense_isbusy) {
23193 		ret_val = SD_FAILURE;
23194 		mutex_exit(SD_MUTEX(un));
23195 		return (ret_val);
23196 	}
23197 
23198 	/*
23199 	 * If the request sense buffer (and packet) is not in use,
23200 	 * let's set the un_sense_isbusy and send our packet
23201 	 */
23202 	un->un_sense_isbusy 	= 1;
23203 	rqs_pktp->pkt_resid  	= 0;
23204 	rqs_pktp->pkt_reason 	= 0;
23205 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
23206 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
23207 
23208 	mutex_exit(SD_MUTEX(un));
23209 
23210 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
23211 	    " 0x%p\n", rqs_bp->b_un.b_addr);
23212 
23213 	/*
23214 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
23215 	 * axle - it has a call into us!
23216 	 */
23217 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
23218 		SD_INFO(SD_LOG_COMMON, un,
23219 		    "sd_send_polled_RQS: RQS failed\n");
23220 	}
23221 
23222 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
23223 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
23224 
23225 	mutex_enter(SD_MUTEX(un));
23226 	un->un_sense_isbusy = 0;
23227 	mutex_exit(SD_MUTEX(un));
23228 
23229 	return (ret_val);
23230 }
23231 
23232 /*
23233  * Defines needed for localized version of the scsi_poll routine.
23234  */
23235 #define	SD_CSEC		10000			/* usecs */
23236 #define	SD_SEC_TO_CSEC	(1000000/SD_CSEC)
23237 
23238 
23239 /*
23240  *    Function: sd_ddi_scsi_poll()
23241  *
23242  * Description: Localized version of the scsi_poll routine.  The purpose is to
23243  *		send a scsi_pkt to a device as a polled command.  This version
23244  *		is to ensure more robust handling of transport errors.
23245  *		Specifically this routine cures not ready, coming ready
23246  *		transition for power up and reset of sonoma's.  This can take
23247  *		up to 45 seconds for power-on and 20 seconds for reset of a
23248  * 		sonoma lun.
23249  *
23250  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
23251  *
23252  * Return Code: 0 - Command completed successfully with good status
23253  *             -1 - Command failed.
23254  *
23255  */
23256 
23257 static int
23258 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
23259 {
23260 	int busy_count;
23261 	int timeout;
23262 	int rval = SD_FAILURE;
23263 	int savef;
23264 	uint8_t *sensep;
23265 	long savet;
23266 	void (*savec)();
23267 	/*
23268 	 * The following is defined in machdep.c and is used in determining if
23269 	 * the scsi transport system will do polled I/O instead of interrupt
23270 	 * I/O when called from xx_dump().
23271 	 */
23272 	extern int do_polled_io;
23273 
23274 	/*
23275 	 * save old flags in pkt, to restore at end
23276 	 */
23277 	savef = pkt->pkt_flags;
23278 	savec = pkt->pkt_comp;
23279 	savet = pkt->pkt_time;
23280 
23281 	pkt->pkt_flags |= FLAG_NOINTR;
23282 
23283 	/*
23284 	 * XXX there is nothing in the SCSA spec that states that we should not
23285 	 * do a callback for polled cmds; however, removing this will break sd
23286 	 * and probably other target drivers
23287 	 */
23288 	pkt->pkt_comp = NULL;
23289 
23290 	/*
23291 	 * we don't like a polled command without timeout.
23292 	 * 60 seconds seems long enough.
23293 	 */
23294 	if (pkt->pkt_time == 0) {
23295 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
23296 	}
23297 
23298 	/*
23299 	 * Send polled cmd.
23300 	 *
23301 	 * We do some error recovery for various errors.  Tran_busy,
23302 	 * queue full, and non-dispatched commands are retried every 10 msec.
23303 	 * as they are typically transient failures.  Busy status and Not
23304 	 * Ready are retried every second as this status takes a while to
23305 	 * change.  Unit attention is retried for pkt_time (60) times
23306 	 * with no delay.
23307 	 */
23308 	timeout = pkt->pkt_time * SD_SEC_TO_CSEC;
23309 
23310 	for (busy_count = 0; busy_count < timeout; busy_count++) {
23311 		int rc;
23312 		int poll_delay;
23313 
23314 		/*
23315 		 * Initialize pkt status variables.
23316 		 */
23317 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
23318 
23319 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
23320 			if (rc != TRAN_BUSY) {
23321 				/* Transport failed - give up. */
23322 				break;
23323 			} else {
23324 				/* Transport busy - try again. */
23325 				poll_delay = 1 * SD_CSEC; /* 10 msec */
23326 			}
23327 		} else {
23328 			/*
23329 			 * Transport accepted - check pkt status.
23330 			 */
23331 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
23332 			if (pkt->pkt_reason == CMD_CMPLT &&
23333 			    rc == STATUS_CHECK &&
23334 			    pkt->pkt_state & STATE_ARQ_DONE) {
23335 				struct scsi_arq_status *arqstat =
23336 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
23337 
23338 				sensep = (uint8_t *)&arqstat->sts_sensedata;
23339 			} else {
23340 				sensep = NULL;
23341 			}
23342 
23343 			if ((pkt->pkt_reason == CMD_CMPLT) &&
23344 			    (rc == STATUS_GOOD)) {
23345 				/* No error - we're done */
23346 				rval = SD_SUCCESS;
23347 				break;
23348 
23349 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
23350 				/* Lost connection - give up */
23351 				break;
23352 
23353 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
23354 			    (pkt->pkt_state == 0)) {
23355 				/* Pkt not dispatched - try again. */
23356 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
23357 
23358 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23359 			    (rc == STATUS_QFULL)) {
23360 				/* Queue full - try again. */
23361 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
23362 
23363 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23364 			    (rc == STATUS_BUSY)) {
23365 				/* Busy - try again. */
23366 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
23367 				busy_count += (SD_SEC_TO_CSEC - 1);
23368 
23369 			} else if ((sensep != NULL) &&
23370 			    (scsi_sense_key(sensep) ==
23371 			    KEY_UNIT_ATTENTION)) {
23372 				/* Unit Attention - try again */
23373 				busy_count += (SD_SEC_TO_CSEC - 1); /* 1 */
23374 				continue;
23375 
23376 			} else if ((sensep != NULL) &&
23377 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
23378 			    (scsi_sense_asc(sensep) == 0x04) &&
23379 			    (scsi_sense_ascq(sensep) == 0x01)) {
23380 				/* Not ready -> ready - try again. */
23381 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
23382 				busy_count += (SD_SEC_TO_CSEC - 1);
23383 
23384 			} else {
23385 				/* BAD status - give up. */
23386 				break;
23387 			}
23388 		}
23389 
23390 		if ((curthread->t_flag & T_INTR_THREAD) == 0 &&
23391 		    !do_polled_io) {
23392 			delay(drv_usectohz(poll_delay));
23393 		} else {
23394 			/* we busy wait during cpr_dump or interrupt threads */
23395 			drv_usecwait(poll_delay);
23396 		}
23397 	}
23398 
23399 	pkt->pkt_flags = savef;
23400 	pkt->pkt_comp = savec;
23401 	pkt->pkt_time = savet;
23402 	return (rval);
23403 }
23404 
23405 
23406 /*
23407  *    Function: sd_persistent_reservation_in_read_keys
23408  *
23409  * Description: This routine is the driver entry point for handling CD-ROM
23410  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
23411  *		by sending the SCSI-3 PRIN commands to the device.
23412  *		Processes the read keys command response by copying the
23413  *		reservation key information into the user provided buffer.
23414  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
23415  *
23416  *   Arguments: un   -  Pointer to soft state struct for the target.
23417  *		usrp -	user provided pointer to multihost Persistent In Read
23418  *			Keys structure (mhioc_inkeys_t)
23419  *		flag -	this argument is a pass through to ddi_copyxxx()
23420  *			directly from the mode argument of ioctl().
23421  *
23422  * Return Code: 0   - Success
23423  *		EACCES
23424  *		ENOTSUP
23425  *		errno return code from sd_send_scsi_cmd()
23426  *
23427  *     Context: Can sleep. Does not return until command is completed.
23428  */
23429 
23430 static int
23431 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
23432     mhioc_inkeys_t *usrp, int flag)
23433 {
23434 #ifdef _MULTI_DATAMODEL
23435 	struct mhioc_key_list32	li32;
23436 #endif
23437 	sd_prin_readkeys_t	*in;
23438 	mhioc_inkeys_t		*ptr;
23439 	mhioc_key_list_t	li;
23440 	uchar_t			*data_bufp;
23441 	int 			data_len;
23442 	int			rval;
23443 	size_t			copysz;
23444 
23445 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
23446 		return (EINVAL);
23447 	}
23448 	bzero(&li, sizeof (mhioc_key_list_t));
23449 
23450 	/*
23451 	 * Get the listsize from user
23452 	 */
23453 #ifdef _MULTI_DATAMODEL
23454 
23455 	switch (ddi_model_convert_from(flag & FMODELS)) {
23456 	case DDI_MODEL_ILP32:
23457 		copysz = sizeof (struct mhioc_key_list32);
23458 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
23459 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23460 			    "sd_persistent_reservation_in_read_keys: "
23461 			    "failed ddi_copyin: mhioc_key_list32_t\n");
23462 			rval = EFAULT;
23463 			goto done;
23464 		}
23465 		li.listsize = li32.listsize;
23466 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
23467 		break;
23468 
23469 	case DDI_MODEL_NONE:
23470 		copysz = sizeof (mhioc_key_list_t);
23471 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23472 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23473 			    "sd_persistent_reservation_in_read_keys: "
23474 			    "failed ddi_copyin: mhioc_key_list_t\n");
23475 			rval = EFAULT;
23476 			goto done;
23477 		}
23478 		break;
23479 	}
23480 
23481 #else /* ! _MULTI_DATAMODEL */
23482 	copysz = sizeof (mhioc_key_list_t);
23483 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23484 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23485 		    "sd_persistent_reservation_in_read_keys: "
23486 		    "failed ddi_copyin: mhioc_key_list_t\n");
23487 		rval = EFAULT;
23488 		goto done;
23489 	}
23490 #endif
23491 
23492 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
23493 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
23494 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23495 
23496 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS,
23497 	    data_len, data_bufp)) != 0) {
23498 		goto done;
23499 	}
23500 	in = (sd_prin_readkeys_t *)data_bufp;
23501 	ptr->generation = BE_32(in->generation);
23502 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
23503 
23504 	/*
23505 	 * Return the min(listsize, listlen) keys
23506 	 */
23507 #ifdef _MULTI_DATAMODEL
23508 
23509 	switch (ddi_model_convert_from(flag & FMODELS)) {
23510 	case DDI_MODEL_ILP32:
23511 		li32.listlen = li.listlen;
23512 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
23513 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23514 			    "sd_persistent_reservation_in_read_keys: "
23515 			    "failed ddi_copyout: mhioc_key_list32_t\n");
23516 			rval = EFAULT;
23517 			goto done;
23518 		}
23519 		break;
23520 
23521 	case DDI_MODEL_NONE:
23522 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23523 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23524 			    "sd_persistent_reservation_in_read_keys: "
23525 			    "failed ddi_copyout: mhioc_key_list_t\n");
23526 			rval = EFAULT;
23527 			goto done;
23528 		}
23529 		break;
23530 	}
23531 
23532 #else /* ! _MULTI_DATAMODEL */
23533 
23534 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23535 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23536 		    "sd_persistent_reservation_in_read_keys: "
23537 		    "failed ddi_copyout: mhioc_key_list_t\n");
23538 		rval = EFAULT;
23539 		goto done;
23540 	}
23541 
23542 #endif /* _MULTI_DATAMODEL */
23543 
23544 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
23545 	    li.listsize * MHIOC_RESV_KEY_SIZE);
23546 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
23547 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23548 		    "sd_persistent_reservation_in_read_keys: "
23549 		    "failed ddi_copyout: keylist\n");
23550 		rval = EFAULT;
23551 	}
23552 done:
23553 	kmem_free(data_bufp, data_len);
23554 	return (rval);
23555 }
23556 
23557 
23558 /*
23559  *    Function: sd_persistent_reservation_in_read_resv
23560  *
23561  * Description: This routine is the driver entry point for handling CD-ROM
23562  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
23563  *		by sending the SCSI-3 PRIN commands to the device.
23564  *		Process the read persistent reservations command response by
23565  *		copying the reservation information into the user provided
23566  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
23567  *
23568  *   Arguments: un   -  Pointer to soft state struct for the target.
23569  *		usrp -	user provided pointer to multihost Persistent In Read
23570  *			Keys structure (mhioc_inkeys_t)
23571  *		flag -	this argument is a pass through to ddi_copyxxx()
23572  *			directly from the mode argument of ioctl().
23573  *
23574  * Return Code: 0   - Success
23575  *		EACCES
23576  *		ENOTSUP
23577  *		errno return code from sd_send_scsi_cmd()
23578  *
23579  *     Context: Can sleep. Does not return until command is completed.
23580  */
23581 
23582 static int
23583 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
23584     mhioc_inresvs_t *usrp, int flag)
23585 {
23586 #ifdef _MULTI_DATAMODEL
23587 	struct mhioc_resv_desc_list32 resvlist32;
23588 #endif
23589 	sd_prin_readresv_t	*in;
23590 	mhioc_inresvs_t		*ptr;
23591 	sd_readresv_desc_t	*readresv_ptr;
23592 	mhioc_resv_desc_list_t	resvlist;
23593 	mhioc_resv_desc_t 	resvdesc;
23594 	uchar_t			*data_bufp;
23595 	int 			data_len;
23596 	int			rval;
23597 	int			i;
23598 	size_t			copysz;
23599 	mhioc_resv_desc_t	*bufp;
23600 
23601 	if ((ptr = usrp) == NULL) {
23602 		return (EINVAL);
23603 	}
23604 
23605 	/*
23606 	 * Get the listsize from user
23607 	 */
23608 #ifdef _MULTI_DATAMODEL
23609 	switch (ddi_model_convert_from(flag & FMODELS)) {
23610 	case DDI_MODEL_ILP32:
23611 		copysz = sizeof (struct mhioc_resv_desc_list32);
23612 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
23613 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23614 			    "sd_persistent_reservation_in_read_resv: "
23615 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23616 			rval = EFAULT;
23617 			goto done;
23618 		}
23619 		resvlist.listsize = resvlist32.listsize;
23620 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
23621 		break;
23622 
23623 	case DDI_MODEL_NONE:
23624 		copysz = sizeof (mhioc_resv_desc_list_t);
23625 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23626 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23627 			    "sd_persistent_reservation_in_read_resv: "
23628 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23629 			rval = EFAULT;
23630 			goto done;
23631 		}
23632 		break;
23633 	}
23634 #else /* ! _MULTI_DATAMODEL */
23635 	copysz = sizeof (mhioc_resv_desc_list_t);
23636 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23637 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23638 		    "sd_persistent_reservation_in_read_resv: "
23639 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23640 		rval = EFAULT;
23641 		goto done;
23642 	}
23643 #endif /* ! _MULTI_DATAMODEL */
23644 
23645 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
23646 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
23647 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23648 
23649 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_RESV,
23650 	    data_len, data_bufp)) != 0) {
23651 		goto done;
23652 	}
23653 	in = (sd_prin_readresv_t *)data_bufp;
23654 	ptr->generation = BE_32(in->generation);
23655 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
23656 
23657 	/*
23658 	 * Return the min(listsize, listlen( keys
23659 	 */
23660 #ifdef _MULTI_DATAMODEL
23661 
23662 	switch (ddi_model_convert_from(flag & FMODELS)) {
23663 	case DDI_MODEL_ILP32:
23664 		resvlist32.listlen = resvlist.listlen;
23665 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
23666 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23667 			    "sd_persistent_reservation_in_read_resv: "
23668 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23669 			rval = EFAULT;
23670 			goto done;
23671 		}
23672 		break;
23673 
23674 	case DDI_MODEL_NONE:
23675 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
23676 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23677 			    "sd_persistent_reservation_in_read_resv: "
23678 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23679 			rval = EFAULT;
23680 			goto done;
23681 		}
23682 		break;
23683 	}
23684 
23685 #else /* ! _MULTI_DATAMODEL */
23686 
23687 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
23688 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23689 		    "sd_persistent_reservation_in_read_resv: "
23690 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23691 		rval = EFAULT;
23692 		goto done;
23693 	}
23694 
23695 #endif /* ! _MULTI_DATAMODEL */
23696 
23697 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
23698 	bufp = resvlist.list;
23699 	copysz = sizeof (mhioc_resv_desc_t);
23700 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
23701 	    i++, readresv_ptr++, bufp++) {
23702 
23703 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
23704 		    MHIOC_RESV_KEY_SIZE);
23705 		resvdesc.type  = readresv_ptr->type;
23706 		resvdesc.scope = readresv_ptr->scope;
23707 		resvdesc.scope_specific_addr =
23708 		    BE_32(readresv_ptr->scope_specific_addr);
23709 
23710 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
23711 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23712 			    "sd_persistent_reservation_in_read_resv: "
23713 			    "failed ddi_copyout: resvlist\n");
23714 			rval = EFAULT;
23715 			goto done;
23716 		}
23717 	}
23718 done:
23719 	kmem_free(data_bufp, data_len);
23720 	return (rval);
23721 }
23722 
23723 
23724 /*
23725  *    Function: sr_change_blkmode()
23726  *
23727  * Description: This routine is the driver entry point for handling CD-ROM
23728  *		block mode ioctl requests. Support for returning and changing
23729  *		the current block size in use by the device is implemented. The
23730  *		LBA size is changed via a MODE SELECT Block Descriptor.
23731  *
23732  *		This routine issues a mode sense with an allocation length of
23733  *		12 bytes for the mode page header and a single block descriptor.
23734  *
23735  *   Arguments: dev - the device 'dev_t'
23736  *		cmd - the request type; one of CDROMGBLKMODE (get) or
23737  *		      CDROMSBLKMODE (set)
23738  *		data - current block size or requested block size
23739  *		flag - this argument is a pass through to ddi_copyxxx() directly
23740  *		       from the mode argument of ioctl().
23741  *
23742  * Return Code: the code returned by sd_send_scsi_cmd()
23743  *		EINVAL if invalid arguments are provided
23744  *		EFAULT if ddi_copyxxx() fails
23745  *		ENXIO if fail ddi_get_soft_state
23746  *		EIO if invalid mode sense block descriptor length
23747  *
23748  */
23749 
23750 static int
23751 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
23752 {
23753 	struct sd_lun			*un = NULL;
23754 	struct mode_header		*sense_mhp, *select_mhp;
23755 	struct block_descriptor		*sense_desc, *select_desc;
23756 	int				current_bsize;
23757 	int				rval = EINVAL;
23758 	uchar_t				*sense = NULL;
23759 	uchar_t				*select = NULL;
23760 
23761 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
23762 
23763 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23764 		return (ENXIO);
23765 	}
23766 
23767 	/*
23768 	 * The block length is changed via the Mode Select block descriptor, the
23769 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
23770 	 * required as part of this routine. Therefore the mode sense allocation
23771 	 * length is specified to be the length of a mode page header and a
23772 	 * block descriptor.
23773 	 */
23774 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
23775 
23776 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
23777 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD)) != 0) {
23778 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23779 		    "sr_change_blkmode: Mode Sense Failed\n");
23780 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23781 		return (rval);
23782 	}
23783 
23784 	/* Check the block descriptor len to handle only 1 block descriptor */
23785 	sense_mhp = (struct mode_header *)sense;
23786 	if ((sense_mhp->bdesc_length == 0) ||
23787 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
23788 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23789 		    "sr_change_blkmode: Mode Sense returned invalid block"
23790 		    " descriptor length\n");
23791 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23792 		return (EIO);
23793 	}
23794 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
23795 	current_bsize = ((sense_desc->blksize_hi << 16) |
23796 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
23797 
23798 	/* Process command */
23799 	switch (cmd) {
23800 	case CDROMGBLKMODE:
23801 		/* Return the block size obtained during the mode sense */
23802 		if (ddi_copyout(&current_bsize, (void *)data,
23803 		    sizeof (int), flag) != 0)
23804 			rval = EFAULT;
23805 		break;
23806 	case CDROMSBLKMODE:
23807 		/* Validate the requested block size */
23808 		switch (data) {
23809 		case CDROM_BLK_512:
23810 		case CDROM_BLK_1024:
23811 		case CDROM_BLK_2048:
23812 		case CDROM_BLK_2056:
23813 		case CDROM_BLK_2336:
23814 		case CDROM_BLK_2340:
23815 		case CDROM_BLK_2352:
23816 		case CDROM_BLK_2368:
23817 		case CDROM_BLK_2448:
23818 		case CDROM_BLK_2646:
23819 		case CDROM_BLK_2647:
23820 			break;
23821 		default:
23822 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23823 			    "sr_change_blkmode: "
23824 			    "Block Size '%ld' Not Supported\n", data);
23825 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23826 			return (EINVAL);
23827 		}
23828 
23829 		/*
23830 		 * The current block size matches the requested block size so
23831 		 * there is no need to send the mode select to change the size
23832 		 */
23833 		if (current_bsize == data) {
23834 			break;
23835 		}
23836 
23837 		/* Build the select data for the requested block size */
23838 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
23839 		select_mhp = (struct mode_header *)select;
23840 		select_desc =
23841 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
23842 		/*
23843 		 * The LBA size is changed via the block descriptor, so the
23844 		 * descriptor is built according to the user data
23845 		 */
23846 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
23847 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
23848 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
23849 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
23850 
23851 		/* Send the mode select for the requested block size */
23852 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
23853 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
23854 		    SD_PATH_STANDARD)) != 0) {
23855 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23856 			    "sr_change_blkmode: Mode Select Failed\n");
23857 			/*
23858 			 * The mode select failed for the requested block size,
23859 			 * so reset the data for the original block size and
23860 			 * send it to the target. The error is indicated by the
23861 			 * return value for the failed mode select.
23862 			 */
23863 			select_desc->blksize_hi  = sense_desc->blksize_hi;
23864 			select_desc->blksize_mid = sense_desc->blksize_mid;
23865 			select_desc->blksize_lo  = sense_desc->blksize_lo;
23866 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
23867 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
23868 			    SD_PATH_STANDARD);
23869 		} else {
23870 			ASSERT(!mutex_owned(SD_MUTEX(un)));
23871 			mutex_enter(SD_MUTEX(un));
23872 			sd_update_block_info(un, (uint32_t)data, 0);
23873 			mutex_exit(SD_MUTEX(un));
23874 		}
23875 		break;
23876 	default:
23877 		/* should not reach here, but check anyway */
23878 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23879 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
23880 		rval = EINVAL;
23881 		break;
23882 	}
23883 
23884 	if (select) {
23885 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
23886 	}
23887 	if (sense) {
23888 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23889 	}
23890 	return (rval);
23891 }
23892 
23893 
23894 /*
23895  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
23896  * implement driver support for getting and setting the CD speed. The command
23897  * set used will be based on the device type. If the device has not been
23898  * identified as MMC the Toshiba vendor specific mode page will be used. If
23899  * the device is MMC but does not support the Real Time Streaming feature
23900  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
23901  * be used to read the speed.
23902  */
23903 
23904 /*
23905  *    Function: sr_change_speed()
23906  *
23907  * Description: This routine is the driver entry point for handling CD-ROM
23908  *		drive speed ioctl requests for devices supporting the Toshiba
23909  *		vendor specific drive speed mode page. Support for returning
23910  *		and changing the current drive speed in use by the device is
23911  *		implemented.
23912  *
23913  *   Arguments: dev - the device 'dev_t'
23914  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
23915  *		      CDROMSDRVSPEED (set)
23916  *		data - current drive speed or requested drive speed
23917  *		flag - this argument is a pass through to ddi_copyxxx() directly
23918  *		       from the mode argument of ioctl().
23919  *
23920  * Return Code: the code returned by sd_send_scsi_cmd()
23921  *		EINVAL if invalid arguments are provided
23922  *		EFAULT if ddi_copyxxx() fails
23923  *		ENXIO if fail ddi_get_soft_state
23924  *		EIO if invalid mode sense block descriptor length
23925  */
23926 
23927 static int
23928 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
23929 {
23930 	struct sd_lun			*un = NULL;
23931 	struct mode_header		*sense_mhp, *select_mhp;
23932 	struct mode_speed		*sense_page, *select_page;
23933 	int				current_speed;
23934 	int				rval = EINVAL;
23935 	int				bd_len;
23936 	uchar_t				*sense = NULL;
23937 	uchar_t				*select = NULL;
23938 
23939 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
23940 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23941 		return (ENXIO);
23942 	}
23943 
23944 	/*
23945 	 * Note: The drive speed is being modified here according to a Toshiba
23946 	 * vendor specific mode page (0x31).
23947 	 */
23948 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
23949 
23950 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
23951 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
23952 	    SD_PATH_STANDARD)) != 0) {
23953 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23954 		    "sr_change_speed: Mode Sense Failed\n");
23955 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
23956 		return (rval);
23957 	}
23958 	sense_mhp  = (struct mode_header *)sense;
23959 
23960 	/* Check the block descriptor len to handle only 1 block descriptor */
23961 	bd_len = sense_mhp->bdesc_length;
23962 	if (bd_len > MODE_BLK_DESC_LENGTH) {
23963 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23964 		    "sr_change_speed: Mode Sense returned invalid block "
23965 		    "descriptor length\n");
23966 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
23967 		return (EIO);
23968 	}
23969 
23970 	sense_page = (struct mode_speed *)
23971 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
23972 	current_speed = sense_page->speed;
23973 
23974 	/* Process command */
23975 	switch (cmd) {
23976 	case CDROMGDRVSPEED:
23977 		/* Return the drive speed obtained during the mode sense */
23978 		if (current_speed == 0x2) {
23979 			current_speed = CDROM_TWELVE_SPEED;
23980 		}
23981 		if (ddi_copyout(&current_speed, (void *)data,
23982 		    sizeof (int), flag) != 0) {
23983 			rval = EFAULT;
23984 		}
23985 		break;
23986 	case CDROMSDRVSPEED:
23987 		/* Validate the requested drive speed */
23988 		switch ((uchar_t)data) {
23989 		case CDROM_TWELVE_SPEED:
23990 			data = 0x2;
23991 			/*FALLTHROUGH*/
23992 		case CDROM_NORMAL_SPEED:
23993 		case CDROM_DOUBLE_SPEED:
23994 		case CDROM_QUAD_SPEED:
23995 		case CDROM_MAXIMUM_SPEED:
23996 			break;
23997 		default:
23998 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23999 			    "sr_change_speed: "
24000 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
24001 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24002 			return (EINVAL);
24003 		}
24004 
24005 		/*
24006 		 * The current drive speed matches the requested drive speed so
24007 		 * there is no need to send the mode select to change the speed
24008 		 */
24009 		if (current_speed == data) {
24010 			break;
24011 		}
24012 
24013 		/* Build the select data for the requested drive speed */
24014 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
24015 		select_mhp = (struct mode_header *)select;
24016 		select_mhp->bdesc_length = 0;
24017 		select_page =
24018 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
24019 		select_page =
24020 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
24021 		select_page->mode_page.code = CDROM_MODE_SPEED;
24022 		select_page->mode_page.length = 2;
24023 		select_page->speed = (uchar_t)data;
24024 
24025 		/* Send the mode select for the requested block size */
24026 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
24027 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
24028 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
24029 			/*
24030 			 * The mode select failed for the requested drive speed,
24031 			 * so reset the data for the original drive speed and
24032 			 * send it to the target. The error is indicated by the
24033 			 * return value for the failed mode select.
24034 			 */
24035 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24036 			    "sr_drive_speed: Mode Select Failed\n");
24037 			select_page->speed = sense_page->speed;
24038 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
24039 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
24040 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
24041 		}
24042 		break;
24043 	default:
24044 		/* should not reach here, but check anyway */
24045 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24046 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
24047 		rval = EINVAL;
24048 		break;
24049 	}
24050 
24051 	if (select) {
24052 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
24053 	}
24054 	if (sense) {
24055 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24056 	}
24057 
24058 	return (rval);
24059 }
24060 
24061 
24062 /*
24063  *    Function: sr_atapi_change_speed()
24064  *
24065  * Description: This routine is the driver entry point for handling CD-ROM
24066  *		drive speed ioctl requests for MMC devices that do not support
24067  *		the Real Time Streaming feature (0x107).
24068  *
24069  *		Note: This routine will use the SET SPEED command which may not
24070  *		be supported by all devices.
24071  *
24072  *   Arguments: dev- the device 'dev_t'
24073  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
24074  *		     CDROMSDRVSPEED (set)
24075  *		data- current drive speed or requested drive speed
24076  *		flag- this argument is a pass through to ddi_copyxxx() directly
24077  *		      from the mode argument of ioctl().
24078  *
24079  * Return Code: the code returned by sd_send_scsi_cmd()
24080  *		EINVAL if invalid arguments are provided
24081  *		EFAULT if ddi_copyxxx() fails
24082  *		ENXIO if fail ddi_get_soft_state
24083  *		EIO if invalid mode sense block descriptor length
24084  */
24085 
24086 static int
24087 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
24088 {
24089 	struct sd_lun			*un;
24090 	struct uscsi_cmd		*com = NULL;
24091 	struct mode_header_grp2		*sense_mhp;
24092 	uchar_t				*sense_page;
24093 	uchar_t				*sense = NULL;
24094 	char				cdb[CDB_GROUP5];
24095 	int				bd_len;
24096 	int				current_speed = 0;
24097 	int				max_speed = 0;
24098 	int				rval;
24099 
24100 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
24101 
24102 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24103 		return (ENXIO);
24104 	}
24105 
24106 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
24107 
24108 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
24109 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
24110 	    SD_PATH_STANDARD)) != 0) {
24111 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24112 		    "sr_atapi_change_speed: Mode Sense Failed\n");
24113 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24114 		return (rval);
24115 	}
24116 
24117 	/* Check the block descriptor len to handle only 1 block descriptor */
24118 	sense_mhp = (struct mode_header_grp2 *)sense;
24119 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
24120 	if (bd_len > MODE_BLK_DESC_LENGTH) {
24121 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24122 		    "sr_atapi_change_speed: Mode Sense returned invalid "
24123 		    "block descriptor length\n");
24124 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24125 		return (EIO);
24126 	}
24127 
24128 	/* Calculate the current and maximum drive speeds */
24129 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
24130 	current_speed = (sense_page[14] << 8) | sense_page[15];
24131 	max_speed = (sense_page[8] << 8) | sense_page[9];
24132 
24133 	/* Process the command */
24134 	switch (cmd) {
24135 	case CDROMGDRVSPEED:
24136 		current_speed /= SD_SPEED_1X;
24137 		if (ddi_copyout(&current_speed, (void *)data,
24138 		    sizeof (int), flag) != 0)
24139 			rval = EFAULT;
24140 		break;
24141 	case CDROMSDRVSPEED:
24142 		/* Convert the speed code to KB/sec */
24143 		switch ((uchar_t)data) {
24144 		case CDROM_NORMAL_SPEED:
24145 			current_speed = SD_SPEED_1X;
24146 			break;
24147 		case CDROM_DOUBLE_SPEED:
24148 			current_speed = 2 * SD_SPEED_1X;
24149 			break;
24150 		case CDROM_QUAD_SPEED:
24151 			current_speed = 4 * SD_SPEED_1X;
24152 			break;
24153 		case CDROM_TWELVE_SPEED:
24154 			current_speed = 12 * SD_SPEED_1X;
24155 			break;
24156 		case CDROM_MAXIMUM_SPEED:
24157 			current_speed = 0xffff;
24158 			break;
24159 		default:
24160 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24161 			    "sr_atapi_change_speed: invalid drive speed %d\n",
24162 			    (uchar_t)data);
24163 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24164 			return (EINVAL);
24165 		}
24166 
24167 		/* Check the request against the drive's max speed. */
24168 		if (current_speed != 0xffff) {
24169 			if (current_speed > max_speed) {
24170 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24171 				return (EINVAL);
24172 			}
24173 		}
24174 
24175 		/*
24176 		 * Build and send the SET SPEED command
24177 		 *
24178 		 * Note: The SET SPEED (0xBB) command used in this routine is
24179 		 * obsolete per the SCSI MMC spec but still supported in the
24180 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
24181 		 * therefore the command is still implemented in this routine.
24182 		 */
24183 		bzero(cdb, sizeof (cdb));
24184 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
24185 		cdb[2] = (uchar_t)(current_speed >> 8);
24186 		cdb[3] = (uchar_t)current_speed;
24187 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24188 		com->uscsi_cdb	   = (caddr_t)cdb;
24189 		com->uscsi_cdblen  = CDB_GROUP5;
24190 		com->uscsi_bufaddr = NULL;
24191 		com->uscsi_buflen  = 0;
24192 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
24193 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
24194 		break;
24195 	default:
24196 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24197 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
24198 		rval = EINVAL;
24199 	}
24200 
24201 	if (sense) {
24202 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24203 	}
24204 	if (com) {
24205 		kmem_free(com, sizeof (*com));
24206 	}
24207 	return (rval);
24208 }
24209 
24210 
24211 /*
24212  *    Function: sr_pause_resume()
24213  *
24214  * Description: This routine is the driver entry point for handling CD-ROM
24215  *		pause/resume ioctl requests. This only affects the audio play
24216  *		operation.
24217  *
24218  *   Arguments: dev - the device 'dev_t'
24219  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
24220  *		      for setting the resume bit of the cdb.
24221  *
24222  * Return Code: the code returned by sd_send_scsi_cmd()
24223  *		EINVAL if invalid mode specified
24224  *
24225  */
24226 
24227 static int
24228 sr_pause_resume(dev_t dev, int cmd)
24229 {
24230 	struct sd_lun		*un;
24231 	struct uscsi_cmd	*com;
24232 	char			cdb[CDB_GROUP1];
24233 	int			rval;
24234 
24235 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24236 		return (ENXIO);
24237 	}
24238 
24239 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24240 	bzero(cdb, CDB_GROUP1);
24241 	cdb[0] = SCMD_PAUSE_RESUME;
24242 	switch (cmd) {
24243 	case CDROMRESUME:
24244 		cdb[8] = 1;
24245 		break;
24246 	case CDROMPAUSE:
24247 		cdb[8] = 0;
24248 		break;
24249 	default:
24250 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
24251 		    " Command '%x' Not Supported\n", cmd);
24252 		rval = EINVAL;
24253 		goto done;
24254 	}
24255 
24256 	com->uscsi_cdb    = cdb;
24257 	com->uscsi_cdblen = CDB_GROUP1;
24258 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24259 
24260 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24261 	    SD_PATH_STANDARD);
24262 
24263 done:
24264 	kmem_free(com, sizeof (*com));
24265 	return (rval);
24266 }
24267 
24268 
24269 /*
24270  *    Function: sr_play_msf()
24271  *
24272  * Description: This routine is the driver entry point for handling CD-ROM
24273  *		ioctl requests to output the audio signals at the specified
24274  *		starting address and continue the audio play until the specified
24275  *		ending address (CDROMPLAYMSF) The address is in Minute Second
24276  *		Frame (MSF) format.
24277  *
24278  *   Arguments: dev	- the device 'dev_t'
24279  *		data	- pointer to user provided audio msf structure,
24280  *		          specifying start/end addresses.
24281  *		flag	- this argument is a pass through to ddi_copyxxx()
24282  *		          directly from the mode argument of ioctl().
24283  *
24284  * Return Code: the code returned by sd_send_scsi_cmd()
24285  *		EFAULT if ddi_copyxxx() fails
24286  *		ENXIO if fail ddi_get_soft_state
24287  *		EINVAL if data pointer is NULL
24288  */
24289 
24290 static int
24291 sr_play_msf(dev_t dev, caddr_t data, int flag)
24292 {
24293 	struct sd_lun		*un;
24294 	struct uscsi_cmd	*com;
24295 	struct cdrom_msf	msf_struct;
24296 	struct cdrom_msf	*msf = &msf_struct;
24297 	char			cdb[CDB_GROUP1];
24298 	int			rval;
24299 
24300 	if (data == NULL) {
24301 		return (EINVAL);
24302 	}
24303 
24304 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24305 		return (ENXIO);
24306 	}
24307 
24308 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
24309 		return (EFAULT);
24310 	}
24311 
24312 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24313 	bzero(cdb, CDB_GROUP1);
24314 	cdb[0] = SCMD_PLAYAUDIO_MSF;
24315 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
24316 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
24317 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
24318 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
24319 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
24320 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
24321 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
24322 	} else {
24323 		cdb[3] = msf->cdmsf_min0;
24324 		cdb[4] = msf->cdmsf_sec0;
24325 		cdb[5] = msf->cdmsf_frame0;
24326 		cdb[6] = msf->cdmsf_min1;
24327 		cdb[7] = msf->cdmsf_sec1;
24328 		cdb[8] = msf->cdmsf_frame1;
24329 	}
24330 	com->uscsi_cdb    = cdb;
24331 	com->uscsi_cdblen = CDB_GROUP1;
24332 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24333 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24334 	    SD_PATH_STANDARD);
24335 	kmem_free(com, sizeof (*com));
24336 	return (rval);
24337 }
24338 
24339 
24340 /*
24341  *    Function: sr_play_trkind()
24342  *
24343  * Description: This routine is the driver entry point for handling CD-ROM
24344  *		ioctl requests to output the audio signals at the specified
24345  *		starting address and continue the audio play until the specified
24346  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
24347  *		format.
24348  *
24349  *   Arguments: dev	- the device 'dev_t'
24350  *		data	- pointer to user provided audio track/index structure,
24351  *		          specifying start/end addresses.
24352  *		flag	- this argument is a pass through to ddi_copyxxx()
24353  *		          directly from the mode argument of ioctl().
24354  *
24355  * Return Code: the code returned by sd_send_scsi_cmd()
24356  *		EFAULT if ddi_copyxxx() fails
24357  *		ENXIO if fail ddi_get_soft_state
24358  *		EINVAL if data pointer is NULL
24359  */
24360 
24361 static int
24362 sr_play_trkind(dev_t dev, caddr_t data, int flag)
24363 {
24364 	struct cdrom_ti		ti_struct;
24365 	struct cdrom_ti		*ti = &ti_struct;
24366 	struct uscsi_cmd	*com = NULL;
24367 	char			cdb[CDB_GROUP1];
24368 	int			rval;
24369 
24370 	if (data == NULL) {
24371 		return (EINVAL);
24372 	}
24373 
24374 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
24375 		return (EFAULT);
24376 	}
24377 
24378 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24379 	bzero(cdb, CDB_GROUP1);
24380 	cdb[0] = SCMD_PLAYAUDIO_TI;
24381 	cdb[4] = ti->cdti_trk0;
24382 	cdb[5] = ti->cdti_ind0;
24383 	cdb[7] = ti->cdti_trk1;
24384 	cdb[8] = ti->cdti_ind1;
24385 	com->uscsi_cdb    = cdb;
24386 	com->uscsi_cdblen = CDB_GROUP1;
24387 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24388 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24389 	    SD_PATH_STANDARD);
24390 	kmem_free(com, sizeof (*com));
24391 	return (rval);
24392 }
24393 
24394 
24395 /*
24396  *    Function: sr_read_all_subcodes()
24397  *
24398  * Description: This routine is the driver entry point for handling CD-ROM
24399  *		ioctl requests to return raw subcode data while the target is
24400  *		playing audio (CDROMSUBCODE).
24401  *
24402  *   Arguments: dev	- the device 'dev_t'
24403  *		data	- pointer to user provided cdrom subcode structure,
24404  *		          specifying the transfer length and address.
24405  *		flag	- this argument is a pass through to ddi_copyxxx()
24406  *		          directly from the mode argument of ioctl().
24407  *
24408  * Return Code: the code returned by sd_send_scsi_cmd()
24409  *		EFAULT if ddi_copyxxx() fails
24410  *		ENXIO if fail ddi_get_soft_state
24411  *		EINVAL if data pointer is NULL
24412  */
24413 
24414 static int
24415 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
24416 {
24417 	struct sd_lun		*un = NULL;
24418 	struct uscsi_cmd	*com = NULL;
24419 	struct cdrom_subcode	*subcode = NULL;
24420 	int			rval;
24421 	size_t			buflen;
24422 	char			cdb[CDB_GROUP5];
24423 
24424 #ifdef _MULTI_DATAMODEL
24425 	/* To support ILP32 applications in an LP64 world */
24426 	struct cdrom_subcode32		cdrom_subcode32;
24427 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
24428 #endif
24429 	if (data == NULL) {
24430 		return (EINVAL);
24431 	}
24432 
24433 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24434 		return (ENXIO);
24435 	}
24436 
24437 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
24438 
24439 #ifdef _MULTI_DATAMODEL
24440 	switch (ddi_model_convert_from(flag & FMODELS)) {
24441 	case DDI_MODEL_ILP32:
24442 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
24443 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24444 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24445 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24446 			return (EFAULT);
24447 		}
24448 		/* Convert the ILP32 uscsi data from the application to LP64 */
24449 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
24450 		break;
24451 	case DDI_MODEL_NONE:
24452 		if (ddi_copyin(data, subcode,
24453 		    sizeof (struct cdrom_subcode), flag)) {
24454 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24455 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24456 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24457 			return (EFAULT);
24458 		}
24459 		break;
24460 	}
24461 #else /* ! _MULTI_DATAMODEL */
24462 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
24463 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24464 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
24465 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24466 		return (EFAULT);
24467 	}
24468 #endif /* _MULTI_DATAMODEL */
24469 
24470 	/*
24471 	 * Since MMC-2 expects max 3 bytes for length, check if the
24472 	 * length input is greater than 3 bytes
24473 	 */
24474 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
24475 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24476 		    "sr_read_all_subcodes: "
24477 		    "cdrom transfer length too large: %d (limit %d)\n",
24478 		    subcode->cdsc_length, 0xFFFFFF);
24479 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24480 		return (EINVAL);
24481 	}
24482 
24483 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
24484 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24485 	bzero(cdb, CDB_GROUP5);
24486 
24487 	if (un->un_f_mmc_cap == TRUE) {
24488 		cdb[0] = (char)SCMD_READ_CD;
24489 		cdb[2] = (char)0xff;
24490 		cdb[3] = (char)0xff;
24491 		cdb[4] = (char)0xff;
24492 		cdb[5] = (char)0xff;
24493 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24494 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24495 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
24496 		cdb[10] = 1;
24497 	} else {
24498 		/*
24499 		 * Note: A vendor specific command (0xDF) is being used her to
24500 		 * request a read of all subcodes.
24501 		 */
24502 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
24503 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
24504 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24505 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24506 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
24507 	}
24508 	com->uscsi_cdb	   = cdb;
24509 	com->uscsi_cdblen  = CDB_GROUP5;
24510 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
24511 	com->uscsi_buflen  = buflen;
24512 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24513 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
24514 	    SD_PATH_STANDARD);
24515 	kmem_free(subcode, sizeof (struct cdrom_subcode));
24516 	kmem_free(com, sizeof (*com));
24517 	return (rval);
24518 }
24519 
24520 
24521 /*
24522  *    Function: sr_read_subchannel()
24523  *
24524  * Description: This routine is the driver entry point for handling CD-ROM
24525  *		ioctl requests to return the Q sub-channel data of the CD
24526  *		current position block. (CDROMSUBCHNL) The data includes the
24527  *		track number, index number, absolute CD-ROM address (LBA or MSF
24528  *		format per the user) , track relative CD-ROM address (LBA or MSF
24529  *		format per the user), control data and audio status.
24530  *
24531  *   Arguments: dev	- the device 'dev_t'
24532  *		data	- pointer to user provided cdrom sub-channel structure
24533  *		flag	- this argument is a pass through to ddi_copyxxx()
24534  *		          directly from the mode argument of ioctl().
24535  *
24536  * Return Code: the code returned by sd_send_scsi_cmd()
24537  *		EFAULT if ddi_copyxxx() fails
24538  *		ENXIO if fail ddi_get_soft_state
24539  *		EINVAL if data pointer is NULL
24540  */
24541 
24542 static int
24543 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
24544 {
24545 	struct sd_lun		*un;
24546 	struct uscsi_cmd	*com;
24547 	struct cdrom_subchnl	subchanel;
24548 	struct cdrom_subchnl	*subchnl = &subchanel;
24549 	char			cdb[CDB_GROUP1];
24550 	caddr_t			buffer;
24551 	int			rval;
24552 
24553 	if (data == NULL) {
24554 		return (EINVAL);
24555 	}
24556 
24557 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24558 	    (un->un_state == SD_STATE_OFFLINE)) {
24559 		return (ENXIO);
24560 	}
24561 
24562 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
24563 		return (EFAULT);
24564 	}
24565 
24566 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
24567 	bzero(cdb, CDB_GROUP1);
24568 	cdb[0] = SCMD_READ_SUBCHANNEL;
24569 	/* Set the MSF bit based on the user requested address format */
24570 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
24571 	/*
24572 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
24573 	 * returned
24574 	 */
24575 	cdb[2] = 0x40;
24576 	/*
24577 	 * Set byte 3 to specify the return data format. A value of 0x01
24578 	 * indicates that the CD-ROM current position should be returned.
24579 	 */
24580 	cdb[3] = 0x01;
24581 	cdb[8] = 0x10;
24582 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24583 	com->uscsi_cdb	   = cdb;
24584 	com->uscsi_cdblen  = CDB_GROUP1;
24585 	com->uscsi_bufaddr = buffer;
24586 	com->uscsi_buflen  = 16;
24587 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24588 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24589 	    SD_PATH_STANDARD);
24590 	if (rval != 0) {
24591 		kmem_free(buffer, 16);
24592 		kmem_free(com, sizeof (*com));
24593 		return (rval);
24594 	}
24595 
24596 	/* Process the returned Q sub-channel data */
24597 	subchnl->cdsc_audiostatus = buffer[1];
24598 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
24599 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
24600 	subchnl->cdsc_trk	= buffer[6];
24601 	subchnl->cdsc_ind	= buffer[7];
24602 	if (subchnl->cdsc_format & CDROM_LBA) {
24603 		subchnl->cdsc_absaddr.lba =
24604 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
24605 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
24606 		subchnl->cdsc_reladdr.lba =
24607 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
24608 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
24609 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
24610 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
24611 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
24612 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
24613 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
24614 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
24615 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
24616 	} else {
24617 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
24618 		subchnl->cdsc_absaddr.msf.second = buffer[10];
24619 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
24620 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
24621 		subchnl->cdsc_reladdr.msf.second = buffer[14];
24622 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
24623 	}
24624 	kmem_free(buffer, 16);
24625 	kmem_free(com, sizeof (*com));
24626 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
24627 	    != 0) {
24628 		return (EFAULT);
24629 	}
24630 	return (rval);
24631 }
24632 
24633 
24634 /*
24635  *    Function: sr_read_tocentry()
24636  *
24637  * Description: This routine is the driver entry point for handling CD-ROM
24638  *		ioctl requests to read from the Table of Contents (TOC)
24639  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
24640  *		fields, the starting address (LBA or MSF format per the user)
24641  *		and the data mode if the user specified track is a data track.
24642  *
24643  *		Note: The READ HEADER (0x44) command used in this routine is
24644  *		obsolete per the SCSI MMC spec but still supported in the
24645  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
24646  *		therefore the command is still implemented in this routine.
24647  *
24648  *   Arguments: dev	- the device 'dev_t'
24649  *		data	- pointer to user provided toc entry structure,
24650  *			  specifying the track # and the address format
24651  *			  (LBA or MSF).
24652  *		flag	- this argument is a pass through to ddi_copyxxx()
24653  *		          directly from the mode argument of ioctl().
24654  *
24655  * Return Code: the code returned by sd_send_scsi_cmd()
24656  *		EFAULT if ddi_copyxxx() fails
24657  *		ENXIO if fail ddi_get_soft_state
24658  *		EINVAL if data pointer is NULL
24659  */
24660 
24661 static int
24662 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
24663 {
24664 	struct sd_lun		*un = NULL;
24665 	struct uscsi_cmd	*com;
24666 	struct cdrom_tocentry	toc_entry;
24667 	struct cdrom_tocentry	*entry = &toc_entry;
24668 	caddr_t			buffer;
24669 	int			rval;
24670 	char			cdb[CDB_GROUP1];
24671 
24672 	if (data == NULL) {
24673 		return (EINVAL);
24674 	}
24675 
24676 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24677 	    (un->un_state == SD_STATE_OFFLINE)) {
24678 		return (ENXIO);
24679 	}
24680 
24681 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
24682 		return (EFAULT);
24683 	}
24684 
24685 	/* Validate the requested track and address format */
24686 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
24687 		return (EINVAL);
24688 	}
24689 
24690 	if (entry->cdte_track == 0) {
24691 		return (EINVAL);
24692 	}
24693 
24694 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
24695 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24696 	bzero(cdb, CDB_GROUP1);
24697 
24698 	cdb[0] = SCMD_READ_TOC;
24699 	/* Set the MSF bit based on the user requested address format  */
24700 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
24701 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
24702 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
24703 	} else {
24704 		cdb[6] = entry->cdte_track;
24705 	}
24706 
24707 	/*
24708 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
24709 	 * (4 byte TOC response header + 8 byte track descriptor)
24710 	 */
24711 	cdb[8] = 12;
24712 	com->uscsi_cdb	   = cdb;
24713 	com->uscsi_cdblen  = CDB_GROUP1;
24714 	com->uscsi_bufaddr = buffer;
24715 	com->uscsi_buflen  = 0x0C;
24716 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
24717 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24718 	    SD_PATH_STANDARD);
24719 	if (rval != 0) {
24720 		kmem_free(buffer, 12);
24721 		kmem_free(com, sizeof (*com));
24722 		return (rval);
24723 	}
24724 
24725 	/* Process the toc entry */
24726 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
24727 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
24728 	if (entry->cdte_format & CDROM_LBA) {
24729 		entry->cdte_addr.lba =
24730 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
24731 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
24732 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
24733 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
24734 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
24735 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
24736 		/*
24737 		 * Send a READ TOC command using the LBA address format to get
24738 		 * the LBA for the track requested so it can be used in the
24739 		 * READ HEADER request
24740 		 *
24741 		 * Note: The MSF bit of the READ HEADER command specifies the
24742 		 * output format. The block address specified in that command
24743 		 * must be in LBA format.
24744 		 */
24745 		cdb[1] = 0;
24746 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24747 		    SD_PATH_STANDARD);
24748 		if (rval != 0) {
24749 			kmem_free(buffer, 12);
24750 			kmem_free(com, sizeof (*com));
24751 			return (rval);
24752 		}
24753 	} else {
24754 		entry->cdte_addr.msf.minute	= buffer[9];
24755 		entry->cdte_addr.msf.second	= buffer[10];
24756 		entry->cdte_addr.msf.frame	= buffer[11];
24757 		/*
24758 		 * Send a READ TOC command using the LBA address format to get
24759 		 * the LBA for the track requested so it can be used in the
24760 		 * READ HEADER request
24761 		 *
24762 		 * Note: The MSF bit of the READ HEADER command specifies the
24763 		 * output format. The block address specified in that command
24764 		 * must be in LBA format.
24765 		 */
24766 		cdb[1] = 0;
24767 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24768 		    SD_PATH_STANDARD);
24769 		if (rval != 0) {
24770 			kmem_free(buffer, 12);
24771 			kmem_free(com, sizeof (*com));
24772 			return (rval);
24773 		}
24774 	}
24775 
24776 	/*
24777 	 * Build and send the READ HEADER command to determine the data mode of
24778 	 * the user specified track.
24779 	 */
24780 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
24781 	    (entry->cdte_track != CDROM_LEADOUT)) {
24782 		bzero(cdb, CDB_GROUP1);
24783 		cdb[0] = SCMD_READ_HEADER;
24784 		cdb[2] = buffer[8];
24785 		cdb[3] = buffer[9];
24786 		cdb[4] = buffer[10];
24787 		cdb[5] = buffer[11];
24788 		cdb[8] = 0x08;
24789 		com->uscsi_buflen = 0x08;
24790 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24791 		    SD_PATH_STANDARD);
24792 		if (rval == 0) {
24793 			entry->cdte_datamode = buffer[0];
24794 		} else {
24795 			/*
24796 			 * READ HEADER command failed, since this is
24797 			 * obsoleted in one spec, its better to return
24798 			 * -1 for an invlid track so that we can still
24799 			 * receive the rest of the TOC data.
24800 			 */
24801 			entry->cdte_datamode = (uchar_t)-1;
24802 		}
24803 	} else {
24804 		entry->cdte_datamode = (uchar_t)-1;
24805 	}
24806 
24807 	kmem_free(buffer, 12);
24808 	kmem_free(com, sizeof (*com));
24809 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
24810 		return (EFAULT);
24811 
24812 	return (rval);
24813 }
24814 
24815 
24816 /*
24817  *    Function: sr_read_tochdr()
24818  *
24819  * Description: This routine is the driver entry point for handling CD-ROM
24820  * 		ioctl requests to read the Table of Contents (TOC) header
24821  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
24822  *		and ending track numbers
24823  *
24824  *   Arguments: dev	- the device 'dev_t'
24825  *		data	- pointer to user provided toc header structure,
24826  *			  specifying the starting and ending track numbers.
24827  *		flag	- this argument is a pass through to ddi_copyxxx()
24828  *			  directly from the mode argument of ioctl().
24829  *
24830  * Return Code: the code returned by sd_send_scsi_cmd()
24831  *		EFAULT if ddi_copyxxx() fails
24832  *		ENXIO if fail ddi_get_soft_state
24833  *		EINVAL if data pointer is NULL
24834  */
24835 
24836 static int
24837 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
24838 {
24839 	struct sd_lun		*un;
24840 	struct uscsi_cmd	*com;
24841 	struct cdrom_tochdr	toc_header;
24842 	struct cdrom_tochdr	*hdr = &toc_header;
24843 	char			cdb[CDB_GROUP1];
24844 	int			rval;
24845 	caddr_t			buffer;
24846 
24847 	if (data == NULL) {
24848 		return (EINVAL);
24849 	}
24850 
24851 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24852 	    (un->un_state == SD_STATE_OFFLINE)) {
24853 		return (ENXIO);
24854 	}
24855 
24856 	buffer = kmem_zalloc(4, KM_SLEEP);
24857 	bzero(cdb, CDB_GROUP1);
24858 	cdb[0] = SCMD_READ_TOC;
24859 	/*
24860 	 * Specifying a track number of 0x00 in the READ TOC command indicates
24861 	 * that the TOC header should be returned
24862 	 */
24863 	cdb[6] = 0x00;
24864 	/*
24865 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
24866 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
24867 	 */
24868 	cdb[8] = 0x04;
24869 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24870 	com->uscsi_cdb	   = cdb;
24871 	com->uscsi_cdblen  = CDB_GROUP1;
24872 	com->uscsi_bufaddr = buffer;
24873 	com->uscsi_buflen  = 0x04;
24874 	com->uscsi_timeout = 300;
24875 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24876 
24877 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24878 	    SD_PATH_STANDARD);
24879 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
24880 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
24881 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
24882 	} else {
24883 		hdr->cdth_trk0 = buffer[2];
24884 		hdr->cdth_trk1 = buffer[3];
24885 	}
24886 	kmem_free(buffer, 4);
24887 	kmem_free(com, sizeof (*com));
24888 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
24889 		return (EFAULT);
24890 	}
24891 	return (rval);
24892 }
24893 
24894 
24895 /*
24896  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
24897  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
24898  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
24899  * digital audio and extended architecture digital audio. These modes are
24900  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
24901  * MMC specs.
24902  *
24903  * In addition to support for the various data formats these routines also
24904  * include support for devices that implement only the direct access READ
24905  * commands (0x08, 0x28), devices that implement the READ_CD commands
24906  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
24907  * READ CDXA commands (0xD8, 0xDB)
24908  */
24909 
24910 /*
24911  *    Function: sr_read_mode1()
24912  *
24913  * Description: This routine is the driver entry point for handling CD-ROM
24914  *		ioctl read mode1 requests (CDROMREADMODE1).
24915  *
24916  *   Arguments: dev	- the device 'dev_t'
24917  *		data	- pointer to user provided cd read structure specifying
24918  *			  the lba buffer address and length.
24919  *		flag	- this argument is a pass through to ddi_copyxxx()
24920  *			  directly from the mode argument of ioctl().
24921  *
24922  * Return Code: the code returned by sd_send_scsi_cmd()
24923  *		EFAULT if ddi_copyxxx() fails
24924  *		ENXIO if fail ddi_get_soft_state
24925  *		EINVAL if data pointer is NULL
24926  */
24927 
24928 static int
24929 sr_read_mode1(dev_t dev, caddr_t data, int flag)
24930 {
24931 	struct sd_lun		*un;
24932 	struct cdrom_read	mode1_struct;
24933 	struct cdrom_read	*mode1 = &mode1_struct;
24934 	int			rval;
24935 #ifdef _MULTI_DATAMODEL
24936 	/* To support ILP32 applications in an LP64 world */
24937 	struct cdrom_read32	cdrom_read32;
24938 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
24939 #endif /* _MULTI_DATAMODEL */
24940 
24941 	if (data == NULL) {
24942 		return (EINVAL);
24943 	}
24944 
24945 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24946 	    (un->un_state == SD_STATE_OFFLINE)) {
24947 		return (ENXIO);
24948 	}
24949 
24950 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
24951 	    "sd_read_mode1: entry: un:0x%p\n", un);
24952 
24953 #ifdef _MULTI_DATAMODEL
24954 	switch (ddi_model_convert_from(flag & FMODELS)) {
24955 	case DDI_MODEL_ILP32:
24956 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
24957 			return (EFAULT);
24958 		}
24959 		/* Convert the ILP32 uscsi data from the application to LP64 */
24960 		cdrom_read32tocdrom_read(cdrd32, mode1);
24961 		break;
24962 	case DDI_MODEL_NONE:
24963 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
24964 			return (EFAULT);
24965 		}
24966 	}
24967 #else /* ! _MULTI_DATAMODEL */
24968 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
24969 		return (EFAULT);
24970 	}
24971 #endif /* _MULTI_DATAMODEL */
24972 
24973 	rval = sd_send_scsi_READ(un, mode1->cdread_bufaddr,
24974 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
24975 
24976 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
24977 	    "sd_read_mode1: exit: un:0x%p\n", un);
24978 
24979 	return (rval);
24980 }
24981 
24982 
24983 /*
24984  *    Function: sr_read_cd_mode2()
24985  *
24986  * Description: This routine is the driver entry point for handling CD-ROM
24987  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
24988  *		support the READ CD (0xBE) command or the 1st generation
24989  *		READ CD (0xD4) command.
24990  *
24991  *   Arguments: dev	- the device 'dev_t'
24992  *		data	- pointer to user provided cd read structure specifying
24993  *			  the lba buffer address and length.
24994  *		flag	- this argument is a pass through to ddi_copyxxx()
24995  *			  directly from the mode argument of ioctl().
24996  *
24997  * Return Code: the code returned by sd_send_scsi_cmd()
24998  *		EFAULT if ddi_copyxxx() fails
24999  *		ENXIO if fail ddi_get_soft_state
25000  *		EINVAL if data pointer is NULL
25001  */
25002 
25003 static int
25004 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
25005 {
25006 	struct sd_lun		*un;
25007 	struct uscsi_cmd	*com;
25008 	struct cdrom_read	mode2_struct;
25009 	struct cdrom_read	*mode2 = &mode2_struct;
25010 	uchar_t			cdb[CDB_GROUP5];
25011 	int			nblocks;
25012 	int			rval;
25013 #ifdef _MULTI_DATAMODEL
25014 	/*  To support ILP32 applications in an LP64 world */
25015 	struct cdrom_read32	cdrom_read32;
25016 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25017 #endif /* _MULTI_DATAMODEL */
25018 
25019 	if (data == NULL) {
25020 		return (EINVAL);
25021 	}
25022 
25023 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25024 	    (un->un_state == SD_STATE_OFFLINE)) {
25025 		return (ENXIO);
25026 	}
25027 
25028 #ifdef _MULTI_DATAMODEL
25029 	switch (ddi_model_convert_from(flag & FMODELS)) {
25030 	case DDI_MODEL_ILP32:
25031 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25032 			return (EFAULT);
25033 		}
25034 		/* Convert the ILP32 uscsi data from the application to LP64 */
25035 		cdrom_read32tocdrom_read(cdrd32, mode2);
25036 		break;
25037 	case DDI_MODEL_NONE:
25038 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25039 			return (EFAULT);
25040 		}
25041 		break;
25042 	}
25043 
25044 #else /* ! _MULTI_DATAMODEL */
25045 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25046 		return (EFAULT);
25047 	}
25048 #endif /* _MULTI_DATAMODEL */
25049 
25050 	bzero(cdb, sizeof (cdb));
25051 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
25052 		/* Read command supported by 1st generation atapi drives */
25053 		cdb[0] = SCMD_READ_CDD4;
25054 	} else {
25055 		/* Universal CD Access Command */
25056 		cdb[0] = SCMD_READ_CD;
25057 	}
25058 
25059 	/*
25060 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
25061 	 */
25062 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
25063 
25064 	/* set the start address */
25065 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
25066 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
25067 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
25068 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
25069 
25070 	/* set the transfer length */
25071 	nblocks = mode2->cdread_buflen / 2336;
25072 	cdb[6] = (uchar_t)(nblocks >> 16);
25073 	cdb[7] = (uchar_t)(nblocks >> 8);
25074 	cdb[8] = (uchar_t)nblocks;
25075 
25076 	/* set the filter bits */
25077 	cdb[9] = CDROM_READ_CD_USERDATA;
25078 
25079 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25080 	com->uscsi_cdb = (caddr_t)cdb;
25081 	com->uscsi_cdblen = sizeof (cdb);
25082 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
25083 	com->uscsi_buflen = mode2->cdread_buflen;
25084 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25085 
25086 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25087 	    SD_PATH_STANDARD);
25088 	kmem_free(com, sizeof (*com));
25089 	return (rval);
25090 }
25091 
25092 
25093 /*
25094  *    Function: sr_read_mode2()
25095  *
25096  * Description: This routine is the driver entry point for handling CD-ROM
25097  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
25098  *		do not support the READ CD (0xBE) command.
25099  *
25100  *   Arguments: dev	- the device 'dev_t'
25101  *		data	- pointer to user provided cd read structure specifying
25102  *			  the lba buffer address and length.
25103  *		flag	- this argument is a pass through to ddi_copyxxx()
25104  *			  directly from the mode argument of ioctl().
25105  *
25106  * Return Code: the code returned by sd_send_scsi_cmd()
25107  *		EFAULT if ddi_copyxxx() fails
25108  *		ENXIO if fail ddi_get_soft_state
25109  *		EINVAL if data pointer is NULL
25110  *		EIO if fail to reset block size
25111  *		EAGAIN if commands are in progress in the driver
25112  */
25113 
25114 static int
25115 sr_read_mode2(dev_t dev, caddr_t data, int flag)
25116 {
25117 	struct sd_lun		*un;
25118 	struct cdrom_read	mode2_struct;
25119 	struct cdrom_read	*mode2 = &mode2_struct;
25120 	int			rval;
25121 	uint32_t		restore_blksize;
25122 	struct uscsi_cmd	*com;
25123 	uchar_t			cdb[CDB_GROUP0];
25124 	int			nblocks;
25125 
25126 #ifdef _MULTI_DATAMODEL
25127 	/* To support ILP32 applications in an LP64 world */
25128 	struct cdrom_read32	cdrom_read32;
25129 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25130 #endif /* _MULTI_DATAMODEL */
25131 
25132 	if (data == NULL) {
25133 		return (EINVAL);
25134 	}
25135 
25136 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25137 	    (un->un_state == SD_STATE_OFFLINE)) {
25138 		return (ENXIO);
25139 	}
25140 
25141 	/*
25142 	 * Because this routine will update the device and driver block size
25143 	 * being used we want to make sure there are no commands in progress.
25144 	 * If commands are in progress the user will have to try again.
25145 	 *
25146 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
25147 	 * in sdioctl to protect commands from sdioctl through to the top of
25148 	 * sd_uscsi_strategy. See sdioctl for details.
25149 	 */
25150 	mutex_enter(SD_MUTEX(un));
25151 	if (un->un_ncmds_in_driver != 1) {
25152 		mutex_exit(SD_MUTEX(un));
25153 		return (EAGAIN);
25154 	}
25155 	mutex_exit(SD_MUTEX(un));
25156 
25157 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25158 	    "sd_read_mode2: entry: un:0x%p\n", un);
25159 
25160 #ifdef _MULTI_DATAMODEL
25161 	switch (ddi_model_convert_from(flag & FMODELS)) {
25162 	case DDI_MODEL_ILP32:
25163 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25164 			return (EFAULT);
25165 		}
25166 		/* Convert the ILP32 uscsi data from the application to LP64 */
25167 		cdrom_read32tocdrom_read(cdrd32, mode2);
25168 		break;
25169 	case DDI_MODEL_NONE:
25170 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25171 			return (EFAULT);
25172 		}
25173 		break;
25174 	}
25175 #else /* ! _MULTI_DATAMODEL */
25176 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
25177 		return (EFAULT);
25178 	}
25179 #endif /* _MULTI_DATAMODEL */
25180 
25181 	/* Store the current target block size for restoration later */
25182 	restore_blksize = un->un_tgt_blocksize;
25183 
25184 	/* Change the device and soft state target block size to 2336 */
25185 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
25186 		rval = EIO;
25187 		goto done;
25188 	}
25189 
25190 
25191 	bzero(cdb, sizeof (cdb));
25192 
25193 	/* set READ operation */
25194 	cdb[0] = SCMD_READ;
25195 
25196 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
25197 	mode2->cdread_lba >>= 2;
25198 
25199 	/* set the start address */
25200 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
25201 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
25202 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
25203 
25204 	/* set the transfer length */
25205 	nblocks = mode2->cdread_buflen / 2336;
25206 	cdb[4] = (uchar_t)nblocks & 0xFF;
25207 
25208 	/* build command */
25209 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25210 	com->uscsi_cdb = (caddr_t)cdb;
25211 	com->uscsi_cdblen = sizeof (cdb);
25212 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
25213 	com->uscsi_buflen = mode2->cdread_buflen;
25214 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25215 
25216 	/*
25217 	 * Issue SCSI command with user space address for read buffer.
25218 	 *
25219 	 * This sends the command through main channel in the driver.
25220 	 *
25221 	 * Since this is accessed via an IOCTL call, we go through the
25222 	 * standard path, so that if the device was powered down, then
25223 	 * it would be 'awakened' to handle the command.
25224 	 */
25225 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25226 	    SD_PATH_STANDARD);
25227 
25228 	kmem_free(com, sizeof (*com));
25229 
25230 	/* Restore the device and soft state target block size */
25231 	if (sr_sector_mode(dev, restore_blksize) != 0) {
25232 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25233 		    "can't do switch back to mode 1\n");
25234 		/*
25235 		 * If sd_send_scsi_READ succeeded we still need to report
25236 		 * an error because we failed to reset the block size
25237 		 */
25238 		if (rval == 0) {
25239 			rval = EIO;
25240 		}
25241 	}
25242 
25243 done:
25244 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25245 	    "sd_read_mode2: exit: un:0x%p\n", un);
25246 
25247 	return (rval);
25248 }
25249 
25250 
25251 /*
25252  *    Function: sr_sector_mode()
25253  *
25254  * Description: This utility function is used by sr_read_mode2 to set the target
25255  *		block size based on the user specified size. This is a legacy
25256  *		implementation based upon a vendor specific mode page
25257  *
25258  *   Arguments: dev	- the device 'dev_t'
25259  *		data	- flag indicating if block size is being set to 2336 or
25260  *			  512.
25261  *
25262  * Return Code: the code returned by sd_send_scsi_cmd()
25263  *		EFAULT if ddi_copyxxx() fails
25264  *		ENXIO if fail ddi_get_soft_state
25265  *		EINVAL if data pointer is NULL
25266  */
25267 
25268 static int
25269 sr_sector_mode(dev_t dev, uint32_t blksize)
25270 {
25271 	struct sd_lun	*un;
25272 	uchar_t		*sense;
25273 	uchar_t		*select;
25274 	int		rval;
25275 
25276 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25277 	    (un->un_state == SD_STATE_OFFLINE)) {
25278 		return (ENXIO);
25279 	}
25280 
25281 	sense = kmem_zalloc(20, KM_SLEEP);
25282 
25283 	/* Note: This is a vendor specific mode page (0x81) */
25284 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, 20, 0x81,
25285 	    SD_PATH_STANDARD)) != 0) {
25286 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25287 		    "sr_sector_mode: Mode Sense failed\n");
25288 		kmem_free(sense, 20);
25289 		return (rval);
25290 	}
25291 	select = kmem_zalloc(20, KM_SLEEP);
25292 	select[3] = 0x08;
25293 	select[10] = ((blksize >> 8) & 0xff);
25294 	select[11] = (blksize & 0xff);
25295 	select[12] = 0x01;
25296 	select[13] = 0x06;
25297 	select[14] = sense[14];
25298 	select[15] = sense[15];
25299 	if (blksize == SD_MODE2_BLKSIZE) {
25300 		select[14] |= 0x01;
25301 	}
25302 
25303 	if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select, 20,
25304 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
25305 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25306 		    "sr_sector_mode: Mode Select failed\n");
25307 	} else {
25308 		/*
25309 		 * Only update the softstate block size if we successfully
25310 		 * changed the device block mode.
25311 		 */
25312 		mutex_enter(SD_MUTEX(un));
25313 		sd_update_block_info(un, blksize, 0);
25314 		mutex_exit(SD_MUTEX(un));
25315 	}
25316 	kmem_free(sense, 20);
25317 	kmem_free(select, 20);
25318 	return (rval);
25319 }
25320 
25321 
25322 /*
25323  *    Function: sr_read_cdda()
25324  *
25325  * Description: This routine is the driver entry point for handling CD-ROM
25326  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
25327  *		the target supports CDDA these requests are handled via a vendor
25328  *		specific command (0xD8) If the target does not support CDDA
25329  *		these requests are handled via the READ CD command (0xBE).
25330  *
25331  *   Arguments: dev	- the device 'dev_t'
25332  *		data	- pointer to user provided CD-DA structure specifying
25333  *			  the track starting address, transfer length, and
25334  *			  subcode options.
25335  *		flag	- this argument is a pass through to ddi_copyxxx()
25336  *			  directly from the mode argument of ioctl().
25337  *
25338  * Return Code: the code returned by sd_send_scsi_cmd()
25339  *		EFAULT if ddi_copyxxx() fails
25340  *		ENXIO if fail ddi_get_soft_state
25341  *		EINVAL if invalid arguments are provided
25342  *		ENOTTY
25343  */
25344 
25345 static int
25346 sr_read_cdda(dev_t dev, caddr_t data, int flag)
25347 {
25348 	struct sd_lun			*un;
25349 	struct uscsi_cmd		*com;
25350 	struct cdrom_cdda		*cdda;
25351 	int				rval;
25352 	size_t				buflen;
25353 	char				cdb[CDB_GROUP5];
25354 
25355 #ifdef _MULTI_DATAMODEL
25356 	/* To support ILP32 applications in an LP64 world */
25357 	struct cdrom_cdda32	cdrom_cdda32;
25358 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
25359 #endif /* _MULTI_DATAMODEL */
25360 
25361 	if (data == NULL) {
25362 		return (EINVAL);
25363 	}
25364 
25365 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25366 		return (ENXIO);
25367 	}
25368 
25369 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
25370 
25371 #ifdef _MULTI_DATAMODEL
25372 	switch (ddi_model_convert_from(flag & FMODELS)) {
25373 	case DDI_MODEL_ILP32:
25374 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
25375 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25376 			    "sr_read_cdda: ddi_copyin Failed\n");
25377 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25378 			return (EFAULT);
25379 		}
25380 		/* Convert the ILP32 uscsi data from the application to LP64 */
25381 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
25382 		break;
25383 	case DDI_MODEL_NONE:
25384 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25385 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25386 			    "sr_read_cdda: ddi_copyin Failed\n");
25387 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25388 			return (EFAULT);
25389 		}
25390 		break;
25391 	}
25392 #else /* ! _MULTI_DATAMODEL */
25393 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25394 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25395 		    "sr_read_cdda: ddi_copyin Failed\n");
25396 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25397 		return (EFAULT);
25398 	}
25399 #endif /* _MULTI_DATAMODEL */
25400 
25401 	/*
25402 	 * Since MMC-2 expects max 3 bytes for length, check if the
25403 	 * length input is greater than 3 bytes
25404 	 */
25405 	if ((cdda->cdda_length & 0xFF000000) != 0) {
25406 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
25407 		    "cdrom transfer length too large: %d (limit %d)\n",
25408 		    cdda->cdda_length, 0xFFFFFF);
25409 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25410 		return (EINVAL);
25411 	}
25412 
25413 	switch (cdda->cdda_subcode) {
25414 	case CDROM_DA_NO_SUBCODE:
25415 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
25416 		break;
25417 	case CDROM_DA_SUBQ:
25418 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
25419 		break;
25420 	case CDROM_DA_ALL_SUBCODE:
25421 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
25422 		break;
25423 	case CDROM_DA_SUBCODE_ONLY:
25424 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
25425 		break;
25426 	default:
25427 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25428 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
25429 		    cdda->cdda_subcode);
25430 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25431 		return (EINVAL);
25432 	}
25433 
25434 	/* Build and send the command */
25435 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25436 	bzero(cdb, CDB_GROUP5);
25437 
25438 	if (un->un_f_cfg_cdda == TRUE) {
25439 		cdb[0] = (char)SCMD_READ_CD;
25440 		cdb[1] = 0x04;
25441 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25442 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25443 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25444 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25445 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25446 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25447 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
25448 		cdb[9] = 0x10;
25449 		switch (cdda->cdda_subcode) {
25450 		case CDROM_DA_NO_SUBCODE :
25451 			cdb[10] = 0x0;
25452 			break;
25453 		case CDROM_DA_SUBQ :
25454 			cdb[10] = 0x2;
25455 			break;
25456 		case CDROM_DA_ALL_SUBCODE :
25457 			cdb[10] = 0x1;
25458 			break;
25459 		case CDROM_DA_SUBCODE_ONLY :
25460 			/* FALLTHROUGH */
25461 		default :
25462 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25463 			kmem_free(com, sizeof (*com));
25464 			return (ENOTTY);
25465 		}
25466 	} else {
25467 		cdb[0] = (char)SCMD_READ_CDDA;
25468 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25469 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25470 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25471 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25472 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
25473 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25474 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25475 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
25476 		cdb[10] = cdda->cdda_subcode;
25477 	}
25478 
25479 	com->uscsi_cdb = cdb;
25480 	com->uscsi_cdblen = CDB_GROUP5;
25481 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
25482 	com->uscsi_buflen = buflen;
25483 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25484 
25485 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25486 	    SD_PATH_STANDARD);
25487 
25488 	kmem_free(cdda, sizeof (struct cdrom_cdda));
25489 	kmem_free(com, sizeof (*com));
25490 	return (rval);
25491 }
25492 
25493 
25494 /*
25495  *    Function: sr_read_cdxa()
25496  *
25497  * Description: This routine is the driver entry point for handling CD-ROM
25498  *		ioctl requests to return CD-XA (Extended Architecture) data.
25499  *		(CDROMCDXA).
25500  *
25501  *   Arguments: dev	- the device 'dev_t'
25502  *		data	- pointer to user provided CD-XA structure specifying
25503  *			  the data starting address, transfer length, and format
25504  *		flag	- this argument is a pass through to ddi_copyxxx()
25505  *			  directly from the mode argument of ioctl().
25506  *
25507  * Return Code: the code returned by sd_send_scsi_cmd()
25508  *		EFAULT if ddi_copyxxx() fails
25509  *		ENXIO if fail ddi_get_soft_state
25510  *		EINVAL if data pointer is NULL
25511  */
25512 
25513 static int
25514 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
25515 {
25516 	struct sd_lun		*un;
25517 	struct uscsi_cmd	*com;
25518 	struct cdrom_cdxa	*cdxa;
25519 	int			rval;
25520 	size_t			buflen;
25521 	char			cdb[CDB_GROUP5];
25522 	uchar_t			read_flags;
25523 
25524 #ifdef _MULTI_DATAMODEL
25525 	/* To support ILP32 applications in an LP64 world */
25526 	struct cdrom_cdxa32		cdrom_cdxa32;
25527 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
25528 #endif /* _MULTI_DATAMODEL */
25529 
25530 	if (data == NULL) {
25531 		return (EINVAL);
25532 	}
25533 
25534 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25535 		return (ENXIO);
25536 	}
25537 
25538 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
25539 
25540 #ifdef _MULTI_DATAMODEL
25541 	switch (ddi_model_convert_from(flag & FMODELS)) {
25542 	case DDI_MODEL_ILP32:
25543 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
25544 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25545 			return (EFAULT);
25546 		}
25547 		/*
25548 		 * Convert the ILP32 uscsi data from the
25549 		 * application to LP64 for internal use.
25550 		 */
25551 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
25552 		break;
25553 	case DDI_MODEL_NONE:
25554 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25555 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25556 			return (EFAULT);
25557 		}
25558 		break;
25559 	}
25560 #else /* ! _MULTI_DATAMODEL */
25561 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25562 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25563 		return (EFAULT);
25564 	}
25565 #endif /* _MULTI_DATAMODEL */
25566 
25567 	/*
25568 	 * Since MMC-2 expects max 3 bytes for length, check if the
25569 	 * length input is greater than 3 bytes
25570 	 */
25571 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
25572 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
25573 		    "cdrom transfer length too large: %d (limit %d)\n",
25574 		    cdxa->cdxa_length, 0xFFFFFF);
25575 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25576 		return (EINVAL);
25577 	}
25578 
25579 	switch (cdxa->cdxa_format) {
25580 	case CDROM_XA_DATA:
25581 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
25582 		read_flags = 0x10;
25583 		break;
25584 	case CDROM_XA_SECTOR_DATA:
25585 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
25586 		read_flags = 0xf8;
25587 		break;
25588 	case CDROM_XA_DATA_W_ERROR:
25589 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
25590 		read_flags = 0xfc;
25591 		break;
25592 	default:
25593 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25594 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
25595 		    cdxa->cdxa_format);
25596 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25597 		return (EINVAL);
25598 	}
25599 
25600 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25601 	bzero(cdb, CDB_GROUP5);
25602 	if (un->un_f_mmc_cap == TRUE) {
25603 		cdb[0] = (char)SCMD_READ_CD;
25604 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25605 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25606 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25607 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25608 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25609 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25610 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
25611 		cdb[9] = (char)read_flags;
25612 	} else {
25613 		/*
25614 		 * Note: A vendor specific command (0xDB) is being used her to
25615 		 * request a read of all subcodes.
25616 		 */
25617 		cdb[0] = (char)SCMD_READ_CDXA;
25618 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25619 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25620 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25621 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25622 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
25623 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25624 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25625 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
25626 		cdb[10] = cdxa->cdxa_format;
25627 	}
25628 	com->uscsi_cdb	   = cdb;
25629 	com->uscsi_cdblen  = CDB_GROUP5;
25630 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
25631 	com->uscsi_buflen  = buflen;
25632 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25633 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25634 	    SD_PATH_STANDARD);
25635 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25636 	kmem_free(com, sizeof (*com));
25637 	return (rval);
25638 }
25639 
25640 
25641 /*
25642  *    Function: sr_eject()
25643  *
25644  * Description: This routine is the driver entry point for handling CD-ROM
25645  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
25646  *
25647  *   Arguments: dev	- the device 'dev_t'
25648  *
25649  * Return Code: the code returned by sd_send_scsi_cmd()
25650  */
25651 
25652 static int
25653 sr_eject(dev_t dev)
25654 {
25655 	struct sd_lun	*un;
25656 	int		rval;
25657 
25658 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25659 	    (un->un_state == SD_STATE_OFFLINE)) {
25660 		return (ENXIO);
25661 	}
25662 
25663 	/*
25664 	 * To prevent race conditions with the eject
25665 	 * command, keep track of an eject command as
25666 	 * it progresses. If we are already handling
25667 	 * an eject command in the driver for the given
25668 	 * unit and another request to eject is received
25669 	 * immediately return EAGAIN so we don't lose
25670 	 * the command if the current eject command fails.
25671 	 */
25672 	mutex_enter(SD_MUTEX(un));
25673 	if (un->un_f_ejecting == TRUE) {
25674 		mutex_exit(SD_MUTEX(un));
25675 		return (EAGAIN);
25676 	}
25677 	un->un_f_ejecting = TRUE;
25678 	mutex_exit(SD_MUTEX(un));
25679 
25680 	if ((rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
25681 	    SD_PATH_STANDARD)) != 0) {
25682 		mutex_enter(SD_MUTEX(un));
25683 		un->un_f_ejecting = FALSE;
25684 		mutex_exit(SD_MUTEX(un));
25685 		return (rval);
25686 	}
25687 
25688 	rval = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_EJECT,
25689 	    SD_PATH_STANDARD);
25690 
25691 	if (rval == 0) {
25692 		mutex_enter(SD_MUTEX(un));
25693 		sr_ejected(un);
25694 		un->un_mediastate = DKIO_EJECTED;
25695 		un->un_f_ejecting = FALSE;
25696 		cv_broadcast(&un->un_state_cv);
25697 		mutex_exit(SD_MUTEX(un));
25698 	} else {
25699 		mutex_enter(SD_MUTEX(un));
25700 		un->un_f_ejecting = FALSE;
25701 		mutex_exit(SD_MUTEX(un));
25702 	}
25703 	return (rval);
25704 }
25705 
25706 
25707 /*
25708  *    Function: sr_ejected()
25709  *
25710  * Description: This routine updates the soft state structure to invalidate the
25711  *		geometry information after the media has been ejected or a
25712  *		media eject has been detected.
25713  *
25714  *   Arguments: un - driver soft state (unit) structure
25715  */
25716 
25717 static void
25718 sr_ejected(struct sd_lun *un)
25719 {
25720 	struct sd_errstats *stp;
25721 
25722 	ASSERT(un != NULL);
25723 	ASSERT(mutex_owned(SD_MUTEX(un)));
25724 
25725 	un->un_f_blockcount_is_valid	= FALSE;
25726 	un->un_f_tgt_blocksize_is_valid	= FALSE;
25727 	mutex_exit(SD_MUTEX(un));
25728 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
25729 	mutex_enter(SD_MUTEX(un));
25730 
25731 	if (un->un_errstats != NULL) {
25732 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
25733 		stp->sd_capacity.value.ui64 = 0;
25734 	}
25735 
25736 	/* remove "capacity-of-device" properties */
25737 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
25738 	    "device-nblocks");
25739 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
25740 	    "device-blksize");
25741 }
25742 
25743 
25744 /*
25745  *    Function: sr_check_wp()
25746  *
25747  * Description: This routine checks the write protection of a removable
25748  *      media disk and hotpluggable devices via the write protect bit of
25749  *      the Mode Page Header device specific field. Some devices choke
25750  *      on unsupported mode page. In order to workaround this issue,
25751  *      this routine has been implemented to use 0x3f mode page(request
25752  *      for all pages) for all device types.
25753  *
25754  *   Arguments: dev		- the device 'dev_t'
25755  *
25756  * Return Code: int indicating if the device is write protected (1) or not (0)
25757  *
25758  *     Context: Kernel thread.
25759  *
25760  */
25761 
25762 static int
25763 sr_check_wp(dev_t dev)
25764 {
25765 	struct sd_lun	*un;
25766 	uchar_t		device_specific;
25767 	uchar_t		*sense;
25768 	int		hdrlen;
25769 	int		rval = FALSE;
25770 
25771 	/*
25772 	 * Note: The return codes for this routine should be reworked to
25773 	 * properly handle the case of a NULL softstate.
25774 	 */
25775 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25776 		return (FALSE);
25777 	}
25778 
25779 	if (un->un_f_cfg_is_atapi == TRUE) {
25780 		/*
25781 		 * The mode page contents are not required; set the allocation
25782 		 * length for the mode page header only
25783 		 */
25784 		hdrlen = MODE_HEADER_LENGTH_GRP2;
25785 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
25786 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense, hdrlen,
25787 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
25788 			goto err_exit;
25789 		device_specific =
25790 		    ((struct mode_header_grp2 *)sense)->device_specific;
25791 	} else {
25792 		hdrlen = MODE_HEADER_LENGTH;
25793 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
25794 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, hdrlen,
25795 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
25796 			goto err_exit;
25797 		device_specific =
25798 		    ((struct mode_header *)sense)->device_specific;
25799 	}
25800 
25801 	/*
25802 	 * Write protect mode sense failed; not all disks
25803 	 * understand this query. Return FALSE assuming that
25804 	 * these devices are not writable.
25805 	 */
25806 	if (device_specific & WRITE_PROTECT) {
25807 		rval = TRUE;
25808 	}
25809 
25810 err_exit:
25811 	kmem_free(sense, hdrlen);
25812 	return (rval);
25813 }
25814 
25815 /*
25816  *    Function: sr_volume_ctrl()
25817  *
25818  * Description: This routine is the driver entry point for handling CD-ROM
25819  *		audio output volume ioctl requests. (CDROMVOLCTRL)
25820  *
25821  *   Arguments: dev	- the device 'dev_t'
25822  *		data	- pointer to user audio volume control structure
25823  *		flag	- this argument is a pass through to ddi_copyxxx()
25824  *			  directly from the mode argument of ioctl().
25825  *
25826  * Return Code: the code returned by sd_send_scsi_cmd()
25827  *		EFAULT if ddi_copyxxx() fails
25828  *		ENXIO if fail ddi_get_soft_state
25829  *		EINVAL if data pointer is NULL
25830  *
25831  */
25832 
25833 static int
25834 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
25835 {
25836 	struct sd_lun		*un;
25837 	struct cdrom_volctrl    volume;
25838 	struct cdrom_volctrl    *vol = &volume;
25839 	uchar_t			*sense_page;
25840 	uchar_t			*select_page;
25841 	uchar_t			*sense;
25842 	uchar_t			*select;
25843 	int			sense_buflen;
25844 	int			select_buflen;
25845 	int			rval;
25846 
25847 	if (data == NULL) {
25848 		return (EINVAL);
25849 	}
25850 
25851 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25852 	    (un->un_state == SD_STATE_OFFLINE)) {
25853 		return (ENXIO);
25854 	}
25855 
25856 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
25857 		return (EFAULT);
25858 	}
25859 
25860 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
25861 		struct mode_header_grp2		*sense_mhp;
25862 		struct mode_header_grp2		*select_mhp;
25863 		int				bd_len;
25864 
25865 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
25866 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
25867 		    MODEPAGE_AUDIO_CTRL_LEN;
25868 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
25869 		select = kmem_zalloc(select_buflen, KM_SLEEP);
25870 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
25871 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
25872 		    SD_PATH_STANDARD)) != 0) {
25873 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25874 			    "sr_volume_ctrl: Mode Sense Failed\n");
25875 			kmem_free(sense, sense_buflen);
25876 			kmem_free(select, select_buflen);
25877 			return (rval);
25878 		}
25879 		sense_mhp = (struct mode_header_grp2 *)sense;
25880 		select_mhp = (struct mode_header_grp2 *)select;
25881 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
25882 		    sense_mhp->bdesc_length_lo;
25883 		if (bd_len > MODE_BLK_DESC_LENGTH) {
25884 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25885 			    "sr_volume_ctrl: Mode Sense returned invalid "
25886 			    "block descriptor length\n");
25887 			kmem_free(sense, sense_buflen);
25888 			kmem_free(select, select_buflen);
25889 			return (EIO);
25890 		}
25891 		sense_page = (uchar_t *)
25892 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
25893 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
25894 		select_mhp->length_msb = 0;
25895 		select_mhp->length_lsb = 0;
25896 		select_mhp->bdesc_length_hi = 0;
25897 		select_mhp->bdesc_length_lo = 0;
25898 	} else {
25899 		struct mode_header		*sense_mhp, *select_mhp;
25900 
25901 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
25902 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
25903 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
25904 		select = kmem_zalloc(select_buflen, KM_SLEEP);
25905 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
25906 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
25907 		    SD_PATH_STANDARD)) != 0) {
25908 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25909 			    "sr_volume_ctrl: Mode Sense Failed\n");
25910 			kmem_free(sense, sense_buflen);
25911 			kmem_free(select, select_buflen);
25912 			return (rval);
25913 		}
25914 		sense_mhp  = (struct mode_header *)sense;
25915 		select_mhp = (struct mode_header *)select;
25916 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
25917 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25918 			    "sr_volume_ctrl: Mode Sense returned invalid "
25919 			    "block descriptor length\n");
25920 			kmem_free(sense, sense_buflen);
25921 			kmem_free(select, select_buflen);
25922 			return (EIO);
25923 		}
25924 		sense_page = (uchar_t *)
25925 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
25926 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
25927 		select_mhp->length = 0;
25928 		select_mhp->bdesc_length = 0;
25929 	}
25930 	/*
25931 	 * Note: An audio control data structure could be created and overlayed
25932 	 * on the following in place of the array indexing method implemented.
25933 	 */
25934 
25935 	/* Build the select data for the user volume data */
25936 	select_page[0] = MODEPAGE_AUDIO_CTRL;
25937 	select_page[1] = 0xE;
25938 	/* Set the immediate bit */
25939 	select_page[2] = 0x04;
25940 	/* Zero out reserved fields */
25941 	select_page[3] = 0x00;
25942 	select_page[4] = 0x00;
25943 	/* Return sense data for fields not to be modified */
25944 	select_page[5] = sense_page[5];
25945 	select_page[6] = sense_page[6];
25946 	select_page[7] = sense_page[7];
25947 	/* Set the user specified volume levels for channel 0 and 1 */
25948 	select_page[8] = 0x01;
25949 	select_page[9] = vol->channel0;
25950 	select_page[10] = 0x02;
25951 	select_page[11] = vol->channel1;
25952 	/* Channel 2 and 3 are currently unsupported so return the sense data */
25953 	select_page[12] = sense_page[12];
25954 	select_page[13] = sense_page[13];
25955 	select_page[14] = sense_page[14];
25956 	select_page[15] = sense_page[15];
25957 
25958 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
25959 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, select,
25960 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
25961 	} else {
25962 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
25963 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
25964 	}
25965 
25966 	kmem_free(sense, sense_buflen);
25967 	kmem_free(select, select_buflen);
25968 	return (rval);
25969 }
25970 
25971 
25972 /*
25973  *    Function: sr_read_sony_session_offset()
25974  *
25975  * Description: This routine is the driver entry point for handling CD-ROM
25976  *		ioctl requests for session offset information. (CDROMREADOFFSET)
25977  *		The address of the first track in the last session of a
25978  *		multi-session CD-ROM is returned
25979  *
25980  *		Note: This routine uses a vendor specific key value in the
25981  *		command control field without implementing any vendor check here
25982  *		or in the ioctl routine.
25983  *
25984  *   Arguments: dev	- the device 'dev_t'
25985  *		data	- pointer to an int to hold the requested address
25986  *		flag	- this argument is a pass through to ddi_copyxxx()
25987  *			  directly from the mode argument of ioctl().
25988  *
25989  * Return Code: the code returned by sd_send_scsi_cmd()
25990  *		EFAULT if ddi_copyxxx() fails
25991  *		ENXIO if fail ddi_get_soft_state
25992  *		EINVAL if data pointer is NULL
25993  */
25994 
25995 static int
25996 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
25997 {
25998 	struct sd_lun		*un;
25999 	struct uscsi_cmd	*com;
26000 	caddr_t			buffer;
26001 	char			cdb[CDB_GROUP1];
26002 	int			session_offset = 0;
26003 	int			rval;
26004 
26005 	if (data == NULL) {
26006 		return (EINVAL);
26007 	}
26008 
26009 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26010 	    (un->un_state == SD_STATE_OFFLINE)) {
26011 		return (ENXIO);
26012 	}
26013 
26014 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
26015 	bzero(cdb, CDB_GROUP1);
26016 	cdb[0] = SCMD_READ_TOC;
26017 	/*
26018 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
26019 	 * (4 byte TOC response header + 8 byte response data)
26020 	 */
26021 	cdb[8] = SONY_SESSION_OFFSET_LEN;
26022 	/* Byte 9 is the control byte. A vendor specific value is used */
26023 	cdb[9] = SONY_SESSION_OFFSET_KEY;
26024 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26025 	com->uscsi_cdb = cdb;
26026 	com->uscsi_cdblen = CDB_GROUP1;
26027 	com->uscsi_bufaddr = buffer;
26028 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
26029 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26030 
26031 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26032 	    SD_PATH_STANDARD);
26033 	if (rval != 0) {
26034 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
26035 		kmem_free(com, sizeof (*com));
26036 		return (rval);
26037 	}
26038 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
26039 		session_offset =
26040 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
26041 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
26042 		/*
26043 		 * Offset returned offset in current lbasize block's. Convert to
26044 		 * 2k block's to return to the user
26045 		 */
26046 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
26047 			session_offset >>= 2;
26048 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
26049 			session_offset >>= 1;
26050 		}
26051 	}
26052 
26053 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
26054 		rval = EFAULT;
26055 	}
26056 
26057 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
26058 	kmem_free(com, sizeof (*com));
26059 	return (rval);
26060 }
26061 
26062 
26063 /*
26064  *    Function: sd_wm_cache_constructor()
26065  *
26066  * Description: Cache Constructor for the wmap cache for the read/modify/write
26067  * 		devices.
26068  *
26069  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
26070  *		un	- sd_lun structure for the device.
26071  *		flag	- the km flags passed to constructor
26072  *
26073  * Return Code: 0 on success.
26074  *		-1 on failure.
26075  */
26076 
26077 /*ARGSUSED*/
26078 static int
26079 sd_wm_cache_constructor(void *wm, void *un, int flags)
26080 {
26081 	bzero(wm, sizeof (struct sd_w_map));
26082 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
26083 	return (0);
26084 }
26085 
26086 
26087 /*
26088  *    Function: sd_wm_cache_destructor()
26089  *
26090  * Description: Cache destructor for the wmap cache for the read/modify/write
26091  * 		devices.
26092  *
26093  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
26094  *		un	- sd_lun structure for the device.
26095  */
26096 /*ARGSUSED*/
26097 static void
26098 sd_wm_cache_destructor(void *wm, void *un)
26099 {
26100 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
26101 }
26102 
26103 
26104 /*
26105  *    Function: sd_range_lock()
26106  *
26107  * Description: Lock the range of blocks specified as parameter to ensure
26108  *		that read, modify write is atomic and no other i/o writes
26109  *		to the same location. The range is specified in terms
26110  *		of start and end blocks. Block numbers are the actual
26111  *		media block numbers and not system.
26112  *
26113  *   Arguments: un	- sd_lun structure for the device.
26114  *		startb - The starting block number
26115  *		endb - The end block number
26116  *		typ - type of i/o - simple/read_modify_write
26117  *
26118  * Return Code: wm  - pointer to the wmap structure.
26119  *
26120  *     Context: This routine can sleep.
26121  */
26122 
26123 static struct sd_w_map *
26124 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
26125 {
26126 	struct sd_w_map *wmp = NULL;
26127 	struct sd_w_map *sl_wmp = NULL;
26128 	struct sd_w_map *tmp_wmp;
26129 	wm_state state = SD_WM_CHK_LIST;
26130 
26131 
26132 	ASSERT(un != NULL);
26133 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26134 
26135 	mutex_enter(SD_MUTEX(un));
26136 
26137 	while (state != SD_WM_DONE) {
26138 
26139 		switch (state) {
26140 		case SD_WM_CHK_LIST:
26141 			/*
26142 			 * This is the starting state. Check the wmap list
26143 			 * to see if the range is currently available.
26144 			 */
26145 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
26146 				/*
26147 				 * If this is a simple write and no rmw
26148 				 * i/o is pending then try to lock the
26149 				 * range as the range should be available.
26150 				 */
26151 				state = SD_WM_LOCK_RANGE;
26152 			} else {
26153 				tmp_wmp = sd_get_range(un, startb, endb);
26154 				if (tmp_wmp != NULL) {
26155 					if ((wmp != NULL) && ONLIST(un, wmp)) {
26156 						/*
26157 						 * Should not keep onlist wmps
26158 						 * while waiting this macro
26159 						 * will also do wmp = NULL;
26160 						 */
26161 						FREE_ONLIST_WMAP(un, wmp);
26162 					}
26163 					/*
26164 					 * sl_wmp is the wmap on which wait
26165 					 * is done, since the tmp_wmp points
26166 					 * to the inuse wmap, set sl_wmp to
26167 					 * tmp_wmp and change the state to sleep
26168 					 */
26169 					sl_wmp = tmp_wmp;
26170 					state = SD_WM_WAIT_MAP;
26171 				} else {
26172 					state = SD_WM_LOCK_RANGE;
26173 				}
26174 
26175 			}
26176 			break;
26177 
26178 		case SD_WM_LOCK_RANGE:
26179 			ASSERT(un->un_wm_cache);
26180 			/*
26181 			 * The range need to be locked, try to get a wmap.
26182 			 * First attempt it with NO_SLEEP, want to avoid a sleep
26183 			 * if possible as we will have to release the sd mutex
26184 			 * if we have to sleep.
26185 			 */
26186 			if (wmp == NULL)
26187 				wmp = kmem_cache_alloc(un->un_wm_cache,
26188 				    KM_NOSLEEP);
26189 			if (wmp == NULL) {
26190 				mutex_exit(SD_MUTEX(un));
26191 				_NOTE(DATA_READABLE_WITHOUT_LOCK
26192 				    (sd_lun::un_wm_cache))
26193 				wmp = kmem_cache_alloc(un->un_wm_cache,
26194 				    KM_SLEEP);
26195 				mutex_enter(SD_MUTEX(un));
26196 				/*
26197 				 * we released the mutex so recheck and go to
26198 				 * check list state.
26199 				 */
26200 				state = SD_WM_CHK_LIST;
26201 			} else {
26202 				/*
26203 				 * We exit out of state machine since we
26204 				 * have the wmap. Do the housekeeping first.
26205 				 * place the wmap on the wmap list if it is not
26206 				 * on it already and then set the state to done.
26207 				 */
26208 				wmp->wm_start = startb;
26209 				wmp->wm_end = endb;
26210 				wmp->wm_flags = typ | SD_WM_BUSY;
26211 				if (typ & SD_WTYPE_RMW) {
26212 					un->un_rmw_count++;
26213 				}
26214 				/*
26215 				 * If not already on the list then link
26216 				 */
26217 				if (!ONLIST(un, wmp)) {
26218 					wmp->wm_next = un->un_wm;
26219 					wmp->wm_prev = NULL;
26220 					if (wmp->wm_next)
26221 						wmp->wm_next->wm_prev = wmp;
26222 					un->un_wm = wmp;
26223 				}
26224 				state = SD_WM_DONE;
26225 			}
26226 			break;
26227 
26228 		case SD_WM_WAIT_MAP:
26229 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
26230 			/*
26231 			 * Wait is done on sl_wmp, which is set in the
26232 			 * check_list state.
26233 			 */
26234 			sl_wmp->wm_wanted_count++;
26235 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
26236 			sl_wmp->wm_wanted_count--;
26237 			/*
26238 			 * We can reuse the memory from the completed sl_wmp
26239 			 * lock range for our new lock, but only if noone is
26240 			 * waiting for it.
26241 			 */
26242 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
26243 			if (sl_wmp->wm_wanted_count == 0) {
26244 				if (wmp != NULL)
26245 					CHK_N_FREEWMP(un, wmp);
26246 				wmp = sl_wmp;
26247 			}
26248 			sl_wmp = NULL;
26249 			/*
26250 			 * After waking up, need to recheck for availability of
26251 			 * range.
26252 			 */
26253 			state = SD_WM_CHK_LIST;
26254 			break;
26255 
26256 		default:
26257 			panic("sd_range_lock: "
26258 			    "Unknown state %d in sd_range_lock", state);
26259 			/*NOTREACHED*/
26260 		} /* switch(state) */
26261 
26262 	} /* while(state != SD_WM_DONE) */
26263 
26264 	mutex_exit(SD_MUTEX(un));
26265 
26266 	ASSERT(wmp != NULL);
26267 
26268 	return (wmp);
26269 }
26270 
26271 
26272 /*
26273  *    Function: sd_get_range()
26274  *
26275  * Description: Find if there any overlapping I/O to this one
26276  *		Returns the write-map of 1st such I/O, NULL otherwise.
26277  *
26278  *   Arguments: un	- sd_lun structure for the device.
26279  *		startb - The starting block number
26280  *		endb - The end block number
26281  *
26282  * Return Code: wm  - pointer to the wmap structure.
26283  */
26284 
26285 static struct sd_w_map *
26286 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
26287 {
26288 	struct sd_w_map *wmp;
26289 
26290 	ASSERT(un != NULL);
26291 
26292 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
26293 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
26294 			continue;
26295 		}
26296 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
26297 			break;
26298 		}
26299 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
26300 			break;
26301 		}
26302 	}
26303 
26304 	return (wmp);
26305 }
26306 
26307 
26308 /*
26309  *    Function: sd_free_inlist_wmap()
26310  *
26311  * Description: Unlink and free a write map struct.
26312  *
26313  *   Arguments: un      - sd_lun structure for the device.
26314  *		wmp	- sd_w_map which needs to be unlinked.
26315  */
26316 
26317 static void
26318 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
26319 {
26320 	ASSERT(un != NULL);
26321 
26322 	if (un->un_wm == wmp) {
26323 		un->un_wm = wmp->wm_next;
26324 	} else {
26325 		wmp->wm_prev->wm_next = wmp->wm_next;
26326 	}
26327 
26328 	if (wmp->wm_next) {
26329 		wmp->wm_next->wm_prev = wmp->wm_prev;
26330 	}
26331 
26332 	wmp->wm_next = wmp->wm_prev = NULL;
26333 
26334 	kmem_cache_free(un->un_wm_cache, wmp);
26335 }
26336 
26337 
26338 /*
26339  *    Function: sd_range_unlock()
26340  *
26341  * Description: Unlock the range locked by wm.
26342  *		Free write map if nobody else is waiting on it.
26343  *
26344  *   Arguments: un      - sd_lun structure for the device.
26345  *              wmp     - sd_w_map which needs to be unlinked.
26346  */
26347 
26348 static void
26349 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
26350 {
26351 	ASSERT(un != NULL);
26352 	ASSERT(wm != NULL);
26353 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26354 
26355 	mutex_enter(SD_MUTEX(un));
26356 
26357 	if (wm->wm_flags & SD_WTYPE_RMW) {
26358 		un->un_rmw_count--;
26359 	}
26360 
26361 	if (wm->wm_wanted_count) {
26362 		wm->wm_flags = 0;
26363 		/*
26364 		 * Broadcast that the wmap is available now.
26365 		 */
26366 		cv_broadcast(&wm->wm_avail);
26367 	} else {
26368 		/*
26369 		 * If no one is waiting on the map, it should be free'ed.
26370 		 */
26371 		sd_free_inlist_wmap(un, wm);
26372 	}
26373 
26374 	mutex_exit(SD_MUTEX(un));
26375 }
26376 
26377 
26378 /*
26379  *    Function: sd_read_modify_write_task
26380  *
26381  * Description: Called from a taskq thread to initiate the write phase of
26382  *		a read-modify-write request.  This is used for targets where
26383  *		un->un_sys_blocksize != un->un_tgt_blocksize.
26384  *
26385  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
26386  *
26387  *     Context: Called under taskq thread context.
26388  */
26389 
26390 static void
26391 sd_read_modify_write_task(void *arg)
26392 {
26393 	struct sd_mapblocksize_info	*bsp;
26394 	struct buf	*bp;
26395 	struct sd_xbuf	*xp;
26396 	struct sd_lun	*un;
26397 
26398 	bp = arg;	/* The bp is given in arg */
26399 	ASSERT(bp != NULL);
26400 
26401 	/* Get the pointer to the layer-private data struct */
26402 	xp = SD_GET_XBUF(bp);
26403 	ASSERT(xp != NULL);
26404 	bsp = xp->xb_private;
26405 	ASSERT(bsp != NULL);
26406 
26407 	un = SD_GET_UN(bp);
26408 	ASSERT(un != NULL);
26409 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26410 
26411 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26412 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
26413 
26414 	/*
26415 	 * This is the write phase of a read-modify-write request, called
26416 	 * under the context of a taskq thread in response to the completion
26417 	 * of the read portion of the rmw request completing under interrupt
26418 	 * context. The write request must be sent from here down the iostart
26419 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
26420 	 * we use the layer index saved in the layer-private data area.
26421 	 */
26422 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
26423 
26424 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26425 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
26426 }
26427 
26428 
26429 /*
26430  *    Function: sddump_do_read_of_rmw()
26431  *
26432  * Description: This routine will be called from sddump, If sddump is called
26433  *		with an I/O which not aligned on device blocksize boundary
26434  *		then the write has to be converted to read-modify-write.
26435  *		Do the read part here in order to keep sddump simple.
26436  *		Note - That the sd_mutex is held across the call to this
26437  *		routine.
26438  *
26439  *   Arguments: un	- sd_lun
26440  *		blkno	- block number in terms of media block size.
26441  *		nblk	- number of blocks.
26442  *		bpp	- pointer to pointer to the buf structure. On return
26443  *			from this function, *bpp points to the valid buffer
26444  *			to which the write has to be done.
26445  *
26446  * Return Code: 0 for success or errno-type return code
26447  */
26448 
26449 static int
26450 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
26451 	struct buf **bpp)
26452 {
26453 	int err;
26454 	int i;
26455 	int rval;
26456 	struct buf *bp;
26457 	struct scsi_pkt *pkt = NULL;
26458 	uint32_t target_blocksize;
26459 
26460 	ASSERT(un != NULL);
26461 	ASSERT(mutex_owned(SD_MUTEX(un)));
26462 
26463 	target_blocksize = un->un_tgt_blocksize;
26464 
26465 	mutex_exit(SD_MUTEX(un));
26466 
26467 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
26468 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
26469 	if (bp == NULL) {
26470 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26471 		    "no resources for dumping; giving up");
26472 		err = ENOMEM;
26473 		goto done;
26474 	}
26475 
26476 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
26477 	    blkno, nblk);
26478 	if (rval != 0) {
26479 		scsi_free_consistent_buf(bp);
26480 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26481 		    "no resources for dumping; giving up");
26482 		err = ENOMEM;
26483 		goto done;
26484 	}
26485 
26486 	pkt->pkt_flags |= FLAG_NOINTR;
26487 
26488 	err = EIO;
26489 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26490 
26491 		/*
26492 		 * Scsi_poll returns 0 (success) if the command completes and
26493 		 * the status block is STATUS_GOOD.  We should only check
26494 		 * errors if this condition is not true.  Even then we should
26495 		 * send our own request sense packet only if we have a check
26496 		 * condition and auto request sense has not been performed by
26497 		 * the hba.
26498 		 */
26499 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
26500 
26501 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
26502 			err = 0;
26503 			break;
26504 		}
26505 
26506 		/*
26507 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
26508 		 * no need to read RQS data.
26509 		 */
26510 		if (pkt->pkt_reason == CMD_DEV_GONE) {
26511 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26512 			    "Device is gone\n");
26513 			break;
26514 		}
26515 
26516 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
26517 			SD_INFO(SD_LOG_DUMP, un,
26518 			    "sddump: read failed with CHECK, try # %d\n", i);
26519 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
26520 				(void) sd_send_polled_RQS(un);
26521 			}
26522 
26523 			continue;
26524 		}
26525 
26526 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
26527 			int reset_retval = 0;
26528 
26529 			SD_INFO(SD_LOG_DUMP, un,
26530 			    "sddump: read failed with BUSY, try # %d\n", i);
26531 
26532 			if (un->un_f_lun_reset_enabled == TRUE) {
26533 				reset_retval = scsi_reset(SD_ADDRESS(un),
26534 				    RESET_LUN);
26535 			}
26536 			if (reset_retval == 0) {
26537 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26538 			}
26539 			(void) sd_send_polled_RQS(un);
26540 
26541 		} else {
26542 			SD_INFO(SD_LOG_DUMP, un,
26543 			    "sddump: read failed with 0x%x, try # %d\n",
26544 			    SD_GET_PKT_STATUS(pkt), i);
26545 			mutex_enter(SD_MUTEX(un));
26546 			sd_reset_target(un, pkt);
26547 			mutex_exit(SD_MUTEX(un));
26548 		}
26549 
26550 		/*
26551 		 * If we are not getting anywhere with lun/target resets,
26552 		 * let's reset the bus.
26553 		 */
26554 		if (i > SD_NDUMP_RETRIES/2) {
26555 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26556 			(void) sd_send_polled_RQS(un);
26557 		}
26558 
26559 	}
26560 	scsi_destroy_pkt(pkt);
26561 
26562 	if (err != 0) {
26563 		scsi_free_consistent_buf(bp);
26564 		*bpp = NULL;
26565 	} else {
26566 		*bpp = bp;
26567 	}
26568 
26569 done:
26570 	mutex_enter(SD_MUTEX(un));
26571 	return (err);
26572 }
26573 
26574 
26575 /*
26576  *    Function: sd_failfast_flushq
26577  *
26578  * Description: Take all bp's on the wait queue that have B_FAILFAST set
26579  *		in b_flags and move them onto the failfast queue, then kick
26580  *		off a thread to return all bp's on the failfast queue to
26581  *		their owners with an error set.
26582  *
26583  *   Arguments: un - pointer to the soft state struct for the instance.
26584  *
26585  *     Context: may execute in interrupt context.
26586  */
26587 
26588 static void
26589 sd_failfast_flushq(struct sd_lun *un)
26590 {
26591 	struct buf *bp;
26592 	struct buf *next_waitq_bp;
26593 	struct buf *prev_waitq_bp = NULL;
26594 
26595 	ASSERT(un != NULL);
26596 	ASSERT(mutex_owned(SD_MUTEX(un)));
26597 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
26598 	ASSERT(un->un_failfast_bp == NULL);
26599 
26600 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
26601 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
26602 
26603 	/*
26604 	 * Check if we should flush all bufs when entering failfast state, or
26605 	 * just those with B_FAILFAST set.
26606 	 */
26607 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
26608 		/*
26609 		 * Move *all* bp's on the wait queue to the failfast flush
26610 		 * queue, including those that do NOT have B_FAILFAST set.
26611 		 */
26612 		if (un->un_failfast_headp == NULL) {
26613 			ASSERT(un->un_failfast_tailp == NULL);
26614 			un->un_failfast_headp = un->un_waitq_headp;
26615 		} else {
26616 			ASSERT(un->un_failfast_tailp != NULL);
26617 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
26618 		}
26619 
26620 		un->un_failfast_tailp = un->un_waitq_tailp;
26621 
26622 		/* update kstat for each bp moved out of the waitq */
26623 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
26624 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
26625 		}
26626 
26627 		/* empty the waitq */
26628 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
26629 
26630 	} else {
26631 		/*
26632 		 * Go thru the wait queue, pick off all entries with
26633 		 * B_FAILFAST set, and move these onto the failfast queue.
26634 		 */
26635 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
26636 			/*
26637 			 * Save the pointer to the next bp on the wait queue,
26638 			 * so we get to it on the next iteration of this loop.
26639 			 */
26640 			next_waitq_bp = bp->av_forw;
26641 
26642 			/*
26643 			 * If this bp from the wait queue does NOT have
26644 			 * B_FAILFAST set, just move on to the next element
26645 			 * in the wait queue. Note, this is the only place
26646 			 * where it is correct to set prev_waitq_bp.
26647 			 */
26648 			if ((bp->b_flags & B_FAILFAST) == 0) {
26649 				prev_waitq_bp = bp;
26650 				continue;
26651 			}
26652 
26653 			/*
26654 			 * Remove the bp from the wait queue.
26655 			 */
26656 			if (bp == un->un_waitq_headp) {
26657 				/* The bp is the first element of the waitq. */
26658 				un->un_waitq_headp = next_waitq_bp;
26659 				if (un->un_waitq_headp == NULL) {
26660 					/* The wait queue is now empty */
26661 					un->un_waitq_tailp = NULL;
26662 				}
26663 			} else {
26664 				/*
26665 				 * The bp is either somewhere in the middle
26666 				 * or at the end of the wait queue.
26667 				 */
26668 				ASSERT(un->un_waitq_headp != NULL);
26669 				ASSERT(prev_waitq_bp != NULL);
26670 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
26671 				    == 0);
26672 				if (bp == un->un_waitq_tailp) {
26673 					/* bp is the last entry on the waitq. */
26674 					ASSERT(next_waitq_bp == NULL);
26675 					un->un_waitq_tailp = prev_waitq_bp;
26676 				}
26677 				prev_waitq_bp->av_forw = next_waitq_bp;
26678 			}
26679 			bp->av_forw = NULL;
26680 
26681 			/*
26682 			 * update kstat since the bp is moved out of
26683 			 * the waitq
26684 			 */
26685 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
26686 
26687 			/*
26688 			 * Now put the bp onto the failfast queue.
26689 			 */
26690 			if (un->un_failfast_headp == NULL) {
26691 				/* failfast queue is currently empty */
26692 				ASSERT(un->un_failfast_tailp == NULL);
26693 				un->un_failfast_headp =
26694 				    un->un_failfast_tailp = bp;
26695 			} else {
26696 				/* Add the bp to the end of the failfast q */
26697 				ASSERT(un->un_failfast_tailp != NULL);
26698 				ASSERT(un->un_failfast_tailp->b_flags &
26699 				    B_FAILFAST);
26700 				un->un_failfast_tailp->av_forw = bp;
26701 				un->un_failfast_tailp = bp;
26702 			}
26703 		}
26704 	}
26705 
26706 	/*
26707 	 * Now return all bp's on the failfast queue to their owners.
26708 	 */
26709 	while ((bp = un->un_failfast_headp) != NULL) {
26710 
26711 		un->un_failfast_headp = bp->av_forw;
26712 		if (un->un_failfast_headp == NULL) {
26713 			un->un_failfast_tailp = NULL;
26714 		}
26715 
26716 		/*
26717 		 * We want to return the bp with a failure error code, but
26718 		 * we do not want a call to sd_start_cmds() to occur here,
26719 		 * so use sd_return_failed_command_no_restart() instead of
26720 		 * sd_return_failed_command().
26721 		 */
26722 		sd_return_failed_command_no_restart(un, bp, EIO);
26723 	}
26724 
26725 	/* Flush the xbuf queues if required. */
26726 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
26727 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
26728 	}
26729 
26730 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
26731 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
26732 }
26733 
26734 
26735 /*
26736  *    Function: sd_failfast_flushq_callback
26737  *
26738  * Description: Return TRUE if the given bp meets the criteria for failfast
26739  *		flushing. Used with ddi_xbuf_flushq(9F).
26740  *
26741  *   Arguments: bp - ptr to buf struct to be examined.
26742  *
26743  *     Context: Any
26744  */
26745 
26746 static int
26747 sd_failfast_flushq_callback(struct buf *bp)
26748 {
26749 	/*
26750 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
26751 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
26752 	 */
26753 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
26754 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
26755 }
26756 
26757 
26758 
26759 /*
26760  * Function: sd_setup_next_xfer
26761  *
26762  * Description: Prepare next I/O operation using DMA_PARTIAL
26763  *
26764  */
26765 
26766 static int
26767 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
26768     struct scsi_pkt *pkt, struct sd_xbuf *xp)
26769 {
26770 	ssize_t	num_blks_not_xfered;
26771 	daddr_t	strt_blk_num;
26772 	ssize_t	bytes_not_xfered;
26773 	int	rval;
26774 
26775 	ASSERT(pkt->pkt_resid == 0);
26776 
26777 	/*
26778 	 * Calculate next block number and amount to be transferred.
26779 	 *
26780 	 * How much data NOT transfered to the HBA yet.
26781 	 */
26782 	bytes_not_xfered = xp->xb_dma_resid;
26783 
26784 	/*
26785 	 * figure how many blocks NOT transfered to the HBA yet.
26786 	 */
26787 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
26788 
26789 	/*
26790 	 * set starting block number to the end of what WAS transfered.
26791 	 */
26792 	strt_blk_num = xp->xb_blkno +
26793 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
26794 
26795 	/*
26796 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
26797 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
26798 	 * the disk mutex here.
26799 	 */
26800 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
26801 	    strt_blk_num, num_blks_not_xfered);
26802 
26803 	if (rval == 0) {
26804 
26805 		/*
26806 		 * Success.
26807 		 *
26808 		 * Adjust things if there are still more blocks to be
26809 		 * transfered.
26810 		 */
26811 		xp->xb_dma_resid = pkt->pkt_resid;
26812 		pkt->pkt_resid = 0;
26813 
26814 		return (1);
26815 	}
26816 
26817 	/*
26818 	 * There's really only one possible return value from
26819 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
26820 	 * returns NULL.
26821 	 */
26822 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
26823 
26824 	bp->b_resid = bp->b_bcount;
26825 	bp->b_flags |= B_ERROR;
26826 
26827 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26828 	    "Error setting up next portion of DMA transfer\n");
26829 
26830 	return (0);
26831 }
26832 
26833 /*
26834  *    Function: sd_panic_for_res_conflict
26835  *
26836  * Description: Call panic with a string formatted with "Reservation Conflict"
26837  *		and a human readable identifier indicating the SD instance
26838  *		that experienced the reservation conflict.
26839  *
26840  *   Arguments: un - pointer to the soft state struct for the instance.
26841  *
26842  *     Context: may execute in interrupt context.
26843  */
26844 
26845 #define	SD_RESV_CONFLICT_FMT_LEN 40
26846 void
26847 sd_panic_for_res_conflict(struct sd_lun *un)
26848 {
26849 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
26850 	char path_str[MAXPATHLEN];
26851 
26852 	(void) snprintf(panic_str, sizeof (panic_str),
26853 	    "Reservation Conflict\nDisk: %s",
26854 	    ddi_pathname(SD_DEVINFO(un), path_str));
26855 
26856 	panic(panic_str);
26857 }
26858 
26859 /*
26860  * Note: The following sd_faultinjection_ioctl( ) routines implement
26861  * driver support for handling fault injection for error analysis
26862  * causing faults in multiple layers of the driver.
26863  *
26864  */
26865 
26866 #ifdef SD_FAULT_INJECTION
26867 static uint_t   sd_fault_injection_on = 0;
26868 
26869 /*
26870  *    Function: sd_faultinjection_ioctl()
26871  *
26872  * Description: This routine is the driver entry point for handling
26873  *              faultinjection ioctls to inject errors into the
26874  *              layer model
26875  *
26876  *   Arguments: cmd	- the ioctl cmd received
26877  *		arg	- the arguments from user and returns
26878  */
26879 
26880 static void
26881 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
26882 
26883 	uint_t i;
26884 	uint_t rval;
26885 
26886 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
26887 
26888 	mutex_enter(SD_MUTEX(un));
26889 
26890 	switch (cmd) {
26891 	case SDIOCRUN:
26892 		/* Allow pushed faults to be injected */
26893 		SD_INFO(SD_LOG_SDTEST, un,
26894 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
26895 
26896 		sd_fault_injection_on = 1;
26897 
26898 		SD_INFO(SD_LOG_IOERR, un,
26899 		    "sd_faultinjection_ioctl: run finished\n");
26900 		break;
26901 
26902 	case SDIOCSTART:
26903 		/* Start Injection Session */
26904 		SD_INFO(SD_LOG_SDTEST, un,
26905 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
26906 
26907 		sd_fault_injection_on = 0;
26908 		un->sd_injection_mask = 0xFFFFFFFF;
26909 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
26910 			un->sd_fi_fifo_pkt[i] = NULL;
26911 			un->sd_fi_fifo_xb[i] = NULL;
26912 			un->sd_fi_fifo_un[i] = NULL;
26913 			un->sd_fi_fifo_arq[i] = NULL;
26914 		}
26915 		un->sd_fi_fifo_start = 0;
26916 		un->sd_fi_fifo_end = 0;
26917 
26918 		mutex_enter(&(un->un_fi_mutex));
26919 		un->sd_fi_log[0] = '\0';
26920 		un->sd_fi_buf_len = 0;
26921 		mutex_exit(&(un->un_fi_mutex));
26922 
26923 		SD_INFO(SD_LOG_IOERR, un,
26924 		    "sd_faultinjection_ioctl: start finished\n");
26925 		break;
26926 
26927 	case SDIOCSTOP:
26928 		/* Stop Injection Session */
26929 		SD_INFO(SD_LOG_SDTEST, un,
26930 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
26931 		sd_fault_injection_on = 0;
26932 		un->sd_injection_mask = 0x0;
26933 
26934 		/* Empty stray or unuseds structs from fifo */
26935 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
26936 			if (un->sd_fi_fifo_pkt[i] != NULL) {
26937 				kmem_free(un->sd_fi_fifo_pkt[i],
26938 				    sizeof (struct sd_fi_pkt));
26939 			}
26940 			if (un->sd_fi_fifo_xb[i] != NULL) {
26941 				kmem_free(un->sd_fi_fifo_xb[i],
26942 				    sizeof (struct sd_fi_xb));
26943 			}
26944 			if (un->sd_fi_fifo_un[i] != NULL) {
26945 				kmem_free(un->sd_fi_fifo_un[i],
26946 				    sizeof (struct sd_fi_un));
26947 			}
26948 			if (un->sd_fi_fifo_arq[i] != NULL) {
26949 				kmem_free(un->sd_fi_fifo_arq[i],
26950 				    sizeof (struct sd_fi_arq));
26951 			}
26952 			un->sd_fi_fifo_pkt[i] = NULL;
26953 			un->sd_fi_fifo_un[i] = NULL;
26954 			un->sd_fi_fifo_xb[i] = NULL;
26955 			un->sd_fi_fifo_arq[i] = NULL;
26956 		}
26957 		un->sd_fi_fifo_start = 0;
26958 		un->sd_fi_fifo_end = 0;
26959 
26960 		SD_INFO(SD_LOG_IOERR, un,
26961 		    "sd_faultinjection_ioctl: stop finished\n");
26962 		break;
26963 
26964 	case SDIOCINSERTPKT:
26965 		/* Store a packet struct to be pushed onto fifo */
26966 		SD_INFO(SD_LOG_SDTEST, un,
26967 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
26968 
26969 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
26970 
26971 		sd_fault_injection_on = 0;
26972 
26973 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
26974 		if (un->sd_fi_fifo_pkt[i] != NULL) {
26975 			kmem_free(un->sd_fi_fifo_pkt[i],
26976 			    sizeof (struct sd_fi_pkt));
26977 		}
26978 		if (arg != NULL) {
26979 			un->sd_fi_fifo_pkt[i] =
26980 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
26981 			if (un->sd_fi_fifo_pkt[i] == NULL) {
26982 				/* Alloc failed don't store anything */
26983 				break;
26984 			}
26985 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
26986 			    sizeof (struct sd_fi_pkt), 0);
26987 			if (rval == -1) {
26988 				kmem_free(un->sd_fi_fifo_pkt[i],
26989 				    sizeof (struct sd_fi_pkt));
26990 				un->sd_fi_fifo_pkt[i] = NULL;
26991 			}
26992 		} else {
26993 			SD_INFO(SD_LOG_IOERR, un,
26994 			    "sd_faultinjection_ioctl: pkt null\n");
26995 		}
26996 		break;
26997 
26998 	case SDIOCINSERTXB:
26999 		/* Store a xb struct to be pushed onto fifo */
27000 		SD_INFO(SD_LOG_SDTEST, un,
27001 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
27002 
27003 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27004 
27005 		sd_fault_injection_on = 0;
27006 
27007 		if (un->sd_fi_fifo_xb[i] != NULL) {
27008 			kmem_free(un->sd_fi_fifo_xb[i],
27009 			    sizeof (struct sd_fi_xb));
27010 			un->sd_fi_fifo_xb[i] = NULL;
27011 		}
27012 		if (arg != NULL) {
27013 			un->sd_fi_fifo_xb[i] =
27014 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
27015 			if (un->sd_fi_fifo_xb[i] == NULL) {
27016 				/* Alloc failed don't store anything */
27017 				break;
27018 			}
27019 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
27020 			    sizeof (struct sd_fi_xb), 0);
27021 
27022 			if (rval == -1) {
27023 				kmem_free(un->sd_fi_fifo_xb[i],
27024 				    sizeof (struct sd_fi_xb));
27025 				un->sd_fi_fifo_xb[i] = NULL;
27026 			}
27027 		} else {
27028 			SD_INFO(SD_LOG_IOERR, un,
27029 			    "sd_faultinjection_ioctl: xb null\n");
27030 		}
27031 		break;
27032 
27033 	case SDIOCINSERTUN:
27034 		/* Store a un struct to be pushed onto fifo */
27035 		SD_INFO(SD_LOG_SDTEST, un,
27036 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
27037 
27038 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27039 
27040 		sd_fault_injection_on = 0;
27041 
27042 		if (un->sd_fi_fifo_un[i] != NULL) {
27043 			kmem_free(un->sd_fi_fifo_un[i],
27044 			    sizeof (struct sd_fi_un));
27045 			un->sd_fi_fifo_un[i] = NULL;
27046 		}
27047 		if (arg != NULL) {
27048 			un->sd_fi_fifo_un[i] =
27049 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
27050 			if (un->sd_fi_fifo_un[i] == NULL) {
27051 				/* Alloc failed don't store anything */
27052 				break;
27053 			}
27054 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
27055 			    sizeof (struct sd_fi_un), 0);
27056 			if (rval == -1) {
27057 				kmem_free(un->sd_fi_fifo_un[i],
27058 				    sizeof (struct sd_fi_un));
27059 				un->sd_fi_fifo_un[i] = NULL;
27060 			}
27061 
27062 		} else {
27063 			SD_INFO(SD_LOG_IOERR, un,
27064 			    "sd_faultinjection_ioctl: un null\n");
27065 		}
27066 
27067 		break;
27068 
27069 	case SDIOCINSERTARQ:
27070 		/* Store a arq struct to be pushed onto fifo */
27071 		SD_INFO(SD_LOG_SDTEST, un,
27072 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
27073 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27074 
27075 		sd_fault_injection_on = 0;
27076 
27077 		if (un->sd_fi_fifo_arq[i] != NULL) {
27078 			kmem_free(un->sd_fi_fifo_arq[i],
27079 			    sizeof (struct sd_fi_arq));
27080 			un->sd_fi_fifo_arq[i] = NULL;
27081 		}
27082 		if (arg != NULL) {
27083 			un->sd_fi_fifo_arq[i] =
27084 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
27085 			if (un->sd_fi_fifo_arq[i] == NULL) {
27086 				/* Alloc failed don't store anything */
27087 				break;
27088 			}
27089 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
27090 			    sizeof (struct sd_fi_arq), 0);
27091 			if (rval == -1) {
27092 				kmem_free(un->sd_fi_fifo_arq[i],
27093 				    sizeof (struct sd_fi_arq));
27094 				un->sd_fi_fifo_arq[i] = NULL;
27095 			}
27096 
27097 		} else {
27098 			SD_INFO(SD_LOG_IOERR, un,
27099 			    "sd_faultinjection_ioctl: arq null\n");
27100 		}
27101 
27102 		break;
27103 
27104 	case SDIOCPUSH:
27105 		/* Push stored xb, pkt, un, and arq onto fifo */
27106 		sd_fault_injection_on = 0;
27107 
27108 		if (arg != NULL) {
27109 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
27110 			if (rval != -1 &&
27111 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
27112 				un->sd_fi_fifo_end += i;
27113 			}
27114 		} else {
27115 			SD_INFO(SD_LOG_IOERR, un,
27116 			    "sd_faultinjection_ioctl: push arg null\n");
27117 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
27118 				un->sd_fi_fifo_end++;
27119 			}
27120 		}
27121 		SD_INFO(SD_LOG_IOERR, un,
27122 		    "sd_faultinjection_ioctl: push to end=%d\n",
27123 		    un->sd_fi_fifo_end);
27124 		break;
27125 
27126 	case SDIOCRETRIEVE:
27127 		/* Return buffer of log from Injection session */
27128 		SD_INFO(SD_LOG_SDTEST, un,
27129 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
27130 
27131 		sd_fault_injection_on = 0;
27132 
27133 		mutex_enter(&(un->un_fi_mutex));
27134 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
27135 		    un->sd_fi_buf_len+1, 0);
27136 		mutex_exit(&(un->un_fi_mutex));
27137 
27138 		if (rval == -1) {
27139 			/*
27140 			 * arg is possibly invalid setting
27141 			 * it to NULL for return
27142 			 */
27143 			arg = NULL;
27144 		}
27145 		break;
27146 	}
27147 
27148 	mutex_exit(SD_MUTEX(un));
27149 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
27150 			    " exit\n");
27151 }
27152 
27153 
27154 /*
27155  *    Function: sd_injection_log()
27156  *
27157  * Description: This routine adds buff to the already existing injection log
27158  *              for retrieval via faultinjection_ioctl for use in fault
27159  *              detection and recovery
27160  *
27161  *   Arguments: buf - the string to add to the log
27162  */
27163 
27164 static void
27165 sd_injection_log(char *buf, struct sd_lun *un)
27166 {
27167 	uint_t len;
27168 
27169 	ASSERT(un != NULL);
27170 	ASSERT(buf != NULL);
27171 
27172 	mutex_enter(&(un->un_fi_mutex));
27173 
27174 	len = min(strlen(buf), 255);
27175 	/* Add logged value to Injection log to be returned later */
27176 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
27177 		uint_t	offset = strlen((char *)un->sd_fi_log);
27178 		char *destp = (char *)un->sd_fi_log + offset;
27179 		int i;
27180 		for (i = 0; i < len; i++) {
27181 			*destp++ = *buf++;
27182 		}
27183 		un->sd_fi_buf_len += len;
27184 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
27185 	}
27186 
27187 	mutex_exit(&(un->un_fi_mutex));
27188 }
27189 
27190 
27191 /*
27192  *    Function: sd_faultinjection()
27193  *
27194  * Description: This routine takes the pkt and changes its
27195  *		content based on error injection scenerio.
27196  *
27197  *   Arguments: pktp	- packet to be changed
27198  */
27199 
27200 static void
27201 sd_faultinjection(struct scsi_pkt *pktp)
27202 {
27203 	uint_t i;
27204 	struct sd_fi_pkt *fi_pkt;
27205 	struct sd_fi_xb *fi_xb;
27206 	struct sd_fi_un *fi_un;
27207 	struct sd_fi_arq *fi_arq;
27208 	struct buf *bp;
27209 	struct sd_xbuf *xb;
27210 	struct sd_lun *un;
27211 
27212 	ASSERT(pktp != NULL);
27213 
27214 	/* pull bp xb and un from pktp */
27215 	bp = (struct buf *)pktp->pkt_private;
27216 	xb = SD_GET_XBUF(bp);
27217 	un = SD_GET_UN(bp);
27218 
27219 	ASSERT(un != NULL);
27220 
27221 	mutex_enter(SD_MUTEX(un));
27222 
27223 	SD_TRACE(SD_LOG_SDTEST, un,
27224 	    "sd_faultinjection: entry Injection from sdintr\n");
27225 
27226 	/* if injection is off return */
27227 	if (sd_fault_injection_on == 0 ||
27228 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
27229 		mutex_exit(SD_MUTEX(un));
27230 		return;
27231 	}
27232 
27233 
27234 	/* take next set off fifo */
27235 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
27236 
27237 	fi_pkt = un->sd_fi_fifo_pkt[i];
27238 	fi_xb = un->sd_fi_fifo_xb[i];
27239 	fi_un = un->sd_fi_fifo_un[i];
27240 	fi_arq = un->sd_fi_fifo_arq[i];
27241 
27242 
27243 	/* set variables accordingly */
27244 	/* set pkt if it was on fifo */
27245 	if (fi_pkt != NULL) {
27246 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
27247 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
27248 		SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
27249 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
27250 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
27251 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
27252 
27253 	}
27254 
27255 	/* set xb if it was on fifo */
27256 	if (fi_xb != NULL) {
27257 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
27258 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
27259 		SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
27260 		SD_CONDSET(xb, xb, xb_victim_retry_count,
27261 		    "xb_victim_retry_count");
27262 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
27263 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
27264 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
27265 
27266 		/* copy in block data from sense */
27267 		if (fi_xb->xb_sense_data[0] != -1) {
27268 			bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
27269 			    SENSE_LENGTH);
27270 		}
27271 
27272 		/* copy in extended sense codes */
27273 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_code,
27274 		    "es_code");
27275 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_key,
27276 		    "es_key");
27277 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_add_code,
27278 		    "es_add_code");
27279 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb,
27280 		    es_qual_code, "es_qual_code");
27281 	}
27282 
27283 	/* set un if it was on fifo */
27284 	if (fi_un != NULL) {
27285 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
27286 		SD_CONDSET(un, un, un_ctype, "un_ctype");
27287 		SD_CONDSET(un, un, un_reset_retry_count,
27288 		    "un_reset_retry_count");
27289 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
27290 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
27291 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
27292 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
27293 		    "un_f_allow_bus_device_reset");
27294 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
27295 
27296 	}
27297 
27298 	/* copy in auto request sense if it was on fifo */
27299 	if (fi_arq != NULL) {
27300 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
27301 	}
27302 
27303 	/* free structs */
27304 	if (un->sd_fi_fifo_pkt[i] != NULL) {
27305 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
27306 	}
27307 	if (un->sd_fi_fifo_xb[i] != NULL) {
27308 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
27309 	}
27310 	if (un->sd_fi_fifo_un[i] != NULL) {
27311 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
27312 	}
27313 	if (un->sd_fi_fifo_arq[i] != NULL) {
27314 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
27315 	}
27316 
27317 	/*
27318 	 * kmem_free does not gurantee to set to NULL
27319 	 * since we uses these to determine if we set
27320 	 * values or not lets confirm they are always
27321 	 * NULL after free
27322 	 */
27323 	un->sd_fi_fifo_pkt[i] = NULL;
27324 	un->sd_fi_fifo_un[i] = NULL;
27325 	un->sd_fi_fifo_xb[i] = NULL;
27326 	un->sd_fi_fifo_arq[i] = NULL;
27327 
27328 	un->sd_fi_fifo_start++;
27329 
27330 	mutex_exit(SD_MUTEX(un));
27331 
27332 	SD_TRACE(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
27333 }
27334 
27335 #endif /* SD_FAULT_INJECTION */
27336 
27337 /*
27338  * This routine is invoked in sd_unit_attach(). Before calling it, the
27339  * properties in conf file should be processed already, and "hotpluggable"
27340  * property was processed also.
27341  *
27342  * The sd driver distinguishes 3 different type of devices: removable media,
27343  * non-removable media, and hotpluggable. Below the differences are defined:
27344  *
27345  * 1. Device ID
27346  *
27347  *     The device ID of a device is used to identify this device. Refer to
27348  *     ddi_devid_register(9F).
27349  *
27350  *     For a non-removable media disk device which can provide 0x80 or 0x83
27351  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
27352  *     device ID is created to identify this device. For other non-removable
27353  *     media devices, a default device ID is created only if this device has
27354  *     at least 2 alter cylinders. Otherwise, this device has no devid.
27355  *
27356  *     -------------------------------------------------------
27357  *     removable media   hotpluggable  | Can Have Device ID
27358  *     -------------------------------------------------------
27359  *         false             false     |     Yes
27360  *         false             true      |     Yes
27361  *         true                x       |     No
27362  *     ------------------------------------------------------
27363  *
27364  *
27365  * 2. SCSI group 4 commands
27366  *
27367  *     In SCSI specs, only some commands in group 4 command set can use
27368  *     8-byte addresses that can be used to access >2TB storage spaces.
27369  *     Other commands have no such capability. Without supporting group4,
27370  *     it is impossible to make full use of storage spaces of a disk with
27371  *     capacity larger than 2TB.
27372  *
27373  *     -----------------------------------------------
27374  *     removable media   hotpluggable   LP64  |  Group
27375  *     -----------------------------------------------
27376  *           false          false       false |   1
27377  *           false          false       true  |   4
27378  *           false          true        false |   1
27379  *           false          true        true  |   4
27380  *           true             x           x   |   5
27381  *     -----------------------------------------------
27382  *
27383  *
27384  * 3. Check for VTOC Label
27385  *
27386  *     If a direct-access disk has no EFI label, sd will check if it has a
27387  *     valid VTOC label. Now, sd also does that check for removable media
27388  *     and hotpluggable devices.
27389  *
27390  *     --------------------------------------------------------------
27391  *     Direct-Access   removable media    hotpluggable |  Check Label
27392  *     -------------------------------------------------------------
27393  *         false          false           false        |   No
27394  *         false          false           true         |   No
27395  *         false          true            false        |   Yes
27396  *         false          true            true         |   Yes
27397  *         true            x                x          |   Yes
27398  *     --------------------------------------------------------------
27399  *
27400  *
27401  * 4. Building default VTOC label
27402  *
27403  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
27404  *     If those devices have no valid VTOC label, sd(7d) will attempt to
27405  *     create default VTOC for them. Currently sd creates default VTOC label
27406  *     for all devices on x86 platform (VTOC_16), but only for removable
27407  *     media devices on SPARC (VTOC_8).
27408  *
27409  *     -----------------------------------------------------------
27410  *       removable media hotpluggable platform   |   Default Label
27411  *     -----------------------------------------------------------
27412  *             false          false    sparc     |     No
27413  *             false          true      x86      |     Yes
27414  *             false          true     sparc     |     Yes
27415  *             true             x        x       |     Yes
27416  *     ----------------------------------------------------------
27417  *
27418  *
27419  * 5. Supported blocksizes of target devices
27420  *
27421  *     Sd supports non-512-byte blocksize for removable media devices only.
27422  *     For other devices, only 512-byte blocksize is supported. This may be
27423  *     changed in near future because some RAID devices require non-512-byte
27424  *     blocksize
27425  *
27426  *     -----------------------------------------------------------
27427  *     removable media    hotpluggable    | non-512-byte blocksize
27428  *     -----------------------------------------------------------
27429  *           false          false         |   No
27430  *           false          true          |   No
27431  *           true             x           |   Yes
27432  *     -----------------------------------------------------------
27433  *
27434  *
27435  * 6. Automatic mount & unmount
27436  *
27437  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
27438  *     if a device is removable media device. It return 1 for removable media
27439  *     devices, and 0 for others.
27440  *
27441  *     The automatic mounting subsystem should distinguish between the types
27442  *     of devices and apply automounting policies to each.
27443  *
27444  *
27445  * 7. fdisk partition management
27446  *
27447  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
27448  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
27449  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
27450  *     fdisk partitions on both x86 and SPARC platform.
27451  *
27452  *     -----------------------------------------------------------
27453  *       platform   removable media  USB/1394  |  fdisk supported
27454  *     -----------------------------------------------------------
27455  *        x86         X               X        |       true
27456  *     ------------------------------------------------------------
27457  *        sparc       X               X        |       false
27458  *     ------------------------------------------------------------
27459  *
27460  *
27461  * 8. MBOOT/MBR
27462  *
27463  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
27464  *     read/write mboot for removable media devices on sparc platform.
27465  *
27466  *     -----------------------------------------------------------
27467  *       platform   removable media  USB/1394  |  mboot supported
27468  *     -----------------------------------------------------------
27469  *        x86         X               X        |       true
27470  *     ------------------------------------------------------------
27471  *        sparc      false           false     |       false
27472  *        sparc      false           true      |       true
27473  *        sparc      true            false     |       true
27474  *        sparc      true            true      |       true
27475  *     ------------------------------------------------------------
27476  *
27477  *
27478  * 9.  error handling during opening device
27479  *
27480  *     If failed to open a disk device, an errno is returned. For some kinds
27481  *     of errors, different errno is returned depending on if this device is
27482  *     a removable media device. This brings USB/1394 hard disks in line with
27483  *     expected hard disk behavior. It is not expected that this breaks any
27484  *     application.
27485  *
27486  *     ------------------------------------------------------
27487  *       removable media    hotpluggable   |  errno
27488  *     ------------------------------------------------------
27489  *             false          false        |   EIO
27490  *             false          true         |   EIO
27491  *             true             x          |   ENXIO
27492  *     ------------------------------------------------------
27493  *
27494  *
27495  * 11. ioctls: DKIOCEJECT, CDROMEJECT
27496  *
27497  *     These IOCTLs are applicable only to removable media devices.
27498  *
27499  *     -----------------------------------------------------------
27500  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
27501  *     -----------------------------------------------------------
27502  *             false          false        |     No
27503  *             false          true         |     No
27504  *             true            x           |     Yes
27505  *     -----------------------------------------------------------
27506  *
27507  *
27508  * 12. Kstats for partitions
27509  *
27510  *     sd creates partition kstat for non-removable media devices. USB and
27511  *     Firewire hard disks now have partition kstats
27512  *
27513  *      ------------------------------------------------------
27514  *       removable media    hotpluggable   |   kstat
27515  *      ------------------------------------------------------
27516  *             false          false        |    Yes
27517  *             false          true         |    Yes
27518  *             true             x          |    No
27519  *       ------------------------------------------------------
27520  *
27521  *
27522  * 13. Removable media & hotpluggable properties
27523  *
27524  *     Sd driver creates a "removable-media" property for removable media
27525  *     devices. Parent nexus drivers create a "hotpluggable" property if
27526  *     it supports hotplugging.
27527  *
27528  *     ---------------------------------------------------------------------
27529  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
27530  *     ---------------------------------------------------------------------
27531  *       false            false       |    No                   No
27532  *       false            true        |    No                   Yes
27533  *       true             false       |    Yes                  No
27534  *       true             true        |    Yes                  Yes
27535  *     ---------------------------------------------------------------------
27536  *
27537  *
27538  * 14. Power Management
27539  *
27540  *     sd only power manages removable media devices or devices that support
27541  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
27542  *
27543  *     A parent nexus that supports hotplugging can also set "pm-capable"
27544  *     if the disk can be power managed.
27545  *
27546  *     ------------------------------------------------------------
27547  *       removable media hotpluggable pm-capable  |   power manage
27548  *     ------------------------------------------------------------
27549  *             false          false     false     |     No
27550  *             false          false     true      |     Yes
27551  *             false          true      false     |     No
27552  *             false          true      true      |     Yes
27553  *             true             x        x        |     Yes
27554  *     ------------------------------------------------------------
27555  *
27556  *      USB and firewire hard disks can now be power managed independently
27557  *      of the framebuffer
27558  *
27559  *
27560  * 15. Support for USB disks with capacity larger than 1TB
27561  *
27562  *     Currently, sd doesn't permit a fixed disk device with capacity
27563  *     larger than 1TB to be used in a 32-bit operating system environment.
27564  *     However, sd doesn't do that for removable media devices. Instead, it
27565  *     assumes that removable media devices cannot have a capacity larger
27566  *     than 1TB. Therefore, using those devices on 32-bit system is partially
27567  *     supported, which can cause some unexpected results.
27568  *
27569  *     ---------------------------------------------------------------------
27570  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
27571  *     ---------------------------------------------------------------------
27572  *             false          false  |   true         |     no
27573  *             false          true   |   true         |     no
27574  *             true           false  |   true         |     Yes
27575  *             true           true   |   true         |     Yes
27576  *     ---------------------------------------------------------------------
27577  *
27578  *
27579  * 16. Check write-protection at open time
27580  *
27581  *     When a removable media device is being opened for writing without NDELAY
27582  *     flag, sd will check if this device is writable. If attempting to open
27583  *     without NDELAY flag a write-protected device, this operation will abort.
27584  *
27585  *     ------------------------------------------------------------
27586  *       removable media    USB/1394   |   WP Check
27587  *     ------------------------------------------------------------
27588  *             false          false    |     No
27589  *             false          true     |     No
27590  *             true           false    |     Yes
27591  *             true           true     |     Yes
27592  *     ------------------------------------------------------------
27593  *
27594  *
27595  * 17. syslog when corrupted VTOC is encountered
27596  *
27597  *      Currently, if an invalid VTOC is encountered, sd only print syslog
27598  *      for fixed SCSI disks.
27599  *     ------------------------------------------------------------
27600  *       removable media    USB/1394   |   print syslog
27601  *     ------------------------------------------------------------
27602  *             false          false    |     Yes
27603  *             false          true     |     No
27604  *             true           false    |     No
27605  *             true           true     |     No
27606  *     ------------------------------------------------------------
27607  */
27608 static void
27609 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
27610 {
27611 	int	pm_capable_prop;
27612 
27613 	ASSERT(un->un_sd);
27614 	ASSERT(un->un_sd->sd_inq);
27615 
27616 	/*
27617 	 * Enable SYNC CACHE support for all devices.
27618 	 */
27619 	un->un_f_sync_cache_supported = TRUE;
27620 
27621 	if (un->un_sd->sd_inq->inq_rmb) {
27622 		/*
27623 		 * The media of this device is removable. And for this kind
27624 		 * of devices, it is possible to change medium after opening
27625 		 * devices. Thus we should support this operation.
27626 		 */
27627 		un->un_f_has_removable_media = TRUE;
27628 
27629 		/*
27630 		 * support non-512-byte blocksize of removable media devices
27631 		 */
27632 		un->un_f_non_devbsize_supported = TRUE;
27633 
27634 		/*
27635 		 * Assume that all removable media devices support DOOR_LOCK
27636 		 */
27637 		un->un_f_doorlock_supported = TRUE;
27638 
27639 		/*
27640 		 * For a removable media device, it is possible to be opened
27641 		 * with NDELAY flag when there is no media in drive, in this
27642 		 * case we don't care if device is writable. But if without
27643 		 * NDELAY flag, we need to check if media is write-protected.
27644 		 */
27645 		un->un_f_chk_wp_open = TRUE;
27646 
27647 		/*
27648 		 * need to start a SCSI watch thread to monitor media state,
27649 		 * when media is being inserted or ejected, notify syseventd.
27650 		 */
27651 		un->un_f_monitor_media_state = TRUE;
27652 
27653 		/*
27654 		 * Some devices don't support START_STOP_UNIT command.
27655 		 * Therefore, we'd better check if a device supports it
27656 		 * before sending it.
27657 		 */
27658 		un->un_f_check_start_stop = TRUE;
27659 
27660 		/*
27661 		 * support eject media ioctl:
27662 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
27663 		 */
27664 		un->un_f_eject_media_supported = TRUE;
27665 
27666 		/*
27667 		 * Because many removable-media devices don't support
27668 		 * LOG_SENSE, we couldn't use this command to check if
27669 		 * a removable media device support power-management.
27670 		 * We assume that they support power-management via
27671 		 * START_STOP_UNIT command and can be spun up and down
27672 		 * without limitations.
27673 		 */
27674 		un->un_f_pm_supported = TRUE;
27675 
27676 		/*
27677 		 * Need to create a zero length (Boolean) property
27678 		 * removable-media for the removable media devices.
27679 		 * Note that the return value of the property is not being
27680 		 * checked, since if unable to create the property
27681 		 * then do not want the attach to fail altogether. Consistent
27682 		 * with other property creation in attach.
27683 		 */
27684 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
27685 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
27686 
27687 	} else {
27688 		/*
27689 		 * create device ID for device
27690 		 */
27691 		un->un_f_devid_supported = TRUE;
27692 
27693 		/*
27694 		 * Spin up non-removable-media devices once it is attached
27695 		 */
27696 		un->un_f_attach_spinup = TRUE;
27697 
27698 		/*
27699 		 * According to SCSI specification, Sense data has two kinds of
27700 		 * format: fixed format, and descriptor format. At present, we
27701 		 * don't support descriptor format sense data for removable
27702 		 * media.
27703 		 */
27704 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
27705 			un->un_f_descr_format_supported = TRUE;
27706 		}
27707 
27708 		/*
27709 		 * kstats are created only for non-removable media devices.
27710 		 *
27711 		 * Set this in sd.conf to 0 in order to disable kstats.  The
27712 		 * default is 1, so they are enabled by default.
27713 		 */
27714 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
27715 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
27716 		    "enable-partition-kstats", 1));
27717 
27718 		/*
27719 		 * Check if HBA has set the "pm-capable" property.
27720 		 * If "pm-capable" exists and is non-zero then we can
27721 		 * power manage the device without checking the start/stop
27722 		 * cycle count log sense page.
27723 		 *
27724 		 * If "pm-capable" exists and is SD_PM_CAPABLE_FALSE (0)
27725 		 * then we should not power manage the device.
27726 		 *
27727 		 * If "pm-capable" doesn't exist then pm_capable_prop will
27728 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
27729 		 * sd will check the start/stop cycle count log sense page
27730 		 * and power manage the device if the cycle count limit has
27731 		 * not been exceeded.
27732 		 */
27733 		pm_capable_prop = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
27734 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
27735 		if (pm_capable_prop == SD_PM_CAPABLE_UNDEFINED) {
27736 			un->un_f_log_sense_supported = TRUE;
27737 		} else {
27738 			/*
27739 			 * pm-capable property exists.
27740 			 *
27741 			 * Convert "TRUE" values for pm_capable_prop to
27742 			 * SD_PM_CAPABLE_TRUE (1) to make it easier to check
27743 			 * later. "TRUE" values are any values except
27744 			 * SD_PM_CAPABLE_FALSE (0) and
27745 			 * SD_PM_CAPABLE_UNDEFINED (-1)
27746 			 */
27747 			if (pm_capable_prop == SD_PM_CAPABLE_FALSE) {
27748 				un->un_f_log_sense_supported = FALSE;
27749 			} else {
27750 				un->un_f_pm_supported = TRUE;
27751 			}
27752 
27753 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
27754 			    "sd_unit_attach: un:0x%p pm-capable "
27755 			    "property set to %d.\n", un, un->un_f_pm_supported);
27756 		}
27757 	}
27758 
27759 	if (un->un_f_is_hotpluggable) {
27760 
27761 		/*
27762 		 * Have to watch hotpluggable devices as well, since
27763 		 * that's the only way for userland applications to
27764 		 * detect hot removal while device is busy/mounted.
27765 		 */
27766 		un->un_f_monitor_media_state = TRUE;
27767 
27768 		un->un_f_check_start_stop = TRUE;
27769 
27770 	}
27771 }
27772 
27773 /*
27774  * sd_tg_rdwr:
27775  * Provides rdwr access for cmlb via sd_tgops. The start_block is
27776  * in sys block size, req_length in bytes.
27777  *
27778  */
27779 static int
27780 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
27781     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
27782 {
27783 	struct sd_lun *un;
27784 	int path_flag = (int)(uintptr_t)tg_cookie;
27785 	char *dkl = NULL;
27786 	diskaddr_t real_addr = start_block;
27787 	diskaddr_t first_byte, end_block;
27788 
27789 	size_t	buffer_size = reqlength;
27790 	int rval;
27791 	diskaddr_t	cap;
27792 	uint32_t	lbasize;
27793 
27794 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
27795 	if (un == NULL)
27796 		return (ENXIO);
27797 
27798 	if (cmd != TG_READ && cmd != TG_WRITE)
27799 		return (EINVAL);
27800 
27801 	mutex_enter(SD_MUTEX(un));
27802 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
27803 		mutex_exit(SD_MUTEX(un));
27804 		rval = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
27805 		    &lbasize, path_flag);
27806 		if (rval != 0)
27807 			return (rval);
27808 		mutex_enter(SD_MUTEX(un));
27809 		sd_update_block_info(un, lbasize, cap);
27810 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
27811 			mutex_exit(SD_MUTEX(un));
27812 			return (EIO);
27813 		}
27814 	}
27815 
27816 	if (NOT_DEVBSIZE(un)) {
27817 		/*
27818 		 * sys_blocksize != tgt_blocksize, need to re-adjust
27819 		 * blkno and save the index to beginning of dk_label
27820 		 */
27821 		first_byte  = SD_SYSBLOCKS2BYTES(un, start_block);
27822 		real_addr = first_byte / un->un_tgt_blocksize;
27823 
27824 		end_block = (first_byte + reqlength +
27825 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
27826 
27827 		/* round up buffer size to multiple of target block size */
27828 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
27829 
27830 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
27831 		    "label_addr: 0x%x allocation size: 0x%x\n",
27832 		    real_addr, buffer_size);
27833 
27834 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
27835 		    (reqlength % un->un_tgt_blocksize) != 0)
27836 			/* the request is not aligned */
27837 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
27838 	}
27839 
27840 	/*
27841 	 * The MMC standard allows READ CAPACITY to be
27842 	 * inaccurate by a bounded amount (in the interest of
27843 	 * response latency).  As a result, failed READs are
27844 	 * commonplace (due to the reading of metadata and not
27845 	 * data). Depending on the per-Vendor/drive Sense data,
27846 	 * the failed READ can cause many (unnecessary) retries.
27847 	 */
27848 
27849 	if (ISCD(un) && (cmd == TG_READ) &&
27850 	    (un->un_f_blockcount_is_valid == TRUE) &&
27851 	    ((start_block == (un->un_blockcount - 1))||
27852 	    (start_block == (un->un_blockcount - 2)))) {
27853 			path_flag = SD_PATH_DIRECT_PRIORITY;
27854 	}
27855 
27856 	mutex_exit(SD_MUTEX(un));
27857 	if (cmd == TG_READ) {
27858 		rval = sd_send_scsi_READ(un, (dkl != NULL)? dkl: bufaddr,
27859 		    buffer_size, real_addr, path_flag);
27860 		if (dkl != NULL)
27861 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
27862 			    real_addr), bufaddr, reqlength);
27863 	} else {
27864 		if (dkl) {
27865 			rval = sd_send_scsi_READ(un, dkl, buffer_size,
27866 			    real_addr, path_flag);
27867 			if (rval) {
27868 				kmem_free(dkl, buffer_size);
27869 				return (rval);
27870 			}
27871 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
27872 			    real_addr), reqlength);
27873 		}
27874 		rval = sd_send_scsi_WRITE(un, (dkl != NULL)? dkl: bufaddr,
27875 		    buffer_size, real_addr, path_flag);
27876 	}
27877 
27878 	if (dkl != NULL)
27879 		kmem_free(dkl, buffer_size);
27880 
27881 	return (rval);
27882 }
27883 
27884 
27885 static int
27886 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
27887 {
27888 
27889 	struct sd_lun *un;
27890 	diskaddr_t	cap;
27891 	uint32_t	lbasize;
27892 	int		path_flag = (int)(uintptr_t)tg_cookie;
27893 	int		ret = 0;
27894 
27895 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
27896 	if (un == NULL)
27897 		return (ENXIO);
27898 
27899 	switch (cmd) {
27900 	case TG_GETPHYGEOM:
27901 	case TG_GETVIRTGEOM:
27902 	case TG_GETCAPACITY:
27903 	case  TG_GETBLOCKSIZE:
27904 		mutex_enter(SD_MUTEX(un));
27905 
27906 		if ((un->un_f_blockcount_is_valid == TRUE) &&
27907 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
27908 			cap = un->un_blockcount;
27909 			lbasize = un->un_tgt_blocksize;
27910 			mutex_exit(SD_MUTEX(un));
27911 		} else {
27912 			mutex_exit(SD_MUTEX(un));
27913 			ret = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
27914 			    &lbasize, path_flag);
27915 			if (ret != 0)
27916 				return (ret);
27917 			mutex_enter(SD_MUTEX(un));
27918 			sd_update_block_info(un, lbasize, cap);
27919 			if ((un->un_f_blockcount_is_valid == FALSE) ||
27920 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
27921 				mutex_exit(SD_MUTEX(un));
27922 				return (EIO);
27923 			}
27924 			mutex_exit(SD_MUTEX(un));
27925 		}
27926 
27927 		if (cmd == TG_GETCAPACITY) {
27928 			*(diskaddr_t *)arg = cap;
27929 			return (0);
27930 		}
27931 
27932 		if (cmd == TG_GETBLOCKSIZE) {
27933 			*(uint32_t *)arg = lbasize;
27934 			return (0);
27935 		}
27936 
27937 		if (cmd == TG_GETPHYGEOM)
27938 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
27939 			    cap, lbasize, path_flag);
27940 		else
27941 			/* TG_GETVIRTGEOM */
27942 			ret = sd_get_virtual_geometry(un,
27943 			    (cmlb_geom_t *)arg, cap, lbasize);
27944 
27945 		return (ret);
27946 
27947 	case TG_GETATTR:
27948 		mutex_enter(SD_MUTEX(un));
27949 		((tg_attribute_t *)arg)->media_is_writable =
27950 		    un->un_f_mmc_writable_media;
27951 		mutex_exit(SD_MUTEX(un));
27952 		return (0);
27953 	default:
27954 		return (ENOTTY);
27955 
27956 	}
27957 
27958 }
27959