xref: /titanic_52/usr/src/uts/common/io/scsi/targets/sd.c (revision 96fe64c14df04df4a6c9e96d67ff739fb75a5464)
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 };
517 
518 
519 
520 #if (defined(SD_PROP_TST))
521 
522 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
523 #define	SD_TST_THROTTLE_VAL	16
524 #define	SD_TST_NOTREADY_VAL	12
525 #define	SD_TST_BUSY_VAL		60
526 #define	SD_TST_RST_RETRY_VAL	36
527 #define	SD_TST_RSV_REL_TIME	60
528 
529 static sd_tunables tst_properties = {
530 	SD_TST_THROTTLE_VAL,
531 	SD_TST_CTYPE_VAL,
532 	SD_TST_NOTREADY_VAL,
533 	SD_TST_BUSY_VAL,
534 	SD_TST_RST_RETRY_VAL,
535 	SD_TST_RSV_REL_TIME,
536 	0,
537 	0,
538 	0
539 };
540 #endif
541 
542 /* This is similar to the ANSI toupper implementation */
543 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
544 
545 /*
546  * Static Driver Configuration Table
547  *
548  * This is the table of disks which need throttle adjustment (or, perhaps
549  * something else as defined by the flags at a future time.)  device_id
550  * is a string consisting of concatenated vid (vendor), pid (product/model)
551  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
552  * the parts of the string are as defined by the sizes in the scsi_inquiry
553  * structure.  Device type is searched as far as the device_id string is
554  * defined.  Flags defines which values are to be set in the driver from the
555  * properties list.
556  *
557  * Entries below which begin and end with a "*" are a special case.
558  * These do not have a specific vendor, and the string which follows
559  * can appear anywhere in the 16 byte PID portion of the inquiry data.
560  *
561  * Entries below which begin and end with a " " (blank) are a special
562  * case. The comparison function will treat multiple consecutive blanks
563  * as equivalent to a single blank. For example, this causes a
564  * sd_disk_table entry of " NEC CDROM " to match a device's id string
565  * of  "NEC       CDROM".
566  *
567  * Note: The MD21 controller type has been obsoleted.
568  *	 ST318202F is a Legacy device
569  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
570  *	 made with an FC connection. The entries here are a legacy.
571  */
572 static sd_disk_config_t sd_disk_table[] = {
573 #if defined(__fibre) || defined(__i386) || defined(__amd64)
574 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
575 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
576 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
577 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
578 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
579 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
580 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
581 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
582 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
583 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
584 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
585 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
586 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
587 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
588 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
589 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
590 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
591 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
592 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
593 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
594 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
595 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
596 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
597 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
598 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
599 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
600 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
601 	{ "IBM     1724-100",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
602 	{ "IBM     1726-2xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
603 	{ "IBM     1726-22x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
604 	{ "IBM     1726-4xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
605 	{ "IBM     1726-42x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
606 	{ "IBM     1726-3xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
607 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
608 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
609 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
610 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
611 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
612 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
613 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
614 	{ "IBM     1814",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
615 	{ "IBM     1814-200",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
616 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
617 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
618 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
619 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
620 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
621 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
622 	{ "Fujitsu SX300",	SD_CONF_BSET_THROTTLE,  &lsi_oem_properties },
623 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
624 	{ "SUN     T3", SD_CONF_BSET_THROTTLE |
625 			SD_CONF_BSET_BSY_RETRY_COUNT|
626 			SD_CONF_BSET_RST_RETRIES|
627 			SD_CONF_BSET_RSV_REL_TIME,
628 		&purple_properties },
629 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
630 		SD_CONF_BSET_BSY_RETRY_COUNT|
631 		SD_CONF_BSET_RST_RETRIES|
632 		SD_CONF_BSET_RSV_REL_TIME|
633 		SD_CONF_BSET_MIN_THROTTLE|
634 		SD_CONF_BSET_DISKSORT_DISABLED,
635 		&sve_properties },
636 	{ "SUN     T4", SD_CONF_BSET_THROTTLE |
637 			SD_CONF_BSET_BSY_RETRY_COUNT|
638 			SD_CONF_BSET_RST_RETRIES|
639 			SD_CONF_BSET_RSV_REL_TIME,
640 		&purple_properties },
641 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
642 		SD_CONF_BSET_LUN_RESET_ENABLED,
643 		&maserati_properties },
644 	{ "SUN     SE6920", SD_CONF_BSET_THROTTLE |
645 		SD_CONF_BSET_NRR_COUNT|
646 		SD_CONF_BSET_BSY_RETRY_COUNT|
647 		SD_CONF_BSET_RST_RETRIES|
648 		SD_CONF_BSET_MIN_THROTTLE|
649 		SD_CONF_BSET_DISKSORT_DISABLED|
650 		SD_CONF_BSET_LUN_RESET_ENABLED,
651 		&pirus_properties },
652 	{ "SUN     SE6940", SD_CONF_BSET_THROTTLE |
653 		SD_CONF_BSET_NRR_COUNT|
654 		SD_CONF_BSET_BSY_RETRY_COUNT|
655 		SD_CONF_BSET_RST_RETRIES|
656 		SD_CONF_BSET_MIN_THROTTLE|
657 		SD_CONF_BSET_DISKSORT_DISABLED|
658 		SD_CONF_BSET_LUN_RESET_ENABLED,
659 		&pirus_properties },
660 	{ "SUN     StorageTek 6920", SD_CONF_BSET_THROTTLE |
661 		SD_CONF_BSET_NRR_COUNT|
662 		SD_CONF_BSET_BSY_RETRY_COUNT|
663 		SD_CONF_BSET_RST_RETRIES|
664 		SD_CONF_BSET_MIN_THROTTLE|
665 		SD_CONF_BSET_DISKSORT_DISABLED|
666 		SD_CONF_BSET_LUN_RESET_ENABLED,
667 		&pirus_properties },
668 	{ "SUN     StorageTek 6940", SD_CONF_BSET_THROTTLE |
669 		SD_CONF_BSET_NRR_COUNT|
670 		SD_CONF_BSET_BSY_RETRY_COUNT|
671 		SD_CONF_BSET_RST_RETRIES|
672 		SD_CONF_BSET_MIN_THROTTLE|
673 		SD_CONF_BSET_DISKSORT_DISABLED|
674 		SD_CONF_BSET_LUN_RESET_ENABLED,
675 		&pirus_properties },
676 	{ "SUN     PSX1000", SD_CONF_BSET_THROTTLE |
677 		SD_CONF_BSET_NRR_COUNT|
678 		SD_CONF_BSET_BSY_RETRY_COUNT|
679 		SD_CONF_BSET_RST_RETRIES|
680 		SD_CONF_BSET_MIN_THROTTLE|
681 		SD_CONF_BSET_DISKSORT_DISABLED|
682 		SD_CONF_BSET_LUN_RESET_ENABLED,
683 		&pirus_properties },
684 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
685 		SD_CONF_BSET_NRR_COUNT|
686 		SD_CONF_BSET_BSY_RETRY_COUNT|
687 		SD_CONF_BSET_RST_RETRIES|
688 		SD_CONF_BSET_MIN_THROTTLE|
689 		SD_CONF_BSET_DISKSORT_DISABLED|
690 		SD_CONF_BSET_LUN_RESET_ENABLED,
691 		&pirus_properties },
692 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
693 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
694 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
695 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
696 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
697 #endif /* fibre or NON-sparc platforms */
698 #if ((defined(__sparc) && !defined(__fibre)) ||\
699 	(defined(__i386) || defined(__amd64)))
700 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
701 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
702 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
703 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
704 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
705 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
706 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
707 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
708 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
709 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
710 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
711 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
712 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
713 	    &symbios_properties },
714 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
715 	    &lsi_properties_scsi },
716 #if defined(__i386) || defined(__amd64)
717 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
718 				    | SD_CONF_BSET_READSUB_BCD
719 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
720 				    | SD_CONF_BSET_NO_READ_HEADER
721 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
722 
723 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
724 				    | SD_CONF_BSET_READSUB_BCD
725 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
726 				    | SD_CONF_BSET_NO_READ_HEADER
727 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
728 #endif /* __i386 || __amd64 */
729 #endif /* sparc NON-fibre or NON-sparc platforms */
730 
731 #if (defined(SD_PROP_TST))
732 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
733 				| SD_CONF_BSET_CTYPE
734 				| SD_CONF_BSET_NRR_COUNT
735 				| SD_CONF_BSET_FAB_DEVID
736 				| SD_CONF_BSET_NOCACHE
737 				| SD_CONF_BSET_BSY_RETRY_COUNT
738 				| SD_CONF_BSET_PLAYMSF_BCD
739 				| SD_CONF_BSET_READSUB_BCD
740 				| SD_CONF_BSET_READ_TOC_TRK_BCD
741 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
742 				| SD_CONF_BSET_NO_READ_HEADER
743 				| SD_CONF_BSET_READ_CD_XD4
744 				| SD_CONF_BSET_RST_RETRIES
745 				| SD_CONF_BSET_RSV_REL_TIME
746 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
747 #endif
748 };
749 
750 static const int sd_disk_table_size =
751 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
752 
753 
754 
755 #define	SD_INTERCONNECT_PARALLEL	0
756 #define	SD_INTERCONNECT_FABRIC		1
757 #define	SD_INTERCONNECT_FIBRE		2
758 #define	SD_INTERCONNECT_SSA		3
759 #define	SD_INTERCONNECT_SATA		4
760 #define	SD_IS_PARALLEL_SCSI(un)		\
761 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
762 #define	SD_IS_SERIAL(un)		\
763 	((un)->un_interconnect_type == SD_INTERCONNECT_SATA)
764 
765 /*
766  * Definitions used by device id registration routines
767  */
768 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
769 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
770 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
771 
772 static kmutex_t sd_sense_mutex = {0};
773 
774 /*
775  * Macros for updates of the driver state
776  */
777 #define	New_state(un, s)        \
778 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
779 #define	Restore_state(un)	\
780 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
781 
782 static struct sd_cdbinfo sd_cdbtab[] = {
783 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
784 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
785 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
786 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
787 };
788 
789 /*
790  * Specifies the number of seconds that must have elapsed since the last
791  * cmd. has completed for a device to be declared idle to the PM framework.
792  */
793 static int sd_pm_idletime = 1;
794 
795 /*
796  * Internal function prototypes
797  */
798 
799 #if (defined(__fibre))
800 /*
801  * These #defines are to avoid namespace collisions that occur because this
802  * code is currently used to compile two separate driver modules: sd and ssd.
803  * All function names need to be treated this way (even if declared static)
804  * in order to allow the debugger to resolve the names properly.
805  * It is anticipated that in the near future the ssd module will be obsoleted,
806  * at which time this ugliness should go away.
807  */
808 #define	sd_log_trace			ssd_log_trace
809 #define	sd_log_info			ssd_log_info
810 #define	sd_log_err			ssd_log_err
811 #define	sdprobe				ssdprobe
812 #define	sdinfo				ssdinfo
813 #define	sd_prop_op			ssd_prop_op
814 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
815 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
816 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
817 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
818 #define	sd_scsi_target_lun_init		ssd_scsi_target_lun_init
819 #define	sd_scsi_target_lun_fini		ssd_scsi_target_lun_fini
820 #define	sd_scsi_get_target_lun_count	ssd_scsi_get_target_lun_count
821 #define	sd_scsi_update_lun_on_target	ssd_scsi_update_lun_on_target
822 #define	sd_spin_up_unit			ssd_spin_up_unit
823 #define	sd_enable_descr_sense		ssd_enable_descr_sense
824 #define	sd_reenable_dsense_task		ssd_reenable_dsense_task
825 #define	sd_set_mmc_caps			ssd_set_mmc_caps
826 #define	sd_read_unit_properties		ssd_read_unit_properties
827 #define	sd_process_sdconf_file		ssd_process_sdconf_file
828 #define	sd_process_sdconf_table		ssd_process_sdconf_table
829 #define	sd_sdconf_id_match		ssd_sdconf_id_match
830 #define	sd_blank_cmp			ssd_blank_cmp
831 #define	sd_chk_vers1_data		ssd_chk_vers1_data
832 #define	sd_set_vers1_properties		ssd_set_vers1_properties
833 
834 #define	sd_get_physical_geometry	ssd_get_physical_geometry
835 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
836 #define	sd_update_block_info		ssd_update_block_info
837 #define	sd_register_devid		ssd_register_devid
838 #define	sd_get_devid			ssd_get_devid
839 #define	sd_create_devid			ssd_create_devid
840 #define	sd_write_deviceid		ssd_write_deviceid
841 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
842 #define	sd_setup_pm			ssd_setup_pm
843 #define	sd_create_pm_components		ssd_create_pm_components
844 #define	sd_ddi_suspend			ssd_ddi_suspend
845 #define	sd_ddi_pm_suspend		ssd_ddi_pm_suspend
846 #define	sd_ddi_resume			ssd_ddi_resume
847 #define	sd_ddi_pm_resume		ssd_ddi_pm_resume
848 #define	sdpower				ssdpower
849 #define	sdattach			ssdattach
850 #define	sddetach			ssddetach
851 #define	sd_unit_attach			ssd_unit_attach
852 #define	sd_unit_detach			ssd_unit_detach
853 #define	sd_set_unit_attributes		ssd_set_unit_attributes
854 #define	sd_create_errstats		ssd_create_errstats
855 #define	sd_set_errstats			ssd_set_errstats
856 #define	sd_set_pstats			ssd_set_pstats
857 #define	sddump				ssddump
858 #define	sd_scsi_poll			ssd_scsi_poll
859 #define	sd_send_polled_RQS		ssd_send_polled_RQS
860 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
861 #define	sd_init_event_callbacks		ssd_init_event_callbacks
862 #define	sd_event_callback		ssd_event_callback
863 #define	sd_cache_control		ssd_cache_control
864 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
865 #define	sd_make_device			ssd_make_device
866 #define	sdopen				ssdopen
867 #define	sdclose				ssdclose
868 #define	sd_ready_and_valid		ssd_ready_and_valid
869 #define	sdmin				ssdmin
870 #define	sdread				ssdread
871 #define	sdwrite				ssdwrite
872 #define	sdaread				ssdaread
873 #define	sdawrite			ssdawrite
874 #define	sdstrategy			ssdstrategy
875 #define	sdioctl				ssdioctl
876 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
877 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
878 #define	sd_checksum_iostart		ssd_checksum_iostart
879 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
880 #define	sd_pm_iostart			ssd_pm_iostart
881 #define	sd_core_iostart			ssd_core_iostart
882 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
883 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
884 #define	sd_checksum_iodone		ssd_checksum_iodone
885 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
886 #define	sd_pm_iodone			ssd_pm_iodone
887 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
888 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
889 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
890 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
891 #define	sd_buf_iodone			ssd_buf_iodone
892 #define	sd_uscsi_strategy		ssd_uscsi_strategy
893 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
894 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
895 #define	sd_uscsi_iodone			ssd_uscsi_iodone
896 #define	sd_xbuf_strategy		ssd_xbuf_strategy
897 #define	sd_xbuf_init			ssd_xbuf_init
898 #define	sd_pm_entry			ssd_pm_entry
899 #define	sd_pm_exit			ssd_pm_exit
900 
901 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
902 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
903 
904 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
905 #define	sdintr				ssdintr
906 #define	sd_start_cmds			ssd_start_cmds
907 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
908 #define	sd_bioclone_alloc		ssd_bioclone_alloc
909 #define	sd_bioclone_free		ssd_bioclone_free
910 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
911 #define	sd_shadow_buf_free		ssd_shadow_buf_free
912 #define	sd_print_transport_rejected_message	\
913 					ssd_print_transport_rejected_message
914 #define	sd_retry_command		ssd_retry_command
915 #define	sd_set_retry_bp			ssd_set_retry_bp
916 #define	sd_send_request_sense_command	ssd_send_request_sense_command
917 #define	sd_start_retry_command		ssd_start_retry_command
918 #define	sd_start_direct_priority_command	\
919 					ssd_start_direct_priority_command
920 #define	sd_return_failed_command	ssd_return_failed_command
921 #define	sd_return_failed_command_no_restart	\
922 					ssd_return_failed_command_no_restart
923 #define	sd_return_command		ssd_return_command
924 #define	sd_sync_with_callback		ssd_sync_with_callback
925 #define	sdrunout			ssdrunout
926 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
927 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
928 #define	sd_reduce_throttle		ssd_reduce_throttle
929 #define	sd_restore_throttle		ssd_restore_throttle
930 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
931 #define	sd_init_cdb_limits		ssd_init_cdb_limits
932 #define	sd_pkt_status_good		ssd_pkt_status_good
933 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
934 #define	sd_pkt_status_busy		ssd_pkt_status_busy
935 #define	sd_pkt_status_reservation_conflict	\
936 					ssd_pkt_status_reservation_conflict
937 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
938 #define	sd_handle_request_sense		ssd_handle_request_sense
939 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
940 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
941 #define	sd_validate_sense_data		ssd_validate_sense_data
942 #define	sd_decode_sense			ssd_decode_sense
943 #define	sd_print_sense_msg		ssd_print_sense_msg
944 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
945 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
946 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
947 #define	sd_sense_key_medium_or_hardware_error	\
948 					ssd_sense_key_medium_or_hardware_error
949 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
950 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
951 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
952 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
953 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
954 #define	sd_sense_key_default		ssd_sense_key_default
955 #define	sd_print_retry_msg		ssd_print_retry_msg
956 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
957 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
958 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
959 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
960 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
961 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
962 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
963 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
964 #define	sd_pkt_reason_default		ssd_pkt_reason_default
965 #define	sd_reset_target			ssd_reset_target
966 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
967 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
968 #define	sd_taskq_create			ssd_taskq_create
969 #define	sd_taskq_delete			ssd_taskq_delete
970 #define	sd_media_change_task		ssd_media_change_task
971 #define	sd_handle_mchange		ssd_handle_mchange
972 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
973 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
974 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
975 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
976 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
977 					sd_send_scsi_feature_GET_CONFIGURATION
978 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
979 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
980 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
981 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
982 					ssd_send_scsi_PERSISTENT_RESERVE_IN
983 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
984 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
985 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
986 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
987 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
988 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
989 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
990 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
991 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
992 #define	sd_alloc_rqs			ssd_alloc_rqs
993 #define	sd_free_rqs			ssd_free_rqs
994 #define	sd_dump_memory			ssd_dump_memory
995 #define	sd_get_media_info		ssd_get_media_info
996 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
997 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
998 #define	sd_setup_next_xfer		ssd_setup_next_xfer
999 #define	sd_dkio_get_temp		ssd_dkio_get_temp
1000 #define	sd_check_mhd			ssd_check_mhd
1001 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1002 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1003 #define	sd_sname			ssd_sname
1004 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1005 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1006 #define	sd_take_ownership		ssd_take_ownership
1007 #define	sd_reserve_release		ssd_reserve_release
1008 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1009 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1010 #define	sd_persistent_reservation_in_read_keys	\
1011 					ssd_persistent_reservation_in_read_keys
1012 #define	sd_persistent_reservation_in_read_resv	\
1013 					ssd_persistent_reservation_in_read_resv
1014 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1015 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1016 #define	sd_mhdioc_release		ssd_mhdioc_release
1017 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1018 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1019 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1020 #define	sr_change_blkmode		ssr_change_blkmode
1021 #define	sr_change_speed			ssr_change_speed
1022 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1023 #define	sr_pause_resume			ssr_pause_resume
1024 #define	sr_play_msf			ssr_play_msf
1025 #define	sr_play_trkind			ssr_play_trkind
1026 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1027 #define	sr_read_subchannel		ssr_read_subchannel
1028 #define	sr_read_tocentry		ssr_read_tocentry
1029 #define	sr_read_tochdr			ssr_read_tochdr
1030 #define	sr_read_cdda			ssr_read_cdda
1031 #define	sr_read_cdxa			ssr_read_cdxa
1032 #define	sr_read_mode1			ssr_read_mode1
1033 #define	sr_read_mode2			ssr_read_mode2
1034 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1035 #define	sr_sector_mode			ssr_sector_mode
1036 #define	sr_eject			ssr_eject
1037 #define	sr_ejected			ssr_ejected
1038 #define	sr_check_wp			ssr_check_wp
1039 #define	sd_check_media			ssd_check_media
1040 #define	sd_media_watch_cb		ssd_media_watch_cb
1041 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1042 #define	sr_volume_ctrl			ssr_volume_ctrl
1043 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1044 #define	sd_log_page_supported		ssd_log_page_supported
1045 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1046 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1047 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1048 #define	sd_range_lock			ssd_range_lock
1049 #define	sd_get_range			ssd_get_range
1050 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1051 #define	sd_range_unlock			ssd_range_unlock
1052 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1053 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1054 
1055 #define	sd_iostart_chain		ssd_iostart_chain
1056 #define	sd_iodone_chain			ssd_iodone_chain
1057 #define	sd_initpkt_map			ssd_initpkt_map
1058 #define	sd_destroypkt_map		ssd_destroypkt_map
1059 #define	sd_chain_type_map		ssd_chain_type_map
1060 #define	sd_chain_index_map		ssd_chain_index_map
1061 
1062 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1063 #define	sd_failfast_flushq		ssd_failfast_flushq
1064 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1065 
1066 #define	sd_is_lsi			ssd_is_lsi
1067 #define	sd_tg_rdwr			ssd_tg_rdwr
1068 #define	sd_tg_getinfo			ssd_tg_getinfo
1069 
1070 #endif	/* #if (defined(__fibre)) */
1071 
1072 
1073 int _init(void);
1074 int _fini(void);
1075 int _info(struct modinfo *modinfop);
1076 
1077 /*PRINTFLIKE3*/
1078 static void sd_log_trace(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1079 /*PRINTFLIKE3*/
1080 static void sd_log_info(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1081 /*PRINTFLIKE3*/
1082 static void sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1083 
1084 static int sdprobe(dev_info_t *devi);
1085 static int sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
1086     void **result);
1087 static int sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
1088     int mod_flags, char *name, caddr_t valuep, int *lengthp);
1089 
1090 /*
1091  * Smart probe for parallel scsi
1092  */
1093 static void sd_scsi_probe_cache_init(void);
1094 static void sd_scsi_probe_cache_fini(void);
1095 static void sd_scsi_clear_probe_cache(void);
1096 static int  sd_scsi_probe_with_cache(struct scsi_device *devp, int (*fn)());
1097 
1098 /*
1099  * Attached luns on target for parallel scsi
1100  */
1101 static void sd_scsi_target_lun_init(void);
1102 static void sd_scsi_target_lun_fini(void);
1103 static int  sd_scsi_get_target_lun_count(dev_info_t *dip, int target);
1104 static void sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag);
1105 
1106 static int	sd_spin_up_unit(struct sd_lun *un);
1107 #ifdef _LP64
1108 static void	sd_enable_descr_sense(struct sd_lun *un);
1109 static void	sd_reenable_dsense_task(void *arg);
1110 #endif /* _LP64 */
1111 
1112 static void	sd_set_mmc_caps(struct sd_lun *un);
1113 
1114 static void sd_read_unit_properties(struct sd_lun *un);
1115 static int  sd_process_sdconf_file(struct sd_lun *un);
1116 static void sd_get_tunables_from_conf(struct sd_lun *un, int flags,
1117     int *data_list, sd_tunables *values);
1118 static void sd_process_sdconf_table(struct sd_lun *un);
1119 static int  sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen);
1120 static int  sd_blank_cmp(struct sd_lun *un, char *id, int idlen);
1121 static int  sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
1122 	int list_len, char *dataname_ptr);
1123 static void sd_set_vers1_properties(struct sd_lun *un, int flags,
1124     sd_tunables *prop_list);
1125 
1126 static void sd_register_devid(struct sd_lun *un, dev_info_t *devi,
1127     int reservation_flag);
1128 static int  sd_get_devid(struct sd_lun *un);
1129 static ddi_devid_t sd_create_devid(struct sd_lun *un);
1130 static int  sd_write_deviceid(struct sd_lun *un);
1131 static int  sd_get_devid_page(struct sd_lun *un, uchar_t *wwn, int *len);
1132 static int  sd_check_vpd_page_support(struct sd_lun *un);
1133 
1134 static void sd_setup_pm(struct sd_lun *un, dev_info_t *devi);
1135 static void sd_create_pm_components(dev_info_t *devi, struct sd_lun *un);
1136 
1137 static int  sd_ddi_suspend(dev_info_t *devi);
1138 static int  sd_ddi_pm_suspend(struct sd_lun *un);
1139 static int  sd_ddi_resume(dev_info_t *devi);
1140 static int  sd_ddi_pm_resume(struct sd_lun *un);
1141 static int  sdpower(dev_info_t *devi, int component, int level);
1142 
1143 static int  sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd);
1144 static int  sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd);
1145 static int  sd_unit_attach(dev_info_t *devi);
1146 static int  sd_unit_detach(dev_info_t *devi);
1147 
1148 static void sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi);
1149 static void sd_create_errstats(struct sd_lun *un, int instance);
1150 static void sd_set_errstats(struct sd_lun *un);
1151 static void sd_set_pstats(struct sd_lun *un);
1152 
1153 static int  sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
1154 static int  sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pkt);
1155 static int  sd_send_polled_RQS(struct sd_lun *un);
1156 static int  sd_ddi_scsi_poll(struct scsi_pkt *pkt);
1157 
1158 #if (defined(__fibre))
1159 /*
1160  * Event callbacks (photon)
1161  */
1162 static void sd_init_event_callbacks(struct sd_lun *un);
1163 static void  sd_event_callback(dev_info_t *, ddi_eventcookie_t, void *, void *);
1164 #endif
1165 
1166 /*
1167  * Defines for sd_cache_control
1168  */
1169 
1170 #define	SD_CACHE_ENABLE		1
1171 #define	SD_CACHE_DISABLE	0
1172 #define	SD_CACHE_NOCHANGE	-1
1173 
1174 static int   sd_cache_control(struct sd_lun *un, int rcd_flag, int wce_flag);
1175 static int   sd_get_write_cache_enabled(struct sd_lun *un, int *is_enabled);
1176 static dev_t sd_make_device(dev_info_t *devi);
1177 
1178 static void  sd_update_block_info(struct sd_lun *un, uint32_t lbasize,
1179 	uint64_t capacity);
1180 
1181 /*
1182  * Driver entry point functions.
1183  */
1184 static int  sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p);
1185 static int  sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p);
1186 static int  sd_ready_and_valid(struct sd_lun *un);
1187 
1188 static void sdmin(struct buf *bp);
1189 static int sdread(dev_t dev, struct uio *uio, cred_t *cred_p);
1190 static int sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p);
1191 static int sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1192 static int sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1193 
1194 static int sdstrategy(struct buf *bp);
1195 static int sdioctl(dev_t, int, intptr_t, int, cred_t *, int *);
1196 
1197 /*
1198  * Function prototypes for layering functions in the iostart chain.
1199  */
1200 static void sd_mapblockaddr_iostart(int index, struct sd_lun *un,
1201 	struct buf *bp);
1202 static void sd_mapblocksize_iostart(int index, struct sd_lun *un,
1203 	struct buf *bp);
1204 static void sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp);
1205 static void sd_checksum_uscsi_iostart(int index, struct sd_lun *un,
1206 	struct buf *bp);
1207 static void sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp);
1208 static void sd_core_iostart(int index, struct sd_lun *un, struct buf *bp);
1209 
1210 /*
1211  * Function prototypes for layering functions in the iodone chain.
1212  */
1213 static void sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp);
1214 static void sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp);
1215 static void sd_mapblockaddr_iodone(int index, struct sd_lun *un,
1216 	struct buf *bp);
1217 static void sd_mapblocksize_iodone(int index, struct sd_lun *un,
1218 	struct buf *bp);
1219 static void sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp);
1220 static void sd_checksum_uscsi_iodone(int index, struct sd_lun *un,
1221 	struct buf *bp);
1222 static void sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp);
1223 
1224 /*
1225  * Prototypes for functions to support buf(9S) based IO.
1226  */
1227 static void sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg);
1228 static int sd_initpkt_for_buf(struct buf *, struct scsi_pkt **);
1229 static void sd_destroypkt_for_buf(struct buf *);
1230 static int sd_setup_rw_pkt(struct sd_lun *un, struct scsi_pkt **pktpp,
1231 	struct buf *bp, int flags,
1232 	int (*callback)(caddr_t), caddr_t callback_arg,
1233 	diskaddr_t lba, uint32_t blockcount);
1234 #if defined(__i386) || defined(__amd64)
1235 static int sd_setup_next_rw_pkt(struct sd_lun *un, struct scsi_pkt *pktp,
1236 	struct buf *bp, diskaddr_t lba, uint32_t blockcount);
1237 #endif /* defined(__i386) || defined(__amd64) */
1238 
1239 /*
1240  * Prototypes for functions to support USCSI IO.
1241  */
1242 static int sd_uscsi_strategy(struct buf *bp);
1243 static int sd_initpkt_for_uscsi(struct buf *, struct scsi_pkt **);
1244 static void sd_destroypkt_for_uscsi(struct buf *);
1245 
1246 static void sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
1247 	uchar_t chain_type, void *pktinfop);
1248 
1249 static int  sd_pm_entry(struct sd_lun *un);
1250 static void sd_pm_exit(struct sd_lun *un);
1251 
1252 static void sd_pm_idletimeout_handler(void *arg);
1253 
1254 /*
1255  * sd_core internal functions (used at the sd_core_io layer).
1256  */
1257 static void sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp);
1258 static void sdintr(struct scsi_pkt *pktp);
1259 static void sd_start_cmds(struct sd_lun *un, struct buf *immed_bp);
1260 
1261 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1262 	enum uio_seg dataspace, int path_flag);
1263 
1264 static struct buf *sd_bioclone_alloc(struct buf *bp, size_t datalen,
1265 	daddr_t blkno, int (*func)(struct buf *));
1266 static struct buf *sd_shadow_buf_alloc(struct buf *bp, size_t datalen,
1267 	uint_t bflags, daddr_t blkno, int (*func)(struct buf *));
1268 static void sd_bioclone_free(struct buf *bp);
1269 static void sd_shadow_buf_free(struct buf *bp);
1270 
1271 static void sd_print_transport_rejected_message(struct sd_lun *un,
1272 	struct sd_xbuf *xp, int code);
1273 static void sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp,
1274     void *arg, int code);
1275 static void sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp,
1276     void *arg, int code);
1277 static void sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp,
1278     void *arg, int code);
1279 
1280 static void sd_retry_command(struct sd_lun *un, struct buf *bp,
1281 	int retry_check_flag,
1282 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp,
1283 		int c),
1284 	void *user_arg, int failure_code,  clock_t retry_delay,
1285 	void (*statp)(kstat_io_t *));
1286 
1287 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1288 	clock_t retry_delay, void (*statp)(kstat_io_t *));
1289 
1290 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1291 	struct scsi_pkt *pktp);
1292 static void sd_start_retry_command(void *arg);
1293 static void sd_start_direct_priority_command(void *arg);
1294 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1295 	int errcode);
1296 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1297 	struct buf *bp, int errcode);
1298 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1299 static void sd_sync_with_callback(struct sd_lun *un);
1300 static int sdrunout(caddr_t arg);
1301 
1302 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1303 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1304 
1305 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1306 static void sd_restore_throttle(void *arg);
1307 
1308 static void sd_init_cdb_limits(struct sd_lun *un);
1309 
1310 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1311 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1312 
1313 /*
1314  * Error handling functions
1315  */
1316 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1317 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1318 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1319 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1320 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1321 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1322 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1323 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1324 
1325 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1326 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1327 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1328 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1329 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1330 	struct sd_xbuf *xp);
1331 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1332 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1333 
1334 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1335 	void *arg, int code);
1336 
1337 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1338 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1339 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1340 	uint8_t *sense_datap,
1341 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1342 static void sd_sense_key_not_ready(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_medium_or_hardware_error(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_illegal_request(struct sd_lun *un, struct buf *bp,
1349 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1350 static void sd_sense_key_unit_attention(struct sd_lun *un,
1351 	uint8_t *sense_datap,
1352 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1353 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1354 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1355 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1356 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1357 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1358 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1359 static void sd_sense_key_default(struct sd_lun *un,
1360 	uint8_t *sense_datap,
1361 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1362 
1363 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1364 	void *arg, int flag);
1365 
1366 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1367 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1368 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1369 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1370 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1371 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1372 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1373 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1374 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1375 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1376 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1377 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1378 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1379 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1380 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1381 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1382 
1383 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1384 
1385 static void sd_start_stop_unit_callback(void *arg);
1386 static void sd_start_stop_unit_task(void *arg);
1387 
1388 static void sd_taskq_create(void);
1389 static void sd_taskq_delete(void);
1390 static void sd_media_change_task(void *arg);
1391 
1392 static int sd_handle_mchange(struct sd_lun *un);
1393 static int sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag);
1394 static int sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp,
1395 	uint32_t *lbap, int path_flag);
1396 static int sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
1397 	uint32_t *lbap, int path_flag);
1398 static int sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag,
1399 	int path_flag);
1400 static int sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr,
1401 	size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1402 static int sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag);
1403 static int sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un,
1404 	uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1405 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un,
1406 	uchar_t usr_cmd, uchar_t *usr_bufp);
1407 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1408 	struct dk_callback *dkc);
1409 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1410 static int sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un,
1411 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1412 	uchar_t *bufaddr, uint_t buflen, int path_flag);
1413 static int sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
1414 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1415 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag);
1416 static int sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize,
1417 	uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1418 static int sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize,
1419 	uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1420 static int sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
1421 	size_t buflen, daddr_t start_block, int path_flag);
1422 #define	sd_send_scsi_READ(un, bufaddr, buflen, start_block, path_flag)	\
1423 	sd_send_scsi_RDWR(un, SCMD_READ, bufaddr, buflen, start_block, \
1424 	path_flag)
1425 #define	sd_send_scsi_WRITE(un, bufaddr, buflen, start_block, path_flag)	\
1426 	sd_send_scsi_RDWR(un, SCMD_WRITE, bufaddr, buflen, start_block,\
1427 	path_flag)
1428 
1429 static int sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr,
1430 	uint16_t buflen, uchar_t page_code, uchar_t page_control,
1431 	uint16_t param_ptr, int path_flag);
1432 
1433 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1434 static void sd_free_rqs(struct sd_lun *un);
1435 
1436 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1437 	uchar_t *data, int len, int fmt);
1438 static void sd_panic_for_res_conflict(struct sd_lun *un);
1439 
1440 /*
1441  * Disk Ioctl Function Prototypes
1442  */
1443 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1444 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1445 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1446 
1447 /*
1448  * Multi-host Ioctl Prototypes
1449  */
1450 static int sd_check_mhd(dev_t dev, int interval);
1451 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1452 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1453 static char *sd_sname(uchar_t status);
1454 static void sd_mhd_resvd_recover(void *arg);
1455 static void sd_resv_reclaim_thread();
1456 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1457 static int sd_reserve_release(dev_t dev, int cmd);
1458 static void sd_rmv_resv_reclaim_req(dev_t dev);
1459 static void sd_mhd_reset_notify_cb(caddr_t arg);
1460 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1461 	mhioc_inkeys_t *usrp, int flag);
1462 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1463 	mhioc_inresvs_t *usrp, int flag);
1464 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1465 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1466 static int sd_mhdioc_release(dev_t dev);
1467 static int sd_mhdioc_register_devid(dev_t dev);
1468 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1469 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1470 
1471 /*
1472  * SCSI removable prototypes
1473  */
1474 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1475 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1476 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1477 static int sr_pause_resume(dev_t dev, int mode);
1478 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1479 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1480 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1481 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1482 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1483 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1484 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1485 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1486 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1487 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1488 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1489 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1490 static int sr_eject(dev_t dev);
1491 static void sr_ejected(register struct sd_lun *un);
1492 static int sr_check_wp(dev_t dev);
1493 static int sd_check_media(dev_t dev, enum dkio_state state);
1494 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1495 static void sd_delayed_cv_broadcast(void *arg);
1496 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1497 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1498 
1499 static int sd_log_page_supported(struct sd_lun *un, int log_page);
1500 
1501 /*
1502  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1503  */
1504 static void sd_check_for_writable_cd(struct sd_lun *un, int path_flag);
1505 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1506 static void sd_wm_cache_destructor(void *wm, void *un);
1507 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1508 	daddr_t endb, ushort_t typ);
1509 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1510 	daddr_t endb);
1511 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1512 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1513 static void sd_read_modify_write_task(void * arg);
1514 static int
1515 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1516 	struct buf **bpp);
1517 
1518 
1519 /*
1520  * Function prototypes for failfast support.
1521  */
1522 static void sd_failfast_flushq(struct sd_lun *un);
1523 static int sd_failfast_flushq_callback(struct buf *bp);
1524 
1525 /*
1526  * Function prototypes to check for lsi devices
1527  */
1528 static void sd_is_lsi(struct sd_lun *un);
1529 
1530 /*
1531  * Function prototypes for x86 support
1532  */
1533 #if defined(__i386) || defined(__amd64)
1534 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1535 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1536 #endif
1537 
1538 
1539 /* Function prototypes for cmlb */
1540 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1541     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1542 
1543 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1544 
1545 /*
1546  * Constants for failfast support:
1547  *
1548  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1549  * failfast processing being performed.
1550  *
1551  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1552  * failfast processing on all bufs with B_FAILFAST set.
1553  */
1554 
1555 #define	SD_FAILFAST_INACTIVE		0
1556 #define	SD_FAILFAST_ACTIVE		1
1557 
1558 /*
1559  * Bitmask to control behavior of buf(9S) flushes when a transition to
1560  * the failfast state occurs. Optional bits include:
1561  *
1562  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1563  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1564  * be flushed.
1565  *
1566  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1567  * driver, in addition to the regular wait queue. This includes the xbuf
1568  * queues. When clear, only the driver's wait queue will be flushed.
1569  */
1570 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1571 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1572 
1573 /*
1574  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1575  * to flush all queues within the driver.
1576  */
1577 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1578 
1579 
1580 /*
1581  * SD Testing Fault Injection
1582  */
1583 #ifdef SD_FAULT_INJECTION
1584 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1585 static void sd_faultinjection(struct scsi_pkt *pktp);
1586 static void sd_injection_log(char *buf, struct sd_lun *un);
1587 #endif
1588 
1589 /*
1590  * Device driver ops vector
1591  */
1592 static struct cb_ops sd_cb_ops = {
1593 	sdopen,			/* open */
1594 	sdclose,		/* close */
1595 	sdstrategy,		/* strategy */
1596 	nodev,			/* print */
1597 	sddump,			/* dump */
1598 	sdread,			/* read */
1599 	sdwrite,		/* write */
1600 	sdioctl,		/* ioctl */
1601 	nodev,			/* devmap */
1602 	nodev,			/* mmap */
1603 	nodev,			/* segmap */
1604 	nochpoll,		/* poll */
1605 	sd_prop_op,		/* cb_prop_op */
1606 	0,			/* streamtab  */
1607 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1608 	CB_REV,			/* cb_rev */
1609 	sdaread, 		/* async I/O read entry point */
1610 	sdawrite		/* async I/O write entry point */
1611 };
1612 
1613 static struct dev_ops sd_ops = {
1614 	DEVO_REV,		/* devo_rev, */
1615 	0,			/* refcnt  */
1616 	sdinfo,			/* info */
1617 	nulldev,		/* identify */
1618 	sdprobe,		/* probe */
1619 	sdattach,		/* attach */
1620 	sddetach,		/* detach */
1621 	nodev,			/* reset */
1622 	&sd_cb_ops,		/* driver operations */
1623 	NULL,			/* bus operations */
1624 	sdpower			/* power */
1625 };
1626 
1627 
1628 /*
1629  * This is the loadable module wrapper.
1630  */
1631 #include <sys/modctl.h>
1632 
1633 static struct modldrv modldrv = {
1634 	&mod_driverops,		/* Type of module. This one is a driver */
1635 	SD_MODULE_NAME,		/* Module name. */
1636 	&sd_ops			/* driver ops */
1637 };
1638 
1639 
1640 static struct modlinkage modlinkage = {
1641 	MODREV_1,
1642 	&modldrv,
1643 	NULL
1644 };
1645 
1646 static cmlb_tg_ops_t sd_tgops = {
1647 	TG_DK_OPS_VERSION_1,
1648 	sd_tg_rdwr,
1649 	sd_tg_getinfo
1650 	};
1651 
1652 static struct scsi_asq_key_strings sd_additional_codes[] = {
1653 	0x81, 0, "Logical Unit is Reserved",
1654 	0x85, 0, "Audio Address Not Valid",
1655 	0xb6, 0, "Media Load Mechanism Failed",
1656 	0xB9, 0, "Audio Play Operation Aborted",
1657 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1658 	0x53, 2, "Medium removal prevented",
1659 	0x6f, 0, "Authentication failed during key exchange",
1660 	0x6f, 1, "Key not present",
1661 	0x6f, 2, "Key not established",
1662 	0x6f, 3, "Read without proper authentication",
1663 	0x6f, 4, "Mismatched region to this logical unit",
1664 	0x6f, 5, "Region reset count error",
1665 	0xffff, 0x0, NULL
1666 };
1667 
1668 
1669 /*
1670  * Struct for passing printing information for sense data messages
1671  */
1672 struct sd_sense_info {
1673 	int	ssi_severity;
1674 	int	ssi_pfa_flag;
1675 };
1676 
1677 /*
1678  * Table of function pointers for iostart-side routines. Separate "chains"
1679  * of layered function calls are formed by placing the function pointers
1680  * sequentially in the desired order. Functions are called according to an
1681  * incrementing table index ordering. The last function in each chain must
1682  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1683  * in the sd_iodone_chain[] array.
1684  *
1685  * Note: It may seem more natural to organize both the iostart and iodone
1686  * functions together, into an array of structures (or some similar
1687  * organization) with a common index, rather than two separate arrays which
1688  * must be maintained in synchronization. The purpose of this division is
1689  * to achieve improved performance: individual arrays allows for more
1690  * effective cache line utilization on certain platforms.
1691  */
1692 
1693 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1694 
1695 
1696 static sd_chain_t sd_iostart_chain[] = {
1697 
1698 	/* Chain for buf IO for disk drive targets (PM enabled) */
1699 	sd_mapblockaddr_iostart,	/* Index: 0 */
1700 	sd_pm_iostart,			/* Index: 1 */
1701 	sd_core_iostart,		/* Index: 2 */
1702 
1703 	/* Chain for buf IO for disk drive targets (PM disabled) */
1704 	sd_mapblockaddr_iostart,	/* Index: 3 */
1705 	sd_core_iostart,		/* Index: 4 */
1706 
1707 	/* Chain for buf IO for removable-media targets (PM enabled) */
1708 	sd_mapblockaddr_iostart,	/* Index: 5 */
1709 	sd_mapblocksize_iostart,	/* Index: 6 */
1710 	sd_pm_iostart,			/* Index: 7 */
1711 	sd_core_iostart,		/* Index: 8 */
1712 
1713 	/* Chain for buf IO for removable-media targets (PM disabled) */
1714 	sd_mapblockaddr_iostart,	/* Index: 9 */
1715 	sd_mapblocksize_iostart,	/* Index: 10 */
1716 	sd_core_iostart,		/* Index: 11 */
1717 
1718 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1719 	sd_mapblockaddr_iostart,	/* Index: 12 */
1720 	sd_checksum_iostart,		/* Index: 13 */
1721 	sd_pm_iostart,			/* Index: 14 */
1722 	sd_core_iostart,		/* Index: 15 */
1723 
1724 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1725 	sd_mapblockaddr_iostart,	/* Index: 16 */
1726 	sd_checksum_iostart,		/* Index: 17 */
1727 	sd_core_iostart,		/* Index: 18 */
1728 
1729 	/* Chain for USCSI commands (all targets) */
1730 	sd_pm_iostart,			/* Index: 19 */
1731 	sd_core_iostart,		/* Index: 20 */
1732 
1733 	/* Chain for checksumming USCSI commands (all targets) */
1734 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1735 	sd_pm_iostart,			/* Index: 22 */
1736 	sd_core_iostart,		/* Index: 23 */
1737 
1738 	/* Chain for "direct" USCSI commands (all targets) */
1739 	sd_core_iostart,		/* Index: 24 */
1740 
1741 	/* Chain for "direct priority" USCSI commands (all targets) */
1742 	sd_core_iostart,		/* Index: 25 */
1743 };
1744 
1745 /*
1746  * Macros to locate the first function of each iostart chain in the
1747  * sd_iostart_chain[] array. These are located by the index in the array.
1748  */
1749 #define	SD_CHAIN_DISK_IOSTART			0
1750 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1751 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1752 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1753 #define	SD_CHAIN_CHKSUM_IOSTART			12
1754 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1755 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1756 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1757 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1758 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1759 
1760 
1761 /*
1762  * Table of function pointers for the iodone-side routines for the driver-
1763  * internal layering mechanism.  The calling sequence for iodone routines
1764  * uses a decrementing table index, so the last routine called in a chain
1765  * must be at the lowest array index location for that chain.  The last
1766  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1767  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1768  * of the functions in an iodone side chain must correspond to the ordering
1769  * of the iostart routines for that chain.  Note that there is no iodone
1770  * side routine that corresponds to sd_core_iostart(), so there is no
1771  * entry in the table for this.
1772  */
1773 
1774 static sd_chain_t sd_iodone_chain[] = {
1775 
1776 	/* Chain for buf IO for disk drive targets (PM enabled) */
1777 	sd_buf_iodone,			/* Index: 0 */
1778 	sd_mapblockaddr_iodone,		/* Index: 1 */
1779 	sd_pm_iodone,			/* Index: 2 */
1780 
1781 	/* Chain for buf IO for disk drive targets (PM disabled) */
1782 	sd_buf_iodone,			/* Index: 3 */
1783 	sd_mapblockaddr_iodone,		/* Index: 4 */
1784 
1785 	/* Chain for buf IO for removable-media targets (PM enabled) */
1786 	sd_buf_iodone,			/* Index: 5 */
1787 	sd_mapblockaddr_iodone,		/* Index: 6 */
1788 	sd_mapblocksize_iodone,		/* Index: 7 */
1789 	sd_pm_iodone,			/* Index: 8 */
1790 
1791 	/* Chain for buf IO for removable-media targets (PM disabled) */
1792 	sd_buf_iodone,			/* Index: 9 */
1793 	sd_mapblockaddr_iodone,		/* Index: 10 */
1794 	sd_mapblocksize_iodone,		/* Index: 11 */
1795 
1796 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1797 	sd_buf_iodone,			/* Index: 12 */
1798 	sd_mapblockaddr_iodone,		/* Index: 13 */
1799 	sd_checksum_iodone,		/* Index: 14 */
1800 	sd_pm_iodone,			/* Index: 15 */
1801 
1802 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1803 	sd_buf_iodone,			/* Index: 16 */
1804 	sd_mapblockaddr_iodone,		/* Index: 17 */
1805 	sd_checksum_iodone,		/* Index: 18 */
1806 
1807 	/* Chain for USCSI commands (non-checksum targets) */
1808 	sd_uscsi_iodone,		/* Index: 19 */
1809 	sd_pm_iodone,			/* Index: 20 */
1810 
1811 	/* Chain for USCSI commands (checksum targets) */
1812 	sd_uscsi_iodone,		/* Index: 21 */
1813 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1814 	sd_pm_iodone,			/* Index: 22 */
1815 
1816 	/* Chain for "direct" USCSI commands (all targets) */
1817 	sd_uscsi_iodone,		/* Index: 24 */
1818 
1819 	/* Chain for "direct priority" USCSI commands (all targets) */
1820 	sd_uscsi_iodone,		/* Index: 25 */
1821 };
1822 
1823 
1824 /*
1825  * Macros to locate the "first" function in the sd_iodone_chain[] array for
1826  * each iodone-side chain. These are located by the array index, but as the
1827  * iodone side functions are called in a decrementing-index order, the
1828  * highest index number in each chain must be specified (as these correspond
1829  * to the first function in the iodone chain that will be called by the core
1830  * at IO completion time).
1831  */
1832 
1833 #define	SD_CHAIN_DISK_IODONE			2
1834 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
1835 #define	SD_CHAIN_RMMEDIA_IODONE			8
1836 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
1837 #define	SD_CHAIN_CHKSUM_IODONE			15
1838 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
1839 #define	SD_CHAIN_USCSI_CMD_IODONE		20
1840 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
1841 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
1842 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
1843 
1844 
1845 
1846 
1847 /*
1848  * Array to map a layering chain index to the appropriate initpkt routine.
1849  * The redundant entries are present so that the index used for accessing
1850  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1851  * with this table as well.
1852  */
1853 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
1854 
1855 static sd_initpkt_t	sd_initpkt_map[] = {
1856 
1857 	/* Chain for buf IO for disk drive targets (PM enabled) */
1858 	sd_initpkt_for_buf,		/* Index: 0 */
1859 	sd_initpkt_for_buf,		/* Index: 1 */
1860 	sd_initpkt_for_buf,		/* Index: 2 */
1861 
1862 	/* Chain for buf IO for disk drive targets (PM disabled) */
1863 	sd_initpkt_for_buf,		/* Index: 3 */
1864 	sd_initpkt_for_buf,		/* Index: 4 */
1865 
1866 	/* Chain for buf IO for removable-media targets (PM enabled) */
1867 	sd_initpkt_for_buf,		/* Index: 5 */
1868 	sd_initpkt_for_buf,		/* Index: 6 */
1869 	sd_initpkt_for_buf,		/* Index: 7 */
1870 	sd_initpkt_for_buf,		/* Index: 8 */
1871 
1872 	/* Chain for buf IO for removable-media targets (PM disabled) */
1873 	sd_initpkt_for_buf,		/* Index: 9 */
1874 	sd_initpkt_for_buf,		/* Index: 10 */
1875 	sd_initpkt_for_buf,		/* Index: 11 */
1876 
1877 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1878 	sd_initpkt_for_buf,		/* Index: 12 */
1879 	sd_initpkt_for_buf,		/* Index: 13 */
1880 	sd_initpkt_for_buf,		/* Index: 14 */
1881 	sd_initpkt_for_buf,		/* Index: 15 */
1882 
1883 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1884 	sd_initpkt_for_buf,		/* Index: 16 */
1885 	sd_initpkt_for_buf,		/* Index: 17 */
1886 	sd_initpkt_for_buf,		/* Index: 18 */
1887 
1888 	/* Chain for USCSI commands (non-checksum targets) */
1889 	sd_initpkt_for_uscsi,		/* Index: 19 */
1890 	sd_initpkt_for_uscsi,		/* Index: 20 */
1891 
1892 	/* Chain for USCSI commands (checksum targets) */
1893 	sd_initpkt_for_uscsi,		/* Index: 21 */
1894 	sd_initpkt_for_uscsi,		/* Index: 22 */
1895 	sd_initpkt_for_uscsi,		/* Index: 22 */
1896 
1897 	/* Chain for "direct" USCSI commands (all targets) */
1898 	sd_initpkt_for_uscsi,		/* Index: 24 */
1899 
1900 	/* Chain for "direct priority" USCSI commands (all targets) */
1901 	sd_initpkt_for_uscsi,		/* Index: 25 */
1902 
1903 };
1904 
1905 
1906 /*
1907  * Array to map a layering chain index to the appropriate destroypktpkt routine.
1908  * The redundant entries are present so that the index used for accessing
1909  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1910  * with this table as well.
1911  */
1912 typedef void (*sd_destroypkt_t)(struct buf *);
1913 
1914 static sd_destroypkt_t	sd_destroypkt_map[] = {
1915 
1916 	/* Chain for buf IO for disk drive targets (PM enabled) */
1917 	sd_destroypkt_for_buf,		/* Index: 0 */
1918 	sd_destroypkt_for_buf,		/* Index: 1 */
1919 	sd_destroypkt_for_buf,		/* Index: 2 */
1920 
1921 	/* Chain for buf IO for disk drive targets (PM disabled) */
1922 	sd_destroypkt_for_buf,		/* Index: 3 */
1923 	sd_destroypkt_for_buf,		/* Index: 4 */
1924 
1925 	/* Chain for buf IO for removable-media targets (PM enabled) */
1926 	sd_destroypkt_for_buf,		/* Index: 5 */
1927 	sd_destroypkt_for_buf,		/* Index: 6 */
1928 	sd_destroypkt_for_buf,		/* Index: 7 */
1929 	sd_destroypkt_for_buf,		/* Index: 8 */
1930 
1931 	/* Chain for buf IO for removable-media targets (PM disabled) */
1932 	sd_destroypkt_for_buf,		/* Index: 9 */
1933 	sd_destroypkt_for_buf,		/* Index: 10 */
1934 	sd_destroypkt_for_buf,		/* Index: 11 */
1935 
1936 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1937 	sd_destroypkt_for_buf,		/* Index: 12 */
1938 	sd_destroypkt_for_buf,		/* Index: 13 */
1939 	sd_destroypkt_for_buf,		/* Index: 14 */
1940 	sd_destroypkt_for_buf,		/* Index: 15 */
1941 
1942 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1943 	sd_destroypkt_for_buf,		/* Index: 16 */
1944 	sd_destroypkt_for_buf,		/* Index: 17 */
1945 	sd_destroypkt_for_buf,		/* Index: 18 */
1946 
1947 	/* Chain for USCSI commands (non-checksum targets) */
1948 	sd_destroypkt_for_uscsi,	/* Index: 19 */
1949 	sd_destroypkt_for_uscsi,	/* Index: 20 */
1950 
1951 	/* Chain for USCSI commands (checksum targets) */
1952 	sd_destroypkt_for_uscsi,	/* Index: 21 */
1953 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1954 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1955 
1956 	/* Chain for "direct" USCSI commands (all targets) */
1957 	sd_destroypkt_for_uscsi,	/* Index: 24 */
1958 
1959 	/* Chain for "direct priority" USCSI commands (all targets) */
1960 	sd_destroypkt_for_uscsi,	/* Index: 25 */
1961 
1962 };
1963 
1964 
1965 
1966 /*
1967  * Array to map a layering chain index to the appropriate chain "type".
1968  * The chain type indicates a specific property/usage of the chain.
1969  * The redundant entries are present so that the index used for accessing
1970  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1971  * with this table as well.
1972  */
1973 
1974 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
1975 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
1976 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
1977 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
1978 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
1979 						/* (for error recovery) */
1980 
1981 static int sd_chain_type_map[] = {
1982 
1983 	/* Chain for buf IO for disk drive targets (PM enabled) */
1984 	SD_CHAIN_BUFIO,			/* Index: 0 */
1985 	SD_CHAIN_BUFIO,			/* Index: 1 */
1986 	SD_CHAIN_BUFIO,			/* Index: 2 */
1987 
1988 	/* Chain for buf IO for disk drive targets (PM disabled) */
1989 	SD_CHAIN_BUFIO,			/* Index: 3 */
1990 	SD_CHAIN_BUFIO,			/* Index: 4 */
1991 
1992 	/* Chain for buf IO for removable-media targets (PM enabled) */
1993 	SD_CHAIN_BUFIO,			/* Index: 5 */
1994 	SD_CHAIN_BUFIO,			/* Index: 6 */
1995 	SD_CHAIN_BUFIO,			/* Index: 7 */
1996 	SD_CHAIN_BUFIO,			/* Index: 8 */
1997 
1998 	/* Chain for buf IO for removable-media targets (PM disabled) */
1999 	SD_CHAIN_BUFIO,			/* Index: 9 */
2000 	SD_CHAIN_BUFIO,			/* Index: 10 */
2001 	SD_CHAIN_BUFIO,			/* Index: 11 */
2002 
2003 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2004 	SD_CHAIN_BUFIO,			/* Index: 12 */
2005 	SD_CHAIN_BUFIO,			/* Index: 13 */
2006 	SD_CHAIN_BUFIO,			/* Index: 14 */
2007 	SD_CHAIN_BUFIO,			/* Index: 15 */
2008 
2009 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2010 	SD_CHAIN_BUFIO,			/* Index: 16 */
2011 	SD_CHAIN_BUFIO,			/* Index: 17 */
2012 	SD_CHAIN_BUFIO,			/* Index: 18 */
2013 
2014 	/* Chain for USCSI commands (non-checksum targets) */
2015 	SD_CHAIN_USCSI,			/* Index: 19 */
2016 	SD_CHAIN_USCSI,			/* Index: 20 */
2017 
2018 	/* Chain for USCSI commands (checksum targets) */
2019 	SD_CHAIN_USCSI,			/* Index: 21 */
2020 	SD_CHAIN_USCSI,			/* Index: 22 */
2021 	SD_CHAIN_USCSI,			/* Index: 22 */
2022 
2023 	/* Chain for "direct" USCSI commands (all targets) */
2024 	SD_CHAIN_DIRECT,		/* Index: 24 */
2025 
2026 	/* Chain for "direct priority" USCSI commands (all targets) */
2027 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2028 };
2029 
2030 
2031 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2032 #define	SD_IS_BUFIO(xp)			\
2033 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2034 
2035 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2036 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2037 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2038 
2039 
2040 
2041 /*
2042  * Struct, array, and macros to map a specific chain to the appropriate
2043  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2044  *
2045  * The sd_chain_index_map[] array is used at attach time to set the various
2046  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2047  * chain to be used with the instance. This allows different instances to use
2048  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2049  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2050  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2051  * dynamically & without the use of locking; and (2) a layer may update the
2052  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2053  * to allow for deferred processing of an IO within the same chain from a
2054  * different execution context.
2055  */
2056 
2057 struct sd_chain_index {
2058 	int	sci_iostart_index;
2059 	int	sci_iodone_index;
2060 };
2061 
2062 static struct sd_chain_index	sd_chain_index_map[] = {
2063 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2064 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2065 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2066 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2067 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2068 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2069 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2070 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2071 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2072 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2073 };
2074 
2075 
2076 /*
2077  * The following are indexes into the sd_chain_index_map[] array.
2078  */
2079 
2080 /* un->un_buf_chain_type must be set to one of these */
2081 #define	SD_CHAIN_INFO_DISK		0
2082 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2083 #define	SD_CHAIN_INFO_RMMEDIA		2
2084 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2085 #define	SD_CHAIN_INFO_CHKSUM		4
2086 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2087 
2088 /* un->un_uscsi_chain_type must be set to one of these */
2089 #define	SD_CHAIN_INFO_USCSI_CMD		6
2090 /* USCSI with PM disabled is the same as DIRECT */
2091 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2092 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2093 
2094 /* un->un_direct_chain_type must be set to one of these */
2095 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2096 
2097 /* un->un_priority_chain_type must be set to one of these */
2098 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2099 
2100 /* size for devid inquiries */
2101 #define	MAX_INQUIRY_SIZE		0xF0
2102 
2103 /*
2104  * Macros used by functions to pass a given buf(9S) struct along to the
2105  * next function in the layering chain for further processing.
2106  *
2107  * In the following macros, passing more than three arguments to the called
2108  * routines causes the optimizer for the SPARC compiler to stop doing tail
2109  * call elimination which results in significant performance degradation.
2110  */
2111 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2112 	((*(sd_iostart_chain[index]))(index, un, bp))
2113 
2114 #define	SD_BEGIN_IODONE(index, un, bp)	\
2115 	((*(sd_iodone_chain[index]))(index, un, bp))
2116 
2117 #define	SD_NEXT_IOSTART(index, un, bp)				\
2118 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2119 
2120 #define	SD_NEXT_IODONE(index, un, bp)				\
2121 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2122 
2123 /*
2124  *    Function: _init
2125  *
2126  * Description: This is the driver _init(9E) entry point.
2127  *
2128  * Return Code: Returns the value from mod_install(9F) or
2129  *		ddi_soft_state_init(9F) as appropriate.
2130  *
2131  *     Context: Called when driver module loaded.
2132  */
2133 
2134 int
2135 _init(void)
2136 {
2137 	int	err;
2138 
2139 	/* establish driver name from module name */
2140 	sd_label = mod_modname(&modlinkage);
2141 
2142 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2143 	    SD_MAXUNIT);
2144 
2145 	if (err != 0) {
2146 		return (err);
2147 	}
2148 
2149 	mutex_init(&sd_detach_mutex, NULL, MUTEX_DRIVER, NULL);
2150 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2151 	mutex_init(&sd_label_mutex,  NULL, MUTEX_DRIVER, NULL);
2152 
2153 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2154 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2155 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2156 
2157 	/*
2158 	 * it's ok to init here even for fibre device
2159 	 */
2160 	sd_scsi_probe_cache_init();
2161 
2162 	sd_scsi_target_lun_init();
2163 
2164 	/*
2165 	 * Creating taskq before mod_install ensures that all callers (threads)
2166 	 * that enter the module after a successfull mod_install encounter
2167 	 * a valid taskq.
2168 	 */
2169 	sd_taskq_create();
2170 
2171 	err = mod_install(&modlinkage);
2172 	if (err != 0) {
2173 		/* delete taskq if install fails */
2174 		sd_taskq_delete();
2175 
2176 		mutex_destroy(&sd_detach_mutex);
2177 		mutex_destroy(&sd_log_mutex);
2178 		mutex_destroy(&sd_label_mutex);
2179 
2180 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2181 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2182 		cv_destroy(&sd_tr.srq_inprocess_cv);
2183 
2184 		sd_scsi_probe_cache_fini();
2185 
2186 		sd_scsi_target_lun_fini();
2187 
2188 		ddi_soft_state_fini(&sd_state);
2189 		return (err);
2190 	}
2191 
2192 	return (err);
2193 }
2194 
2195 
2196 /*
2197  *    Function: _fini
2198  *
2199  * Description: This is the driver _fini(9E) entry point.
2200  *
2201  * Return Code: Returns the value from mod_remove(9F)
2202  *
2203  *     Context: Called when driver module is unloaded.
2204  */
2205 
2206 int
2207 _fini(void)
2208 {
2209 	int err;
2210 
2211 	if ((err = mod_remove(&modlinkage)) != 0) {
2212 		return (err);
2213 	}
2214 
2215 	sd_taskq_delete();
2216 
2217 	mutex_destroy(&sd_detach_mutex);
2218 	mutex_destroy(&sd_log_mutex);
2219 	mutex_destroy(&sd_label_mutex);
2220 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2221 
2222 	sd_scsi_probe_cache_fini();
2223 
2224 	sd_scsi_target_lun_fini();
2225 
2226 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2227 	cv_destroy(&sd_tr.srq_inprocess_cv);
2228 
2229 	ddi_soft_state_fini(&sd_state);
2230 
2231 	return (err);
2232 }
2233 
2234 
2235 /*
2236  *    Function: _info
2237  *
2238  * Description: This is the driver _info(9E) entry point.
2239  *
2240  *   Arguments: modinfop - pointer to the driver modinfo structure
2241  *
2242  * Return Code: Returns the value from mod_info(9F).
2243  *
2244  *     Context: Kernel thread context
2245  */
2246 
2247 int
2248 _info(struct modinfo *modinfop)
2249 {
2250 	return (mod_info(&modlinkage, modinfop));
2251 }
2252 
2253 
2254 /*
2255  * The following routines implement the driver message logging facility.
2256  * They provide component- and level- based debug output filtering.
2257  * Output may also be restricted to messages for a single instance by
2258  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2259  * to NULL, then messages for all instances are printed.
2260  *
2261  * These routines have been cloned from each other due to the language
2262  * constraints of macros and variable argument list processing.
2263  */
2264 
2265 
2266 /*
2267  *    Function: sd_log_err
2268  *
2269  * Description: This routine is called by the SD_ERROR macro for debug
2270  *		logging of error conditions.
2271  *
2272  *   Arguments: comp - driver component being logged
2273  *		dev  - pointer to driver info structure
2274  *		fmt  - error string and format to be logged
2275  */
2276 
2277 static void
2278 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2279 {
2280 	va_list		ap;
2281 	dev_info_t	*dev;
2282 
2283 	ASSERT(un != NULL);
2284 	dev = SD_DEVINFO(un);
2285 	ASSERT(dev != NULL);
2286 
2287 	/*
2288 	 * Filter messages based on the global component and level masks.
2289 	 * Also print if un matches the value of sd_debug_un, or if
2290 	 * sd_debug_un is set to NULL.
2291 	 */
2292 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2293 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2294 		mutex_enter(&sd_log_mutex);
2295 		va_start(ap, fmt);
2296 		(void) vsprintf(sd_log_buf, fmt, ap);
2297 		va_end(ap);
2298 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2299 		mutex_exit(&sd_log_mutex);
2300 	}
2301 #ifdef SD_FAULT_INJECTION
2302 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2303 	if (un->sd_injection_mask & comp) {
2304 		mutex_enter(&sd_log_mutex);
2305 		va_start(ap, fmt);
2306 		(void) vsprintf(sd_log_buf, fmt, ap);
2307 		va_end(ap);
2308 		sd_injection_log(sd_log_buf, un);
2309 		mutex_exit(&sd_log_mutex);
2310 	}
2311 #endif
2312 }
2313 
2314 
2315 /*
2316  *    Function: sd_log_info
2317  *
2318  * Description: This routine is called by the SD_INFO macro for debug
2319  *		logging of general purpose informational conditions.
2320  *
2321  *   Arguments: comp - driver component being logged
2322  *		dev  - pointer to driver info structure
2323  *		fmt  - info string and format to be logged
2324  */
2325 
2326 static void
2327 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2328 {
2329 	va_list		ap;
2330 	dev_info_t	*dev;
2331 
2332 	ASSERT(un != NULL);
2333 	dev = SD_DEVINFO(un);
2334 	ASSERT(dev != NULL);
2335 
2336 	/*
2337 	 * Filter messages based on the global component and level masks.
2338 	 * Also print if un matches the value of sd_debug_un, or if
2339 	 * sd_debug_un is set to NULL.
2340 	 */
2341 	if ((sd_component_mask & component) &&
2342 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2343 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2344 		mutex_enter(&sd_log_mutex);
2345 		va_start(ap, fmt);
2346 		(void) vsprintf(sd_log_buf, fmt, ap);
2347 		va_end(ap);
2348 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2349 		mutex_exit(&sd_log_mutex);
2350 	}
2351 #ifdef SD_FAULT_INJECTION
2352 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2353 	if (un->sd_injection_mask & component) {
2354 		mutex_enter(&sd_log_mutex);
2355 		va_start(ap, fmt);
2356 		(void) vsprintf(sd_log_buf, fmt, ap);
2357 		va_end(ap);
2358 		sd_injection_log(sd_log_buf, un);
2359 		mutex_exit(&sd_log_mutex);
2360 	}
2361 #endif
2362 }
2363 
2364 
2365 /*
2366  *    Function: sd_log_trace
2367  *
2368  * Description: This routine is called by the SD_TRACE macro for debug
2369  *		logging of trace conditions (i.e. function entry/exit).
2370  *
2371  *   Arguments: comp - driver component being logged
2372  *		dev  - pointer to driver info structure
2373  *		fmt  - trace string and format to be logged
2374  */
2375 
2376 static void
2377 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2378 {
2379 	va_list		ap;
2380 	dev_info_t	*dev;
2381 
2382 	ASSERT(un != NULL);
2383 	dev = SD_DEVINFO(un);
2384 	ASSERT(dev != NULL);
2385 
2386 	/*
2387 	 * Filter messages based on the global component and level masks.
2388 	 * Also print if un matches the value of sd_debug_un, or if
2389 	 * sd_debug_un is set to NULL.
2390 	 */
2391 	if ((sd_component_mask & component) &&
2392 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2393 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2394 		mutex_enter(&sd_log_mutex);
2395 		va_start(ap, fmt);
2396 		(void) vsprintf(sd_log_buf, fmt, ap);
2397 		va_end(ap);
2398 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2399 		mutex_exit(&sd_log_mutex);
2400 	}
2401 #ifdef SD_FAULT_INJECTION
2402 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2403 	if (un->sd_injection_mask & component) {
2404 		mutex_enter(&sd_log_mutex);
2405 		va_start(ap, fmt);
2406 		(void) vsprintf(sd_log_buf, fmt, ap);
2407 		va_end(ap);
2408 		sd_injection_log(sd_log_buf, un);
2409 		mutex_exit(&sd_log_mutex);
2410 	}
2411 #endif
2412 }
2413 
2414 
2415 /*
2416  *    Function: sdprobe
2417  *
2418  * Description: This is the driver probe(9e) entry point function.
2419  *
2420  *   Arguments: devi - opaque device info handle
2421  *
2422  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2423  *              DDI_PROBE_FAILURE: If the probe failed.
2424  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2425  *				   but may be present in the future.
2426  */
2427 
2428 static int
2429 sdprobe(dev_info_t *devi)
2430 {
2431 	struct scsi_device	*devp;
2432 	int			rval;
2433 	int			instance;
2434 
2435 	/*
2436 	 * if it wasn't for pln, sdprobe could actually be nulldev
2437 	 * in the "__fibre" case.
2438 	 */
2439 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2440 		return (DDI_PROBE_DONTCARE);
2441 	}
2442 
2443 	devp = ddi_get_driver_private(devi);
2444 
2445 	if (devp == NULL) {
2446 		/* Ooops... nexus driver is mis-configured... */
2447 		return (DDI_PROBE_FAILURE);
2448 	}
2449 
2450 	instance = ddi_get_instance(devi);
2451 
2452 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2453 		return (DDI_PROBE_PARTIAL);
2454 	}
2455 
2456 	/*
2457 	 * Call the SCSA utility probe routine to see if we actually
2458 	 * have a target at this SCSI nexus.
2459 	 */
2460 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2461 	case SCSIPROBE_EXISTS:
2462 		switch (devp->sd_inq->inq_dtype) {
2463 		case DTYPE_DIRECT:
2464 			rval = DDI_PROBE_SUCCESS;
2465 			break;
2466 		case DTYPE_RODIRECT:
2467 			/* CDs etc. Can be removable media */
2468 			rval = DDI_PROBE_SUCCESS;
2469 			break;
2470 		case DTYPE_OPTICAL:
2471 			/*
2472 			 * Rewritable optical driver HP115AA
2473 			 * Can also be removable media
2474 			 */
2475 
2476 			/*
2477 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2478 			 * pre solaris 9 sparc sd behavior is required
2479 			 *
2480 			 * If first time through and sd_dtype_optical_bind
2481 			 * has not been set in /etc/system check properties
2482 			 */
2483 
2484 			if (sd_dtype_optical_bind  < 0) {
2485 				sd_dtype_optical_bind = ddi_prop_get_int
2486 				    (DDI_DEV_T_ANY, devi, 0,
2487 				    "optical-device-bind", 1);
2488 			}
2489 
2490 			if (sd_dtype_optical_bind == 0) {
2491 				rval = DDI_PROBE_FAILURE;
2492 			} else {
2493 				rval = DDI_PROBE_SUCCESS;
2494 			}
2495 			break;
2496 
2497 		case DTYPE_NOTPRESENT:
2498 		default:
2499 			rval = DDI_PROBE_FAILURE;
2500 			break;
2501 		}
2502 		break;
2503 	default:
2504 		rval = DDI_PROBE_PARTIAL;
2505 		break;
2506 	}
2507 
2508 	/*
2509 	 * This routine checks for resource allocation prior to freeing,
2510 	 * so it will take care of the "smart probing" case where a
2511 	 * scsi_probe() may or may not have been issued and will *not*
2512 	 * free previously-freed resources.
2513 	 */
2514 	scsi_unprobe(devp);
2515 	return (rval);
2516 }
2517 
2518 
2519 /*
2520  *    Function: sdinfo
2521  *
2522  * Description: This is the driver getinfo(9e) entry point function.
2523  * 		Given the device number, return the devinfo pointer from
2524  *		the scsi_device structure or the instance number
2525  *		associated with the dev_t.
2526  *
2527  *   Arguments: dip     - pointer to device info structure
2528  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2529  *			  DDI_INFO_DEVT2INSTANCE)
2530  *		arg     - driver dev_t
2531  *		resultp - user buffer for request response
2532  *
2533  * Return Code: DDI_SUCCESS
2534  *              DDI_FAILURE
2535  */
2536 /* ARGSUSED */
2537 static int
2538 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2539 {
2540 	struct sd_lun	*un;
2541 	dev_t		dev;
2542 	int		instance;
2543 	int		error;
2544 
2545 	switch (infocmd) {
2546 	case DDI_INFO_DEVT2DEVINFO:
2547 		dev = (dev_t)arg;
2548 		instance = SDUNIT(dev);
2549 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2550 			return (DDI_FAILURE);
2551 		}
2552 		*result = (void *) SD_DEVINFO(un);
2553 		error = DDI_SUCCESS;
2554 		break;
2555 	case DDI_INFO_DEVT2INSTANCE:
2556 		dev = (dev_t)arg;
2557 		instance = SDUNIT(dev);
2558 		*result = (void *)(uintptr_t)instance;
2559 		error = DDI_SUCCESS;
2560 		break;
2561 	default:
2562 		error = DDI_FAILURE;
2563 	}
2564 	return (error);
2565 }
2566 
2567 /*
2568  *    Function: sd_prop_op
2569  *
2570  * Description: This is the driver prop_op(9e) entry point function.
2571  *		Return the number of blocks for the partition in question
2572  *		or forward the request to the property facilities.
2573  *
2574  *   Arguments: dev       - device number
2575  *		dip       - pointer to device info structure
2576  *		prop_op   - property operator
2577  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2578  *		name      - pointer to property name
2579  *		valuep    - pointer or address of the user buffer
2580  *		lengthp   - property length
2581  *
2582  * Return Code: DDI_PROP_SUCCESS
2583  *              DDI_PROP_NOT_FOUND
2584  *              DDI_PROP_UNDEFINED
2585  *              DDI_PROP_NO_MEMORY
2586  *              DDI_PROP_BUF_TOO_SMALL
2587  */
2588 
2589 static int
2590 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2591 	char *name, caddr_t valuep, int *lengthp)
2592 {
2593 	int		instance = ddi_get_instance(dip);
2594 	struct sd_lun	*un;
2595 	uint64_t	nblocks64;
2596 	uint_t		dblk;
2597 
2598 	/*
2599 	 * Our dynamic properties are all device specific and size oriented.
2600 	 * Requests issued under conditions where size is valid are passed
2601 	 * to ddi_prop_op_nblocks with the size information, otherwise the
2602 	 * request is passed to ddi_prop_op. Size depends on valid geometry.
2603 	 */
2604 	un = ddi_get_soft_state(sd_state, instance);
2605 	if ((dev == DDI_DEV_T_ANY) || (un == NULL)) {
2606 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2607 		    name, valuep, lengthp));
2608 	} else if (!SD_IS_VALID_LABEL(un)) {
2609 		return (ddi_prop_op(dev, dip, prop_op, mod_flags, name,
2610 		    valuep, lengthp));
2611 	}
2612 
2613 	/* get nblocks value */
2614 	ASSERT(!mutex_owned(SD_MUTEX(un)));
2615 
2616 	(void) cmlb_partinfo(un->un_cmlbhandle, SDPART(dev),
2617 	    (diskaddr_t *)&nblocks64, NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
2618 
2619 	/* report size in target size blocks */
2620 	dblk = un->un_tgt_blocksize / un->un_sys_blocksize;
2621 	return (ddi_prop_op_nblocks_blksize(dev, dip, prop_op, mod_flags,
2622 	    name, valuep, lengthp, nblocks64 / dblk, un->un_tgt_blocksize));
2623 }
2624 
2625 /*
2626  * The following functions are for smart probing:
2627  * sd_scsi_probe_cache_init()
2628  * sd_scsi_probe_cache_fini()
2629  * sd_scsi_clear_probe_cache()
2630  * sd_scsi_probe_with_cache()
2631  */
2632 
2633 /*
2634  *    Function: sd_scsi_probe_cache_init
2635  *
2636  * Description: Initializes the probe response cache mutex and head pointer.
2637  *
2638  *     Context: Kernel thread context
2639  */
2640 
2641 static void
2642 sd_scsi_probe_cache_init(void)
2643 {
2644 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2645 	sd_scsi_probe_cache_head = NULL;
2646 }
2647 
2648 
2649 /*
2650  *    Function: sd_scsi_probe_cache_fini
2651  *
2652  * Description: Frees all resources associated with the probe response cache.
2653  *
2654  *     Context: Kernel thread context
2655  */
2656 
2657 static void
2658 sd_scsi_probe_cache_fini(void)
2659 {
2660 	struct sd_scsi_probe_cache *cp;
2661 	struct sd_scsi_probe_cache *ncp;
2662 
2663 	/* Clean up our smart probing linked list */
2664 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2665 		ncp = cp->next;
2666 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2667 	}
2668 	sd_scsi_probe_cache_head = NULL;
2669 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2670 }
2671 
2672 
2673 /*
2674  *    Function: sd_scsi_clear_probe_cache
2675  *
2676  * Description: This routine clears the probe response cache. This is
2677  *		done when open() returns ENXIO so that when deferred
2678  *		attach is attempted (possibly after a device has been
2679  *		turned on) we will retry the probe. Since we don't know
2680  *		which target we failed to open, we just clear the
2681  *		entire cache.
2682  *
2683  *     Context: Kernel thread context
2684  */
2685 
2686 static void
2687 sd_scsi_clear_probe_cache(void)
2688 {
2689 	struct sd_scsi_probe_cache	*cp;
2690 	int				i;
2691 
2692 	mutex_enter(&sd_scsi_probe_cache_mutex);
2693 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2694 		/*
2695 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2696 		 * force probing to be performed the next time
2697 		 * sd_scsi_probe_with_cache is called.
2698 		 */
2699 		for (i = 0; i < NTARGETS_WIDE; i++) {
2700 			cp->cache[i] = SCSIPROBE_EXISTS;
2701 		}
2702 	}
2703 	mutex_exit(&sd_scsi_probe_cache_mutex);
2704 }
2705 
2706 
2707 /*
2708  *    Function: sd_scsi_probe_with_cache
2709  *
2710  * Description: This routine implements support for a scsi device probe
2711  *		with cache. The driver maintains a cache of the target
2712  *		responses to scsi probes. If we get no response from a
2713  *		target during a probe inquiry, we remember that, and we
2714  *		avoid additional calls to scsi_probe on non-zero LUNs
2715  *		on the same target until the cache is cleared. By doing
2716  *		so we avoid the 1/4 sec selection timeout for nonzero
2717  *		LUNs. lun0 of a target is always probed.
2718  *
2719  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2720  *              waitfunc - indicates what the allocator routines should
2721  *			   do when resources are not available. This value
2722  *			   is passed on to scsi_probe() when that routine
2723  *			   is called.
2724  *
2725  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2726  *		otherwise the value returned by scsi_probe(9F).
2727  *
2728  *     Context: Kernel thread context
2729  */
2730 
2731 static int
2732 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2733 {
2734 	struct sd_scsi_probe_cache	*cp;
2735 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2736 	int		lun, tgt;
2737 
2738 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2739 	    SCSI_ADDR_PROP_LUN, 0);
2740 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2741 	    SCSI_ADDR_PROP_TARGET, -1);
2742 
2743 	/* Make sure caching enabled and target in range */
2744 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2745 		/* do it the old way (no cache) */
2746 		return (scsi_probe(devp, waitfn));
2747 	}
2748 
2749 	mutex_enter(&sd_scsi_probe_cache_mutex);
2750 
2751 	/* Find the cache for this scsi bus instance */
2752 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2753 		if (cp->pdip == pdip) {
2754 			break;
2755 		}
2756 	}
2757 
2758 	/* If we can't find a cache for this pdip, create one */
2759 	if (cp == NULL) {
2760 		int i;
2761 
2762 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
2763 		    KM_SLEEP);
2764 		cp->pdip = pdip;
2765 		cp->next = sd_scsi_probe_cache_head;
2766 		sd_scsi_probe_cache_head = cp;
2767 		for (i = 0; i < NTARGETS_WIDE; i++) {
2768 			cp->cache[i] = SCSIPROBE_EXISTS;
2769 		}
2770 	}
2771 
2772 	mutex_exit(&sd_scsi_probe_cache_mutex);
2773 
2774 	/* Recompute the cache for this target if LUN zero */
2775 	if (lun == 0) {
2776 		cp->cache[tgt] = SCSIPROBE_EXISTS;
2777 	}
2778 
2779 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
2780 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
2781 		return (SCSIPROBE_NORESP);
2782 	}
2783 
2784 	/* Do the actual probe; save & return the result */
2785 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
2786 }
2787 
2788 
2789 /*
2790  *    Function: sd_scsi_target_lun_init
2791  *
2792  * Description: Initializes the attached lun chain mutex and head pointer.
2793  *
2794  *     Context: Kernel thread context
2795  */
2796 
2797 static void
2798 sd_scsi_target_lun_init(void)
2799 {
2800 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
2801 	sd_scsi_target_lun_head = NULL;
2802 }
2803 
2804 
2805 /*
2806  *    Function: sd_scsi_target_lun_fini
2807  *
2808  * Description: Frees all resources associated with the attached lun
2809  *              chain
2810  *
2811  *     Context: Kernel thread context
2812  */
2813 
2814 static void
2815 sd_scsi_target_lun_fini(void)
2816 {
2817 	struct sd_scsi_hba_tgt_lun	*cp;
2818 	struct sd_scsi_hba_tgt_lun	*ncp;
2819 
2820 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
2821 		ncp = cp->next;
2822 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
2823 	}
2824 	sd_scsi_target_lun_head = NULL;
2825 	mutex_destroy(&sd_scsi_target_lun_mutex);
2826 }
2827 
2828 
2829 /*
2830  *    Function: sd_scsi_get_target_lun_count
2831  *
2832  * Description: This routine will check in the attached lun chain to see
2833  * 		how many luns are attached on the required SCSI controller
2834  * 		and target. Currently, some capabilities like tagged queue
2835  *		are supported per target based by HBA. So all luns in a
2836  *		target have the same capabilities. Based on this assumption,
2837  * 		sd should only set these capabilities once per target. This
2838  *		function is called when sd needs to decide how many luns
2839  *		already attached on a target.
2840  *
2841  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
2842  *			  controller device.
2843  *              target	- The target ID on the controller's SCSI bus.
2844  *
2845  * Return Code: The number of luns attached on the required target and
2846  *		controller.
2847  *		-1 if target ID is not in parallel SCSI scope or the given
2848  * 		dip is not in the chain.
2849  *
2850  *     Context: Kernel thread context
2851  */
2852 
2853 static int
2854 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
2855 {
2856 	struct sd_scsi_hba_tgt_lun	*cp;
2857 
2858 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
2859 		return (-1);
2860 	}
2861 
2862 	mutex_enter(&sd_scsi_target_lun_mutex);
2863 
2864 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2865 		if (cp->pdip == dip) {
2866 			break;
2867 		}
2868 	}
2869 
2870 	mutex_exit(&sd_scsi_target_lun_mutex);
2871 
2872 	if (cp == NULL) {
2873 		return (-1);
2874 	}
2875 
2876 	return (cp->nlun[target]);
2877 }
2878 
2879 
2880 /*
2881  *    Function: sd_scsi_update_lun_on_target
2882  *
2883  * Description: This routine is used to update the attached lun chain when a
2884  *		lun is attached or detached on a target.
2885  *
2886  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
2887  *                        controller device.
2888  *              target  - The target ID on the controller's SCSI bus.
2889  *		flag	- Indicate the lun is attached or detached.
2890  *
2891  *     Context: Kernel thread context
2892  */
2893 
2894 static void
2895 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
2896 {
2897 	struct sd_scsi_hba_tgt_lun	*cp;
2898 
2899 	mutex_enter(&sd_scsi_target_lun_mutex);
2900 
2901 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2902 		if (cp->pdip == dip) {
2903 			break;
2904 		}
2905 	}
2906 
2907 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
2908 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
2909 		    KM_SLEEP);
2910 		cp->pdip = dip;
2911 		cp->next = sd_scsi_target_lun_head;
2912 		sd_scsi_target_lun_head = cp;
2913 	}
2914 
2915 	mutex_exit(&sd_scsi_target_lun_mutex);
2916 
2917 	if (cp != NULL) {
2918 		if (flag == SD_SCSI_LUN_ATTACH) {
2919 			cp->nlun[target] ++;
2920 		} else {
2921 			cp->nlun[target] --;
2922 		}
2923 	}
2924 }
2925 
2926 
2927 /*
2928  *    Function: sd_spin_up_unit
2929  *
2930  * Description: Issues the following commands to spin-up the device:
2931  *		START STOP UNIT, and INQUIRY.
2932  *
2933  *   Arguments: un - driver soft state (unit) structure
2934  *
2935  * Return Code: 0 - success
2936  *		EIO - failure
2937  *		EACCES - reservation conflict
2938  *
2939  *     Context: Kernel thread context
2940  */
2941 
2942 static int
2943 sd_spin_up_unit(struct sd_lun *un)
2944 {
2945 	size_t	resid		= 0;
2946 	int	has_conflict	= FALSE;
2947 	uchar_t *bufaddr;
2948 
2949 	ASSERT(un != NULL);
2950 
2951 	/*
2952 	 * Send a throwaway START UNIT command.
2953 	 *
2954 	 * If we fail on this, we don't care presently what precisely
2955 	 * is wrong.  EMC's arrays will also fail this with a check
2956 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
2957 	 * we don't want to fail the attach because it may become
2958 	 * "active" later.
2959 	 */
2960 	if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START, SD_PATH_DIRECT)
2961 	    == EACCES)
2962 		has_conflict = TRUE;
2963 
2964 	/*
2965 	 * Send another INQUIRY command to the target. This is necessary for
2966 	 * non-removable media direct access devices because their INQUIRY data
2967 	 * may not be fully qualified until they are spun up (perhaps via the
2968 	 * START command above).  Note: This seems to be needed for some
2969 	 * legacy devices only.) The INQUIRY command should succeed even if a
2970 	 * Reservation Conflict is present.
2971 	 */
2972 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
2973 	if (sd_send_scsi_INQUIRY(un, bufaddr, SUN_INQSIZE, 0, 0, &resid) != 0) {
2974 		kmem_free(bufaddr, SUN_INQSIZE);
2975 		return (EIO);
2976 	}
2977 
2978 	/*
2979 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
2980 	 * Note that this routine does not return a failure here even if the
2981 	 * INQUIRY command did not return any data.  This is a legacy behavior.
2982 	 */
2983 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
2984 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
2985 	}
2986 
2987 	kmem_free(bufaddr, SUN_INQSIZE);
2988 
2989 	/* If we hit a reservation conflict above, tell the caller. */
2990 	if (has_conflict == TRUE) {
2991 		return (EACCES);
2992 	}
2993 
2994 	return (0);
2995 }
2996 
2997 #ifdef _LP64
2998 /*
2999  *    Function: sd_enable_descr_sense
3000  *
3001  * Description: This routine attempts to select descriptor sense format
3002  *		using the Control mode page.  Devices that support 64 bit
3003  *		LBAs (for >2TB luns) should also implement descriptor
3004  *		sense data so we will call this function whenever we see
3005  *		a lun larger than 2TB.  If for some reason the device
3006  *		supports 64 bit LBAs but doesn't support descriptor sense
3007  *		presumably the mode select will fail.  Everything will
3008  *		continue to work normally except that we will not get
3009  *		complete sense data for commands that fail with an LBA
3010  *		larger than 32 bits.
3011  *
3012  *   Arguments: un - driver soft state (unit) structure
3013  *
3014  *     Context: Kernel thread context only
3015  */
3016 
3017 static void
3018 sd_enable_descr_sense(struct sd_lun *un)
3019 {
3020 	uchar_t			*header;
3021 	struct mode_control_scsi3 *ctrl_bufp;
3022 	size_t			buflen;
3023 	size_t			bd_len;
3024 
3025 	/*
3026 	 * Read MODE SENSE page 0xA, Control Mode Page
3027 	 */
3028 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3029 	    sizeof (struct mode_control_scsi3);
3030 	header = kmem_zalloc(buflen, KM_SLEEP);
3031 	if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
3032 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT) != 0) {
3033 		SD_ERROR(SD_LOG_COMMON, un,
3034 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3035 		goto eds_exit;
3036 	}
3037 
3038 	/*
3039 	 * Determine size of Block Descriptors in order to locate
3040 	 * the mode page data. ATAPI devices return 0, SCSI devices
3041 	 * should return MODE_BLK_DESC_LENGTH.
3042 	 */
3043 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3044 
3045 	/* Clear the mode data length field for MODE SELECT */
3046 	((struct mode_header *)header)->length = 0;
3047 
3048 	ctrl_bufp = (struct mode_control_scsi3 *)
3049 	    (header + MODE_HEADER_LENGTH + bd_len);
3050 
3051 	/*
3052 	 * If the page length is smaller than the expected value,
3053 	 * the target device doesn't support D_SENSE. Bail out here.
3054 	 */
3055 	if (ctrl_bufp->mode_page.length <
3056 	    sizeof (struct mode_control_scsi3) - 2) {
3057 		SD_ERROR(SD_LOG_COMMON, un,
3058 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3059 		goto eds_exit;
3060 	}
3061 
3062 	/*
3063 	 * Clear PS bit for MODE SELECT
3064 	 */
3065 	ctrl_bufp->mode_page.ps = 0;
3066 
3067 	/*
3068 	 * Set D_SENSE to enable descriptor sense format.
3069 	 */
3070 	ctrl_bufp->d_sense = 1;
3071 
3072 	/*
3073 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3074 	 */
3075 	if (sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
3076 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT) != 0) {
3077 		SD_INFO(SD_LOG_COMMON, un,
3078 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3079 		goto eds_exit;
3080 	}
3081 
3082 eds_exit:
3083 	kmem_free(header, buflen);
3084 }
3085 
3086 /*
3087  *    Function: sd_reenable_dsense_task
3088  *
3089  * Description: Re-enable descriptor sense after device or bus reset
3090  *
3091  *     Context: Executes in a taskq() thread context
3092  */
3093 static void
3094 sd_reenable_dsense_task(void *arg)
3095 {
3096 	struct	sd_lun	*un = arg;
3097 
3098 	ASSERT(un != NULL);
3099 	sd_enable_descr_sense(un);
3100 }
3101 #endif /* _LP64 */
3102 
3103 /*
3104  *    Function: sd_set_mmc_caps
3105  *
3106  * Description: This routine determines if the device is MMC compliant and if
3107  *		the device supports CDDA via a mode sense of the CDVD
3108  *		capabilities mode page. Also checks if the device is a
3109  *		dvdram writable device.
3110  *
3111  *   Arguments: un - driver soft state (unit) structure
3112  *
3113  *     Context: Kernel thread context only
3114  */
3115 
3116 static void
3117 sd_set_mmc_caps(struct sd_lun *un)
3118 {
3119 	struct mode_header_grp2		*sense_mhp;
3120 	uchar_t				*sense_page;
3121 	caddr_t				buf;
3122 	int				bd_len;
3123 	int				status;
3124 	struct uscsi_cmd		com;
3125 	int				rtn;
3126 	uchar_t				*out_data_rw, *out_data_hd;
3127 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3128 
3129 	ASSERT(un != NULL);
3130 
3131 	/*
3132 	 * The flags which will be set in this function are - mmc compliant,
3133 	 * dvdram writable device, cdda support. Initialize them to FALSE
3134 	 * and if a capability is detected - it will be set to TRUE.
3135 	 */
3136 	un->un_f_mmc_cap = FALSE;
3137 	un->un_f_dvdram_writable_device = FALSE;
3138 	un->un_f_cfg_cdda = FALSE;
3139 
3140 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3141 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
3142 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3143 
3144 	if (status != 0) {
3145 		/* command failed; just return */
3146 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3147 		return;
3148 	}
3149 	/*
3150 	 * If the mode sense request for the CDROM CAPABILITIES
3151 	 * page (0x2A) succeeds the device is assumed to be MMC.
3152 	 */
3153 	un->un_f_mmc_cap = TRUE;
3154 
3155 	/* Get to the page data */
3156 	sense_mhp = (struct mode_header_grp2 *)buf;
3157 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3158 	    sense_mhp->bdesc_length_lo;
3159 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3160 		/*
3161 		 * We did not get back the expected block descriptor
3162 		 * length so we cannot determine if the device supports
3163 		 * CDDA. However, we still indicate the device is MMC
3164 		 * according to the successful response to the page
3165 		 * 0x2A mode sense request.
3166 		 */
3167 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3168 		    "sd_set_mmc_caps: Mode Sense returned "
3169 		    "invalid block descriptor length\n");
3170 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3171 		return;
3172 	}
3173 
3174 	/* See if read CDDA is supported */
3175 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3176 	    bd_len);
3177 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3178 
3179 	/* See if writing DVD RAM is supported. */
3180 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3181 	if (un->un_f_dvdram_writable_device == TRUE) {
3182 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3183 		return;
3184 	}
3185 
3186 	/*
3187 	 * If the device presents DVD or CD capabilities in the mode
3188 	 * page, we can return here since a RRD will not have
3189 	 * these capabilities.
3190 	 */
3191 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3192 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3193 		return;
3194 	}
3195 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3196 
3197 	/*
3198 	 * If un->un_f_dvdram_writable_device is still FALSE,
3199 	 * check for a Removable Rigid Disk (RRD).  A RRD
3200 	 * device is identified by the features RANDOM_WRITABLE and
3201 	 * HARDWARE_DEFECT_MANAGEMENT.
3202 	 */
3203 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3204 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3205 
3206 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3207 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3208 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3209 	if (rtn != 0) {
3210 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3211 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3212 		return;
3213 	}
3214 
3215 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3216 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3217 
3218 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3219 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3220 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3221 	if (rtn == 0) {
3222 		/*
3223 		 * We have good information, check for random writable
3224 		 * and hardware defect features.
3225 		 */
3226 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3227 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3228 			un->un_f_dvdram_writable_device = TRUE;
3229 		}
3230 	}
3231 
3232 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3233 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3234 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3235 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3236 }
3237 
3238 /*
3239  *    Function: sd_check_for_writable_cd
3240  *
3241  * Description: This routine determines if the media in the device is
3242  *		writable or not. It uses the get configuration command (0x46)
3243  *		to determine if the media is writable
3244  *
3245  *   Arguments: un - driver soft state (unit) structure
3246  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3247  *                           chain and the normal command waitq, or
3248  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3249  *                           "direct" chain and bypass the normal command
3250  *                           waitq.
3251  *
3252  *     Context: Never called at interrupt context.
3253  */
3254 
3255 static void
3256 sd_check_for_writable_cd(struct sd_lun *un, int path_flag)
3257 {
3258 	struct uscsi_cmd		com;
3259 	uchar_t				*out_data;
3260 	uchar_t				*rqbuf;
3261 	int				rtn;
3262 	uchar_t				*out_data_rw, *out_data_hd;
3263 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3264 	struct mode_header_grp2		*sense_mhp;
3265 	uchar_t				*sense_page;
3266 	caddr_t				buf;
3267 	int				bd_len;
3268 	int				status;
3269 
3270 	ASSERT(un != NULL);
3271 	ASSERT(mutex_owned(SD_MUTEX(un)));
3272 
3273 	/*
3274 	 * Initialize the writable media to false, if configuration info.
3275 	 * tells us otherwise then only we will set it.
3276 	 */
3277 	un->un_f_mmc_writable_media = FALSE;
3278 	mutex_exit(SD_MUTEX(un));
3279 
3280 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3281 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3282 
3283 	rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf, SENSE_LENGTH,
3284 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3285 
3286 	mutex_enter(SD_MUTEX(un));
3287 	if (rtn == 0) {
3288 		/*
3289 		 * We have good information, check for writable DVD.
3290 		 */
3291 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3292 			un->un_f_mmc_writable_media = TRUE;
3293 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3294 			kmem_free(rqbuf, SENSE_LENGTH);
3295 			return;
3296 		}
3297 	}
3298 
3299 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3300 	kmem_free(rqbuf, SENSE_LENGTH);
3301 
3302 	/*
3303 	 * Determine if this is a RRD type device.
3304 	 */
3305 	mutex_exit(SD_MUTEX(un));
3306 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3307 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
3308 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3309 	mutex_enter(SD_MUTEX(un));
3310 	if (status != 0) {
3311 		/* command failed; just return */
3312 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3313 		return;
3314 	}
3315 
3316 	/* Get to the page data */
3317 	sense_mhp = (struct mode_header_grp2 *)buf;
3318 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3319 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3320 		/*
3321 		 * We did not get back the expected block descriptor length so
3322 		 * we cannot check the mode page.
3323 		 */
3324 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3325 		    "sd_check_for_writable_cd: Mode Sense returned "
3326 		    "invalid block descriptor length\n");
3327 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3328 		return;
3329 	}
3330 
3331 	/*
3332 	 * If the device presents DVD or CD capabilities in the mode
3333 	 * page, we can return here since a RRD device will not have
3334 	 * these capabilities.
3335 	 */
3336 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3337 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3338 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3339 		return;
3340 	}
3341 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3342 
3343 	/*
3344 	 * If un->un_f_mmc_writable_media is still FALSE,
3345 	 * check for RRD type media.  A RRD device is identified
3346 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3347 	 */
3348 	mutex_exit(SD_MUTEX(un));
3349 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3350 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3351 
3352 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3353 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3354 	    RANDOM_WRITABLE, path_flag);
3355 	if (rtn != 0) {
3356 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3357 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3358 		mutex_enter(SD_MUTEX(un));
3359 		return;
3360 	}
3361 
3362 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3363 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3364 
3365 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3366 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3367 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3368 	mutex_enter(SD_MUTEX(un));
3369 	if (rtn == 0) {
3370 		/*
3371 		 * We have good information, check for random writable
3372 		 * and hardware defect features as current.
3373 		 */
3374 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3375 		    (out_data_rw[10] & 0x1) &&
3376 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3377 		    (out_data_hd[10] & 0x1)) {
3378 			un->un_f_mmc_writable_media = TRUE;
3379 		}
3380 	}
3381 
3382 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3383 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3384 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3385 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3386 }
3387 
3388 /*
3389  *    Function: sd_read_unit_properties
3390  *
3391  * Description: The following implements a property lookup mechanism.
3392  *		Properties for particular disks (keyed on vendor, model
3393  *		and rev numbers) are sought in the sd.conf file via
3394  *		sd_process_sdconf_file(), and if not found there, are
3395  *		looked for in a list hardcoded in this driver via
3396  *		sd_process_sdconf_table() Once located the properties
3397  *		are used to update the driver unit structure.
3398  *
3399  *   Arguments: un - driver soft state (unit) structure
3400  */
3401 
3402 static void
3403 sd_read_unit_properties(struct sd_lun *un)
3404 {
3405 	/*
3406 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3407 	 * the "sd-config-list" property (from the sd.conf file) or if
3408 	 * there was not a match for the inquiry vid/pid. If this event
3409 	 * occurs the static driver configuration table is searched for
3410 	 * a match.
3411 	 */
3412 	ASSERT(un != NULL);
3413 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3414 		sd_process_sdconf_table(un);
3415 	}
3416 
3417 	/* check for LSI device */
3418 	sd_is_lsi(un);
3419 
3420 
3421 }
3422 
3423 
3424 /*
3425  *    Function: sd_process_sdconf_file
3426  *
3427  * Description: Use ddi_getlongprop to obtain the properties from the
3428  *		driver's config file (ie, sd.conf) and update the driver
3429  *		soft state structure accordingly.
3430  *
3431  *   Arguments: un - driver soft state (unit) structure
3432  *
3433  * Return Code: SD_SUCCESS - The properties were successfully set according
3434  *			     to the driver configuration file.
3435  *		SD_FAILURE - The driver config list was not obtained or
3436  *			     there was no vid/pid match. This indicates that
3437  *			     the static config table should be used.
3438  *
3439  * The config file has a property, "sd-config-list", which consists of
3440  * one or more duplets as follows:
3441  *
3442  *  sd-config-list=
3443  *	<duplet>,
3444  *	[<duplet>,]
3445  *	[<duplet>];
3446  *
3447  * The structure of each duplet is as follows:
3448  *
3449  *  <duplet>:= <vid+pid>,<data-property-name_list>
3450  *
3451  * The first entry of the duplet is the device ID string (the concatenated
3452  * vid & pid; not to be confused with a device_id).  This is defined in
3453  * the same way as in the sd_disk_table.
3454  *
3455  * The second part of the duplet is a string that identifies a
3456  * data-property-name-list. The data-property-name-list is defined as
3457  * follows:
3458  *
3459  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3460  *
3461  * The syntax of <data-property-name> depends on the <version> field.
3462  *
3463  * If version = SD_CONF_VERSION_1 we have the following syntax:
3464  *
3465  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3466  *
3467  * where the prop0 value will be used to set prop0 if bit0 set in the
3468  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3469  *
3470  */
3471 
3472 static int
3473 sd_process_sdconf_file(struct sd_lun *un)
3474 {
3475 	char	*config_list = NULL;
3476 	int	config_list_len;
3477 	int	len;
3478 	int	dupletlen = 0;
3479 	char	*vidptr;
3480 	int	vidlen;
3481 	char	*dnlist_ptr;
3482 	char	*dataname_ptr;
3483 	int	dnlist_len;
3484 	int	dataname_len;
3485 	int	*data_list;
3486 	int	data_list_len;
3487 	int	rval = SD_FAILURE;
3488 	int	i;
3489 
3490 	ASSERT(un != NULL);
3491 
3492 	/* Obtain the configuration list associated with the .conf file */
3493 	if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), DDI_PROP_DONTPASS,
3494 	    sd_config_list, (caddr_t)&config_list, &config_list_len)
3495 	    != DDI_PROP_SUCCESS) {
3496 		return (SD_FAILURE);
3497 	}
3498 
3499 	/*
3500 	 * Compare vids in each duplet to the inquiry vid - if a match is
3501 	 * made, get the data value and update the soft state structure
3502 	 * accordingly.
3503 	 *
3504 	 * Note: This algorithm is complex and difficult to maintain. It should
3505 	 * be replaced with a more robust implementation.
3506 	 */
3507 	for (len = config_list_len, vidptr = config_list; len > 0;
3508 	    vidptr += dupletlen, len -= dupletlen) {
3509 		/*
3510 		 * Note: The assumption here is that each vid entry is on
3511 		 * a unique line from its associated duplet.
3512 		 */
3513 		vidlen = dupletlen = (int)strlen(vidptr);
3514 		if ((vidlen == 0) ||
3515 		    (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS)) {
3516 			dupletlen++;
3517 			continue;
3518 		}
3519 
3520 		/*
3521 		 * dnlist contains 1 or more blank separated
3522 		 * data-property-name entries
3523 		 */
3524 		dnlist_ptr = vidptr + vidlen + 1;
3525 		dnlist_len = (int)strlen(dnlist_ptr);
3526 		dupletlen += dnlist_len + 2;
3527 
3528 		/*
3529 		 * Set a pointer for the first data-property-name
3530 		 * entry in the list
3531 		 */
3532 		dataname_ptr = dnlist_ptr;
3533 		dataname_len = 0;
3534 
3535 		/*
3536 		 * Loop through all data-property-name entries in the
3537 		 * data-property-name-list setting the properties for each.
3538 		 */
3539 		while (dataname_len < dnlist_len) {
3540 			int version;
3541 
3542 			/*
3543 			 * Determine the length of the current
3544 			 * data-property-name entry by indexing until a
3545 			 * blank or NULL is encountered. When the space is
3546 			 * encountered reset it to a NULL for compliance
3547 			 * with ddi_getlongprop().
3548 			 */
3549 			for (i = 0; ((dataname_ptr[i] != ' ') &&
3550 			    (dataname_ptr[i] != '\0')); i++) {
3551 				;
3552 			}
3553 
3554 			dataname_len += i;
3555 			/* If not null terminated, Make it so */
3556 			if (dataname_ptr[i] == ' ') {
3557 				dataname_ptr[i] = '\0';
3558 			}
3559 			dataname_len++;
3560 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3561 			    "sd_process_sdconf_file: disk:%s, data:%s\n",
3562 			    vidptr, dataname_ptr);
3563 
3564 			/* Get the data list */
3565 			if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), 0,
3566 			    dataname_ptr, (caddr_t)&data_list, &data_list_len)
3567 			    != DDI_PROP_SUCCESS) {
3568 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3569 				    "sd_process_sdconf_file: data property (%s)"
3570 				    " has no value\n", dataname_ptr);
3571 				dataname_ptr = dnlist_ptr + dataname_len;
3572 				continue;
3573 			}
3574 
3575 			version = data_list[0];
3576 
3577 			if (version == SD_CONF_VERSION_1) {
3578 				sd_tunables values;
3579 
3580 				/* Set the properties */
3581 				if (sd_chk_vers1_data(un, data_list[1],
3582 				    &data_list[2], data_list_len, dataname_ptr)
3583 				    == SD_SUCCESS) {
3584 					sd_get_tunables_from_conf(un,
3585 					    data_list[1], &data_list[2],
3586 					    &values);
3587 					sd_set_vers1_properties(un,
3588 					    data_list[1], &values);
3589 					rval = SD_SUCCESS;
3590 				} else {
3591 					rval = SD_FAILURE;
3592 				}
3593 			} else {
3594 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3595 				    "data property %s version 0x%x is invalid.",
3596 				    dataname_ptr, version);
3597 				rval = SD_FAILURE;
3598 			}
3599 			kmem_free(data_list, data_list_len);
3600 			dataname_ptr = dnlist_ptr + dataname_len;
3601 		}
3602 	}
3603 
3604 	/* free up the memory allocated by ddi_getlongprop */
3605 	if (config_list) {
3606 		kmem_free(config_list, config_list_len);
3607 	}
3608 
3609 	return (rval);
3610 }
3611 
3612 /*
3613  *    Function: sd_get_tunables_from_conf()
3614  *
3615  *
3616  *    This function reads the data list from the sd.conf file and pulls
3617  *    the values that can have numeric values as arguments and places
3618  *    the values in the appropriate sd_tunables member.
3619  *    Since the order of the data list members varies across platforms
3620  *    This function reads them from the data list in a platform specific
3621  *    order and places them into the correct sd_tunable member that is
3622  *    consistent across all platforms.
3623  */
3624 static void
3625 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
3626     sd_tunables *values)
3627 {
3628 	int i;
3629 	int mask;
3630 
3631 	bzero(values, sizeof (sd_tunables));
3632 
3633 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3634 
3635 		mask = 1 << i;
3636 		if (mask > flags) {
3637 			break;
3638 		}
3639 
3640 		switch (mask & flags) {
3641 		case 0:	/* This mask bit not set in flags */
3642 			continue;
3643 		case SD_CONF_BSET_THROTTLE:
3644 			values->sdt_throttle = data_list[i];
3645 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3646 			    "sd_get_tunables_from_conf: throttle = %d\n",
3647 			    values->sdt_throttle);
3648 			break;
3649 		case SD_CONF_BSET_CTYPE:
3650 			values->sdt_ctype = data_list[i];
3651 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3652 			    "sd_get_tunables_from_conf: ctype = %d\n",
3653 			    values->sdt_ctype);
3654 			break;
3655 		case SD_CONF_BSET_NRR_COUNT:
3656 			values->sdt_not_rdy_retries = data_list[i];
3657 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3658 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
3659 			    values->sdt_not_rdy_retries);
3660 			break;
3661 		case SD_CONF_BSET_BSY_RETRY_COUNT:
3662 			values->sdt_busy_retries = data_list[i];
3663 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3664 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
3665 			    values->sdt_busy_retries);
3666 			break;
3667 		case SD_CONF_BSET_RST_RETRIES:
3668 			values->sdt_reset_retries = data_list[i];
3669 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3670 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
3671 			    values->sdt_reset_retries);
3672 			break;
3673 		case SD_CONF_BSET_RSV_REL_TIME:
3674 			values->sdt_reserv_rel_time = data_list[i];
3675 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3676 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
3677 			    values->sdt_reserv_rel_time);
3678 			break;
3679 		case SD_CONF_BSET_MIN_THROTTLE:
3680 			values->sdt_min_throttle = data_list[i];
3681 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3682 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
3683 			    values->sdt_min_throttle);
3684 			break;
3685 		case SD_CONF_BSET_DISKSORT_DISABLED:
3686 			values->sdt_disk_sort_dis = data_list[i];
3687 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3688 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
3689 			    values->sdt_disk_sort_dis);
3690 			break;
3691 		case SD_CONF_BSET_LUN_RESET_ENABLED:
3692 			values->sdt_lun_reset_enable = data_list[i];
3693 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3694 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
3695 			    "\n", values->sdt_lun_reset_enable);
3696 			break;
3697 		}
3698 	}
3699 }
3700 
3701 /*
3702  *    Function: sd_process_sdconf_table
3703  *
3704  * Description: Search the static configuration table for a match on the
3705  *		inquiry vid/pid and update the driver soft state structure
3706  *		according to the table property values for the device.
3707  *
3708  *		The form of a configuration table entry is:
3709  *		  <vid+pid>,<flags>,<property-data>
3710  *		  "SEAGATE ST42400N",1,63,0,0			(Fibre)
3711  *		  "SEAGATE ST42400N",1,63,0,0,0,0		(Sparc)
3712  *		  "SEAGATE ST42400N",1,63,0,0,0,0,0,0,0,0,0,0	(Intel)
3713  *
3714  *   Arguments: un - driver soft state (unit) structure
3715  */
3716 
3717 static void
3718 sd_process_sdconf_table(struct sd_lun *un)
3719 {
3720 	char	*id = NULL;
3721 	int	table_index;
3722 	int	idlen;
3723 
3724 	ASSERT(un != NULL);
3725 	for (table_index = 0; table_index < sd_disk_table_size;
3726 	    table_index++) {
3727 		id = sd_disk_table[table_index].device_id;
3728 		idlen = strlen(id);
3729 		if (idlen == 0) {
3730 			continue;
3731 		}
3732 
3733 		/*
3734 		 * The static configuration table currently does not
3735 		 * implement version 10 properties. Additionally,
3736 		 * multiple data-property-name entries are not
3737 		 * implemented in the static configuration table.
3738 		 */
3739 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
3740 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3741 			    "sd_process_sdconf_table: disk %s\n", id);
3742 			sd_set_vers1_properties(un,
3743 			    sd_disk_table[table_index].flags,
3744 			    sd_disk_table[table_index].properties);
3745 			break;
3746 		}
3747 	}
3748 }
3749 
3750 
3751 /*
3752  *    Function: sd_sdconf_id_match
3753  *
3754  * Description: This local function implements a case sensitive vid/pid
3755  *		comparison as well as the boundary cases of wild card and
3756  *		multiple blanks.
3757  *
3758  *		Note: An implicit assumption made here is that the scsi
3759  *		inquiry structure will always keep the vid, pid and
3760  *		revision strings in consecutive sequence, so they can be
3761  *		read as a single string. If this assumption is not the
3762  *		case, a separate string, to be used for the check, needs
3763  *		to be built with these strings concatenated.
3764  *
3765  *   Arguments: un - driver soft state (unit) structure
3766  *		id - table or config file vid/pid
3767  *		idlen  - length of the vid/pid (bytes)
3768  *
3769  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3770  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3771  */
3772 
3773 static int
3774 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
3775 {
3776 	struct scsi_inquiry	*sd_inq;
3777 	int 			rval = SD_SUCCESS;
3778 
3779 	ASSERT(un != NULL);
3780 	sd_inq = un->un_sd->sd_inq;
3781 	ASSERT(id != NULL);
3782 
3783 	/*
3784 	 * We use the inq_vid as a pointer to a buffer containing the
3785 	 * vid and pid and use the entire vid/pid length of the table
3786 	 * entry for the comparison. This works because the inq_pid
3787 	 * data member follows inq_vid in the scsi_inquiry structure.
3788 	 */
3789 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
3790 		/*
3791 		 * The user id string is compared to the inquiry vid/pid
3792 		 * using a case insensitive comparison and ignoring
3793 		 * multiple spaces.
3794 		 */
3795 		rval = sd_blank_cmp(un, id, idlen);
3796 		if (rval != SD_SUCCESS) {
3797 			/*
3798 			 * User id strings that start and end with a "*"
3799 			 * are a special case. These do not have a
3800 			 * specific vendor, and the product string can
3801 			 * appear anywhere in the 16 byte PID portion of
3802 			 * the inquiry data. This is a simple strstr()
3803 			 * type search for the user id in the inquiry data.
3804 			 */
3805 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
3806 				char	*pidptr = &id[1];
3807 				int	i;
3808 				int	j;
3809 				int	pidstrlen = idlen - 2;
3810 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
3811 				    pidstrlen;
3812 
3813 				if (j < 0) {
3814 					return (SD_FAILURE);
3815 				}
3816 				for (i = 0; i < j; i++) {
3817 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
3818 					    pidptr, pidstrlen) == 0) {
3819 						rval = SD_SUCCESS;
3820 						break;
3821 					}
3822 				}
3823 			}
3824 		}
3825 	}
3826 	return (rval);
3827 }
3828 
3829 
3830 /*
3831  *    Function: sd_blank_cmp
3832  *
3833  * Description: If the id string starts and ends with a space, treat
3834  *		multiple consecutive spaces as equivalent to a single
3835  *		space. For example, this causes a sd_disk_table entry
3836  *		of " NEC CDROM " to match a device's id string of
3837  *		"NEC       CDROM".
3838  *
3839  *		Note: The success exit condition for this routine is if
3840  *		the pointer to the table entry is '\0' and the cnt of
3841  *		the inquiry length is zero. This will happen if the inquiry
3842  *		string returned by the device is padded with spaces to be
3843  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
3844  *		SCSI spec states that the inquiry string is to be padded with
3845  *		spaces.
3846  *
3847  *   Arguments: un - driver soft state (unit) structure
3848  *		id - table or config file vid/pid
3849  *		idlen  - length of the vid/pid (bytes)
3850  *
3851  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3852  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3853  */
3854 
3855 static int
3856 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
3857 {
3858 	char		*p1;
3859 	char		*p2;
3860 	int		cnt;
3861 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
3862 	    sizeof (SD_INQUIRY(un)->inq_pid);
3863 
3864 	ASSERT(un != NULL);
3865 	p2 = un->un_sd->sd_inq->inq_vid;
3866 	ASSERT(id != NULL);
3867 	p1 = id;
3868 
3869 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
3870 		/*
3871 		 * Note: string p1 is terminated by a NUL but string p2
3872 		 * isn't.  The end of p2 is determined by cnt.
3873 		 */
3874 		for (;;) {
3875 			/* skip over any extra blanks in both strings */
3876 			while ((*p1 != '\0') && (*p1 == ' ')) {
3877 				p1++;
3878 			}
3879 			while ((cnt != 0) && (*p2 == ' ')) {
3880 				p2++;
3881 				cnt--;
3882 			}
3883 
3884 			/* compare the two strings */
3885 			if ((cnt == 0) ||
3886 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
3887 				break;
3888 			}
3889 			while ((cnt > 0) &&
3890 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
3891 				p1++;
3892 				p2++;
3893 				cnt--;
3894 			}
3895 		}
3896 	}
3897 
3898 	/* return SD_SUCCESS if both strings match */
3899 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
3900 }
3901 
3902 
3903 /*
3904  *    Function: sd_chk_vers1_data
3905  *
3906  * Description: Verify the version 1 device properties provided by the
3907  *		user via the configuration file
3908  *
3909  *   Arguments: un	     - driver soft state (unit) structure
3910  *		flags	     - integer mask indicating properties to be set
3911  *		prop_list    - integer list of property values
3912  *		list_len     - length of user provided data
3913  *
3914  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
3915  *		SD_FAILURE - Indicates the user provided data is invalid
3916  */
3917 
3918 static int
3919 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
3920     int list_len, char *dataname_ptr)
3921 {
3922 	int i;
3923 	int mask = 1;
3924 	int index = 0;
3925 
3926 	ASSERT(un != NULL);
3927 
3928 	/* Check for a NULL property name and list */
3929 	if (dataname_ptr == NULL) {
3930 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3931 		    "sd_chk_vers1_data: NULL data property name.");
3932 		return (SD_FAILURE);
3933 	}
3934 	if (prop_list == NULL) {
3935 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3936 		    "sd_chk_vers1_data: %s NULL data property list.",
3937 		    dataname_ptr);
3938 		return (SD_FAILURE);
3939 	}
3940 
3941 	/* Display a warning if undefined bits are set in the flags */
3942 	if (flags & ~SD_CONF_BIT_MASK) {
3943 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3944 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
3945 		    "Properties not set.",
3946 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
3947 		return (SD_FAILURE);
3948 	}
3949 
3950 	/*
3951 	 * Verify the length of the list by identifying the highest bit set
3952 	 * in the flags and validating that the property list has a length
3953 	 * up to the index of this bit.
3954 	 */
3955 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3956 		if (flags & mask) {
3957 			index++;
3958 		}
3959 		mask = 1 << i;
3960 	}
3961 	if ((list_len / sizeof (int)) < (index + 2)) {
3962 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3963 		    "sd_chk_vers1_data: "
3964 		    "Data property list %s size is incorrect. "
3965 		    "Properties not set.", dataname_ptr);
3966 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
3967 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
3968 		return (SD_FAILURE);
3969 	}
3970 	return (SD_SUCCESS);
3971 }
3972 
3973 
3974 /*
3975  *    Function: sd_set_vers1_properties
3976  *
3977  * Description: Set version 1 device properties based on a property list
3978  *		retrieved from the driver configuration file or static
3979  *		configuration table. Version 1 properties have the format:
3980  *
3981  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3982  *
3983  *		where the prop0 value will be used to set prop0 if bit0
3984  *		is set in the flags
3985  *
3986  *   Arguments: un	     - driver soft state (unit) structure
3987  *		flags	     - integer mask indicating properties to be set
3988  *		prop_list    - integer list of property values
3989  */
3990 
3991 static void
3992 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
3993 {
3994 	ASSERT(un != NULL);
3995 
3996 	/*
3997 	 * Set the flag to indicate cache is to be disabled. An attempt
3998 	 * to disable the cache via sd_cache_control() will be made
3999 	 * later during attach once the basic initialization is complete.
4000 	 */
4001 	if (flags & SD_CONF_BSET_NOCACHE) {
4002 		un->un_f_opt_disable_cache = TRUE;
4003 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4004 		    "sd_set_vers1_properties: caching disabled flag set\n");
4005 	}
4006 
4007 	/* CD-specific configuration parameters */
4008 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4009 		un->un_f_cfg_playmsf_bcd = TRUE;
4010 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4011 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4012 	}
4013 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4014 		un->un_f_cfg_readsub_bcd = TRUE;
4015 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4016 		    "sd_set_vers1_properties: readsub_bcd set\n");
4017 	}
4018 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4019 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4020 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4021 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4022 	}
4023 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4024 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4025 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4026 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4027 	}
4028 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4029 		un->un_f_cfg_no_read_header = TRUE;
4030 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4031 		    "sd_set_vers1_properties: no_read_header set\n");
4032 	}
4033 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4034 		un->un_f_cfg_read_cd_xd4 = TRUE;
4035 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4036 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4037 	}
4038 
4039 	/* Support for devices which do not have valid/unique serial numbers */
4040 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4041 		un->un_f_opt_fab_devid = TRUE;
4042 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4043 		    "sd_set_vers1_properties: fab_devid bit set\n");
4044 	}
4045 
4046 	/* Support for user throttle configuration */
4047 	if (flags & SD_CONF_BSET_THROTTLE) {
4048 		ASSERT(prop_list != NULL);
4049 		un->un_saved_throttle = un->un_throttle =
4050 		    prop_list->sdt_throttle;
4051 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4052 		    "sd_set_vers1_properties: throttle set to %d\n",
4053 		    prop_list->sdt_throttle);
4054 	}
4055 
4056 	/* Set the per disk retry count according to the conf file or table. */
4057 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4058 		ASSERT(prop_list != NULL);
4059 		if (prop_list->sdt_not_rdy_retries) {
4060 			un->un_notready_retry_count =
4061 			    prop_list->sdt_not_rdy_retries;
4062 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4063 			    "sd_set_vers1_properties: not ready retry count"
4064 			    " set to %d\n", un->un_notready_retry_count);
4065 		}
4066 	}
4067 
4068 	/* The controller type is reported for generic disk driver ioctls */
4069 	if (flags & SD_CONF_BSET_CTYPE) {
4070 		ASSERT(prop_list != NULL);
4071 		switch (prop_list->sdt_ctype) {
4072 		case CTYPE_CDROM:
4073 			un->un_ctype = prop_list->sdt_ctype;
4074 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4075 			    "sd_set_vers1_properties: ctype set to "
4076 			    "CTYPE_CDROM\n");
4077 			break;
4078 		case CTYPE_CCS:
4079 			un->un_ctype = prop_list->sdt_ctype;
4080 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4081 			    "sd_set_vers1_properties: ctype set to "
4082 			    "CTYPE_CCS\n");
4083 			break;
4084 		case CTYPE_ROD:		/* RW optical */
4085 			un->un_ctype = prop_list->sdt_ctype;
4086 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4087 			    "sd_set_vers1_properties: ctype set to "
4088 			    "CTYPE_ROD\n");
4089 			break;
4090 		default:
4091 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4092 			    "sd_set_vers1_properties: Could not set "
4093 			    "invalid ctype value (%d)",
4094 			    prop_list->sdt_ctype);
4095 		}
4096 	}
4097 
4098 	/* Purple failover timeout */
4099 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4100 		ASSERT(prop_list != NULL);
4101 		un->un_busy_retry_count =
4102 		    prop_list->sdt_busy_retries;
4103 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4104 		    "sd_set_vers1_properties: "
4105 		    "busy retry count set to %d\n",
4106 		    un->un_busy_retry_count);
4107 	}
4108 
4109 	/* Purple reset retry count */
4110 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4111 		ASSERT(prop_list != NULL);
4112 		un->un_reset_retry_count =
4113 		    prop_list->sdt_reset_retries;
4114 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4115 		    "sd_set_vers1_properties: "
4116 		    "reset retry count set to %d\n",
4117 		    un->un_reset_retry_count);
4118 	}
4119 
4120 	/* Purple reservation release timeout */
4121 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4122 		ASSERT(prop_list != NULL);
4123 		un->un_reserve_release_time =
4124 		    prop_list->sdt_reserv_rel_time;
4125 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4126 		    "sd_set_vers1_properties: "
4127 		    "reservation release timeout set to %d\n",
4128 		    un->un_reserve_release_time);
4129 	}
4130 
4131 	/*
4132 	 * Driver flag telling the driver to verify that no commands are pending
4133 	 * for a device before issuing a Test Unit Ready. This is a workaround
4134 	 * for a firmware bug in some Seagate eliteI drives.
4135 	 */
4136 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4137 		un->un_f_cfg_tur_check = TRUE;
4138 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4139 		    "sd_set_vers1_properties: tur queue check set\n");
4140 	}
4141 
4142 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4143 		un->un_min_throttle = prop_list->sdt_min_throttle;
4144 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4145 		    "sd_set_vers1_properties: min throttle set to %d\n",
4146 		    un->un_min_throttle);
4147 	}
4148 
4149 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4150 		un->un_f_disksort_disabled =
4151 		    (prop_list->sdt_disk_sort_dis != 0) ?
4152 		    TRUE : FALSE;
4153 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4154 		    "sd_set_vers1_properties: disksort disabled "
4155 		    "flag set to %d\n",
4156 		    prop_list->sdt_disk_sort_dis);
4157 	}
4158 
4159 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4160 		un->un_f_lun_reset_enabled =
4161 		    (prop_list->sdt_lun_reset_enable != 0) ?
4162 		    TRUE : FALSE;
4163 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4164 		    "sd_set_vers1_properties: lun reset enabled "
4165 		    "flag set to %d\n",
4166 		    prop_list->sdt_lun_reset_enable);
4167 	}
4168 
4169 	/*
4170 	 * Validate the throttle values.
4171 	 * If any of the numbers are invalid, set everything to defaults.
4172 	 */
4173 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4174 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4175 	    (un->un_min_throttle > un->un_throttle)) {
4176 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4177 		un->un_min_throttle = sd_min_throttle;
4178 	}
4179 }
4180 
4181 /*
4182  *   Function: sd_is_lsi()
4183  *
4184  *   Description: Check for lsi devices, step through the static device
4185  *	table to match vid/pid.
4186  *
4187  *   Args: un - ptr to sd_lun
4188  *
4189  *   Notes:  When creating new LSI property, need to add the new LSI property
4190  *		to this function.
4191  */
4192 static void
4193 sd_is_lsi(struct sd_lun *un)
4194 {
4195 	char	*id = NULL;
4196 	int	table_index;
4197 	int	idlen;
4198 	void	*prop;
4199 
4200 	ASSERT(un != NULL);
4201 	for (table_index = 0; table_index < sd_disk_table_size;
4202 	    table_index++) {
4203 		id = sd_disk_table[table_index].device_id;
4204 		idlen = strlen(id);
4205 		if (idlen == 0) {
4206 			continue;
4207 		}
4208 
4209 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4210 			prop = sd_disk_table[table_index].properties;
4211 			if (prop == &lsi_properties ||
4212 			    prop == &lsi_oem_properties ||
4213 			    prop == &lsi_properties_scsi ||
4214 			    prop == &symbios_properties) {
4215 				un->un_f_cfg_is_lsi = TRUE;
4216 			}
4217 			break;
4218 		}
4219 	}
4220 }
4221 
4222 /*
4223  *    Function: sd_get_physical_geometry
4224  *
4225  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4226  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4227  *		target, and use this information to initialize the physical
4228  *		geometry cache specified by pgeom_p.
4229  *
4230  *		MODE SENSE is an optional command, so failure in this case
4231  *		does not necessarily denote an error. We want to use the
4232  *		MODE SENSE commands to derive the physical geometry of the
4233  *		device, but if either command fails, the logical geometry is
4234  *		used as the fallback for disk label geometry in cmlb.
4235  *
4236  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4237  *		have already been initialized for the current target and
4238  *		that the current values be passed as args so that we don't
4239  *		end up ever trying to use -1 as a valid value. This could
4240  *		happen if either value is reset while we're not holding
4241  *		the mutex.
4242  *
4243  *   Arguments: un - driver soft state (unit) structure
4244  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4245  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4246  *			to use the USCSI "direct" chain and bypass the normal
4247  *			command waitq.
4248  *
4249  *     Context: Kernel thread only (can sleep).
4250  */
4251 
4252 static int
4253 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4254 	diskaddr_t capacity, int lbasize, int path_flag)
4255 {
4256 	struct	mode_format	*page3p;
4257 	struct	mode_geometry	*page4p;
4258 	struct	mode_header	*headerp;
4259 	int	sector_size;
4260 	int	nsect;
4261 	int	nhead;
4262 	int	ncyl;
4263 	int	intrlv;
4264 	int	spc;
4265 	diskaddr_t	modesense_capacity;
4266 	int	rpm;
4267 	int	bd_len;
4268 	int	mode_header_length;
4269 	uchar_t	*p3bufp;
4270 	uchar_t	*p4bufp;
4271 	int	cdbsize;
4272 	int 	ret = EIO;
4273 
4274 	ASSERT(un != NULL);
4275 
4276 	if (lbasize == 0) {
4277 		if (ISCD(un)) {
4278 			lbasize = 2048;
4279 		} else {
4280 			lbasize = un->un_sys_blocksize;
4281 		}
4282 	}
4283 	pgeom_p->g_secsize = (unsigned short)lbasize;
4284 
4285 	/*
4286 	 * If the unit is a cd/dvd drive MODE SENSE page three
4287 	 * and MODE SENSE page four are reserved (see SBC spec
4288 	 * and MMC spec). To prevent soft errors just return
4289 	 * using the default LBA size.
4290 	 */
4291 	if (ISCD(un))
4292 		return (ret);
4293 
4294 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4295 
4296 	/*
4297 	 * Retrieve MODE SENSE page 3 - Format Device Page
4298 	 */
4299 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4300 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p3bufp,
4301 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag)
4302 	    != 0) {
4303 		SD_ERROR(SD_LOG_COMMON, un,
4304 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4305 		goto page3_exit;
4306 	}
4307 
4308 	/*
4309 	 * Determine size of Block Descriptors in order to locate the mode
4310 	 * page data.  ATAPI devices return 0, SCSI devices should return
4311 	 * MODE_BLK_DESC_LENGTH.
4312 	 */
4313 	headerp = (struct mode_header *)p3bufp;
4314 	if (un->un_f_cfg_is_atapi == TRUE) {
4315 		struct mode_header_grp2 *mhp =
4316 		    (struct mode_header_grp2 *)headerp;
4317 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4318 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4319 	} else {
4320 		mode_header_length = MODE_HEADER_LENGTH;
4321 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4322 	}
4323 
4324 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4325 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4326 		    "received unexpected bd_len of %d, page3\n", bd_len);
4327 		goto page3_exit;
4328 	}
4329 
4330 	page3p = (struct mode_format *)
4331 	    ((caddr_t)headerp + mode_header_length + bd_len);
4332 
4333 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4334 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4335 		    "mode sense pg3 code mismatch %d\n",
4336 		    page3p->mode_page.code);
4337 		goto page3_exit;
4338 	}
4339 
4340 	/*
4341 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4342 	 * complete successfully; otherwise, revert to the logical geometry.
4343 	 * So, we need to save everything in temporary variables.
4344 	 */
4345 	sector_size = BE_16(page3p->data_bytes_sect);
4346 
4347 	/*
4348 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4349 	 */
4350 	if (sector_size == 0) {
4351 		sector_size = un->un_sys_blocksize;
4352 	} else {
4353 		sector_size &= ~(un->un_sys_blocksize - 1);
4354 	}
4355 
4356 	nsect  = BE_16(page3p->sect_track);
4357 	intrlv = BE_16(page3p->interleave);
4358 
4359 	SD_INFO(SD_LOG_COMMON, un,
4360 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
4361 	SD_INFO(SD_LOG_COMMON, un,
4362 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
4363 	    page3p->mode_page.code, nsect, sector_size);
4364 	SD_INFO(SD_LOG_COMMON, un,
4365 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
4366 	    BE_16(page3p->track_skew),
4367 	    BE_16(page3p->cylinder_skew));
4368 
4369 
4370 	/*
4371 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
4372 	 */
4373 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
4374 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p4bufp,
4375 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag)
4376 	    != 0) {
4377 		SD_ERROR(SD_LOG_COMMON, un,
4378 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
4379 		goto page4_exit;
4380 	}
4381 
4382 	/*
4383 	 * Determine size of Block Descriptors in order to locate the mode
4384 	 * page data.  ATAPI devices return 0, SCSI devices should return
4385 	 * MODE_BLK_DESC_LENGTH.
4386 	 */
4387 	headerp = (struct mode_header *)p4bufp;
4388 	if (un->un_f_cfg_is_atapi == TRUE) {
4389 		struct mode_header_grp2 *mhp =
4390 		    (struct mode_header_grp2 *)headerp;
4391 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4392 	} else {
4393 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4394 	}
4395 
4396 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4397 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4398 		    "received unexpected bd_len of %d, page4\n", bd_len);
4399 		goto page4_exit;
4400 	}
4401 
4402 	page4p = (struct mode_geometry *)
4403 	    ((caddr_t)headerp + mode_header_length + bd_len);
4404 
4405 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
4406 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4407 		    "mode sense pg4 code mismatch %d\n",
4408 		    page4p->mode_page.code);
4409 		goto page4_exit;
4410 	}
4411 
4412 	/*
4413 	 * Stash the data now, after we know that both commands completed.
4414 	 */
4415 
4416 
4417 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
4418 	spc   = nhead * nsect;
4419 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
4420 	rpm   = BE_16(page4p->rpm);
4421 
4422 	modesense_capacity = spc * ncyl;
4423 
4424 	SD_INFO(SD_LOG_COMMON, un,
4425 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
4426 	SD_INFO(SD_LOG_COMMON, un,
4427 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
4428 	SD_INFO(SD_LOG_COMMON, un,
4429 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
4430 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
4431 	    (void *)pgeom_p, capacity);
4432 
4433 	/*
4434 	 * Compensate if the drive's geometry is not rectangular, i.e.,
4435 	 * the product of C * H * S returned by MODE SENSE >= that returned
4436 	 * by read capacity. This is an idiosyncrasy of the original x86
4437 	 * disk subsystem.
4438 	 */
4439 	if (modesense_capacity >= capacity) {
4440 		SD_INFO(SD_LOG_COMMON, un,
4441 		    "sd_get_physical_geometry: adjusting acyl; "
4442 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
4443 		    (modesense_capacity - capacity + spc - 1) / spc);
4444 		if (sector_size != 0) {
4445 			/* 1243403: NEC D38x7 drives don't support sec size */
4446 			pgeom_p->g_secsize = (unsigned short)sector_size;
4447 		}
4448 		pgeom_p->g_nsect    = (unsigned short)nsect;
4449 		pgeom_p->g_nhead    = (unsigned short)nhead;
4450 		pgeom_p->g_capacity = capacity;
4451 		pgeom_p->g_acyl	    =
4452 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
4453 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
4454 	}
4455 
4456 	pgeom_p->g_rpm    = (unsigned short)rpm;
4457 	pgeom_p->g_intrlv = (unsigned short)intrlv;
4458 	ret = 0;
4459 
4460 	SD_INFO(SD_LOG_COMMON, un,
4461 	    "sd_get_physical_geometry: mode sense geometry:\n");
4462 	SD_INFO(SD_LOG_COMMON, un,
4463 	    "   nsect: %d; sector size: %d; interlv: %d\n",
4464 	    nsect, sector_size, intrlv);
4465 	SD_INFO(SD_LOG_COMMON, un,
4466 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
4467 	    nhead, ncyl, rpm, modesense_capacity);
4468 	SD_INFO(SD_LOG_COMMON, un,
4469 	    "sd_get_physical_geometry: (cached)\n");
4470 	SD_INFO(SD_LOG_COMMON, un,
4471 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
4472 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
4473 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
4474 	SD_INFO(SD_LOG_COMMON, un,
4475 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
4476 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
4477 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
4478 
4479 page4_exit:
4480 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
4481 page3_exit:
4482 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
4483 
4484 	return (ret);
4485 }
4486 
4487 /*
4488  *    Function: sd_get_virtual_geometry
4489  *
4490  * Description: Ask the controller to tell us about the target device.
4491  *
4492  *   Arguments: un - pointer to softstate
4493  *		capacity - disk capacity in #blocks
4494  *		lbasize - disk block size in bytes
4495  *
4496  *     Context: Kernel thread only
4497  */
4498 
4499 static int
4500 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
4501     diskaddr_t capacity, int lbasize)
4502 {
4503 	uint_t	geombuf;
4504 	int	spc;
4505 
4506 	ASSERT(un != NULL);
4507 
4508 	/* Set sector size, and total number of sectors */
4509 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
4510 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
4511 
4512 	/* Let the HBA tell us its geometry */
4513 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
4514 
4515 	/* A value of -1 indicates an undefined "geometry" property */
4516 	if (geombuf == (-1)) {
4517 		return (EINVAL);
4518 	}
4519 
4520 	/* Initialize the logical geometry cache. */
4521 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
4522 	lgeom_p->g_nsect   = geombuf & 0xffff;
4523 	lgeom_p->g_secsize = un->un_sys_blocksize;
4524 
4525 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
4526 
4527 	/*
4528 	 * Note: The driver originally converted the capacity value from
4529 	 * target blocks to system blocks. However, the capacity value passed
4530 	 * to this routine is already in terms of system blocks (this scaling
4531 	 * is done when the READ CAPACITY command is issued and processed).
4532 	 * This 'error' may have gone undetected because the usage of g_ncyl
4533 	 * (which is based upon g_capacity) is very limited within the driver
4534 	 */
4535 	lgeom_p->g_capacity = capacity;
4536 
4537 	/*
4538 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
4539 	 * hba may return zero values if the device has been removed.
4540 	 */
4541 	if (spc == 0) {
4542 		lgeom_p->g_ncyl = 0;
4543 	} else {
4544 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
4545 	}
4546 	lgeom_p->g_acyl = 0;
4547 
4548 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
4549 	return (0);
4550 
4551 }
4552 /*
4553  *    Function: sd_update_block_info
4554  *
4555  * Description: Calculate a byte count to sector count bitshift value
4556  *		from sector size.
4557  *
4558  *   Arguments: un: unit struct.
4559  *		lbasize: new target sector size
4560  *		capacity: new target capacity, ie. block count
4561  *
4562  *     Context: Kernel thread context
4563  */
4564 
4565 static void
4566 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
4567 {
4568 	uint_t		dblk;
4569 
4570 	if (lbasize != 0) {
4571 		un->un_tgt_blocksize = lbasize;
4572 		un->un_f_tgt_blocksize_is_valid	= TRUE;
4573 	}
4574 
4575 	if (capacity != 0) {
4576 		un->un_blockcount		= capacity;
4577 		un->un_f_blockcount_is_valid	= TRUE;
4578 	}
4579 
4580 	/*
4581 	 * Update device capacity properties.
4582 	 *
4583 	 *   'device-nblocks'	number of blocks in target's units
4584 	 *   'device-blksize'	data bearing size of target's block
4585 	 *
4586 	 * NOTE: math is complicated by the fact that un_tgt_blocksize may
4587 	 * not be a power of two for checksumming disks with 520/528 byte
4588 	 * sectors.
4589 	 */
4590 	if (un->un_f_tgt_blocksize_is_valid &&
4591 	    un->un_f_blockcount_is_valid &&
4592 	    un->un_sys_blocksize) {
4593 		dblk = un->un_tgt_blocksize / un->un_sys_blocksize;
4594 		(void) ddi_prop_update_int64(DDI_DEV_T_NONE, SD_DEVINFO(un),
4595 		    "device-nblocks", un->un_blockcount / dblk);
4596 		/*
4597 		 * To save memory, only define "device-blksize" when its
4598 		 * value is differnet than the default DEV_BSIZE value.
4599 		 */
4600 		if ((un->un_sys_blocksize * dblk) != DEV_BSIZE)
4601 			(void) ddi_prop_update_int(DDI_DEV_T_NONE,
4602 			    SD_DEVINFO(un), "device-blksize",
4603 			    un->un_sys_blocksize * dblk);
4604 	}
4605 }
4606 
4607 
4608 /*
4609  *    Function: sd_register_devid
4610  *
4611  * Description: This routine will obtain the device id information from the
4612  *		target, obtain the serial number, and register the device
4613  *		id with the ddi framework.
4614  *
4615  *   Arguments: devi - the system's dev_info_t for the device.
4616  *		un - driver soft state (unit) structure
4617  *		reservation_flag - indicates if a reservation conflict
4618  *		occurred during attach
4619  *
4620  *     Context: Kernel Thread
4621  */
4622 static void
4623 sd_register_devid(struct sd_lun *un, dev_info_t *devi, int reservation_flag)
4624 {
4625 	int		rval		= 0;
4626 	uchar_t		*inq80		= NULL;
4627 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
4628 	size_t		inq80_resid	= 0;
4629 	uchar_t		*inq83		= NULL;
4630 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
4631 	size_t		inq83_resid	= 0;
4632 	int		dlen, len;
4633 	char		*sn;
4634 
4635 	ASSERT(un != NULL);
4636 	ASSERT(mutex_owned(SD_MUTEX(un)));
4637 	ASSERT((SD_DEVINFO(un)) == devi);
4638 
4639 	/*
4640 	 * This is the case of antiquated Sun disk drives that have the
4641 	 * FAB_DEVID property set in the disk_table.  These drives
4642 	 * manage the devid's by storing them in last 2 available sectors
4643 	 * on the drive and have them fabricated by the ddi layer by calling
4644 	 * ddi_devid_init and passing the DEVID_FAB flag.
4645 	 */
4646 	if (un->un_f_opt_fab_devid == TRUE) {
4647 		/*
4648 		 * Depending on EINVAL isn't reliable, since a reserved disk
4649 		 * may result in invalid geometry, so check to make sure a
4650 		 * reservation conflict did not occur during attach.
4651 		 */
4652 		if ((sd_get_devid(un) == EINVAL) &&
4653 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
4654 			/*
4655 			 * The devid is invalid AND there is no reservation
4656 			 * conflict.  Fabricate a new devid.
4657 			 */
4658 			(void) sd_create_devid(un);
4659 		}
4660 
4661 		/* Register the devid if it exists */
4662 		if (un->un_devid != NULL) {
4663 			(void) ddi_devid_register(SD_DEVINFO(un),
4664 			    un->un_devid);
4665 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4666 			    "sd_register_devid: Devid Fabricated\n");
4667 		}
4668 		return;
4669 	}
4670 
4671 	/*
4672 	 * We check the availibility of the World Wide Name (0x83) and Unit
4673 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
4674 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
4675 	 * 0x83 is availible, that is the best choice.  Our next choice is
4676 	 * 0x80.  If neither are availible, we munge the devid from the device
4677 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
4678 	 * to fabricate a devid for non-Sun qualified disks.
4679 	 */
4680 	if (sd_check_vpd_page_support(un) == 0) {
4681 		/* collect page 80 data if available */
4682 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
4683 
4684 			mutex_exit(SD_MUTEX(un));
4685 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
4686 			rval = sd_send_scsi_INQUIRY(un, inq80, inq80_len,
4687 			    0x01, 0x80, &inq80_resid);
4688 
4689 			if (rval != 0) {
4690 				kmem_free(inq80, inq80_len);
4691 				inq80 = NULL;
4692 				inq80_len = 0;
4693 			} else if (ddi_prop_exists(
4694 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
4695 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
4696 			    INQUIRY_SERIAL_NO) == 0) {
4697 				/*
4698 				 * If we don't already have a serial number
4699 				 * property, do quick verify of data returned
4700 				 * and define property.
4701 				 */
4702 				dlen = inq80_len - inq80_resid;
4703 				len = (size_t)inq80[3];
4704 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
4705 					/*
4706 					 * Ensure sn termination, skip leading
4707 					 * blanks, and create property
4708 					 * 'inquiry-serial-no'.
4709 					 */
4710 					sn = (char *)&inq80[4];
4711 					sn[len] = 0;
4712 					while (*sn && (*sn == ' '))
4713 						sn++;
4714 					if (*sn) {
4715 						(void) ddi_prop_update_string(
4716 						    DDI_DEV_T_NONE,
4717 						    SD_DEVINFO(un),
4718 						    INQUIRY_SERIAL_NO, sn);
4719 					}
4720 				}
4721 			}
4722 			mutex_enter(SD_MUTEX(un));
4723 		}
4724 
4725 		/* collect page 83 data if available */
4726 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
4727 			mutex_exit(SD_MUTEX(un));
4728 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
4729 			rval = sd_send_scsi_INQUIRY(un, inq83, inq83_len,
4730 			    0x01, 0x83, &inq83_resid);
4731 
4732 			if (rval != 0) {
4733 				kmem_free(inq83, inq83_len);
4734 				inq83 = NULL;
4735 				inq83_len = 0;
4736 			}
4737 			mutex_enter(SD_MUTEX(un));
4738 		}
4739 	}
4740 
4741 	/* encode best devid possible based on data available */
4742 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
4743 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
4744 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
4745 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
4746 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
4747 
4748 		/* devid successfully encoded, register devid */
4749 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
4750 
4751 	} else {
4752 		/*
4753 		 * Unable to encode a devid based on data available.
4754 		 * This is not a Sun qualified disk.  Older Sun disk
4755 		 * drives that have the SD_FAB_DEVID property
4756 		 * set in the disk_table and non Sun qualified
4757 		 * disks are treated in the same manner.  These
4758 		 * drives manage the devid's by storing them in
4759 		 * last 2 available sectors on the drive and
4760 		 * have them fabricated by the ddi layer by
4761 		 * calling ddi_devid_init and passing the
4762 		 * DEVID_FAB flag.
4763 		 * Create a fabricate devid only if there's no
4764 		 * fabricate devid existed.
4765 		 */
4766 		if (sd_get_devid(un) == EINVAL) {
4767 			(void) sd_create_devid(un);
4768 		}
4769 		un->un_f_opt_fab_devid = TRUE;
4770 
4771 		/* Register the devid if it exists */
4772 		if (un->un_devid != NULL) {
4773 			(void) ddi_devid_register(SD_DEVINFO(un),
4774 			    un->un_devid);
4775 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4776 			    "sd_register_devid: devid fabricated using "
4777 			    "ddi framework\n");
4778 		}
4779 	}
4780 
4781 	/* clean up resources */
4782 	if (inq80 != NULL) {
4783 		kmem_free(inq80, inq80_len);
4784 	}
4785 	if (inq83 != NULL) {
4786 		kmem_free(inq83, inq83_len);
4787 	}
4788 }
4789 
4790 
4791 
4792 /*
4793  *    Function: sd_get_devid
4794  *
4795  * Description: This routine will return 0 if a valid device id has been
4796  *		obtained from the target and stored in the soft state. If a
4797  *		valid device id has not been previously read and stored, a
4798  *		read attempt will be made.
4799  *
4800  *   Arguments: un - driver soft state (unit) structure
4801  *
4802  * Return Code: 0 if we successfully get the device id
4803  *
4804  *     Context: Kernel Thread
4805  */
4806 
4807 static int
4808 sd_get_devid(struct sd_lun *un)
4809 {
4810 	struct dk_devid		*dkdevid;
4811 	ddi_devid_t		tmpid;
4812 	uint_t			*ip;
4813 	size_t			sz;
4814 	diskaddr_t		blk;
4815 	int			status;
4816 	int			chksum;
4817 	int			i;
4818 	size_t			buffer_size;
4819 
4820 	ASSERT(un != NULL);
4821 	ASSERT(mutex_owned(SD_MUTEX(un)));
4822 
4823 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
4824 	    un);
4825 
4826 	if (un->un_devid != NULL) {
4827 		return (0);
4828 	}
4829 
4830 	mutex_exit(SD_MUTEX(un));
4831 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
4832 	    (void *)SD_PATH_DIRECT) != 0) {
4833 		mutex_enter(SD_MUTEX(un));
4834 		return (EINVAL);
4835 	}
4836 
4837 	/*
4838 	 * Read and verify device id, stored in the reserved cylinders at the
4839 	 * end of the disk. Backup label is on the odd sectors of the last
4840 	 * track of the last cylinder. Device id will be on track of the next
4841 	 * to last cylinder.
4842 	 */
4843 	mutex_enter(SD_MUTEX(un));
4844 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
4845 	mutex_exit(SD_MUTEX(un));
4846 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
4847 	status = sd_send_scsi_READ(un, dkdevid, buffer_size, blk,
4848 	    SD_PATH_DIRECT);
4849 	if (status != 0) {
4850 		goto error;
4851 	}
4852 
4853 	/* Validate the revision */
4854 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
4855 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
4856 		status = EINVAL;
4857 		goto error;
4858 	}
4859 
4860 	/* Calculate the checksum */
4861 	chksum = 0;
4862 	ip = (uint_t *)dkdevid;
4863 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
4864 	    i++) {
4865 		chksum ^= ip[i];
4866 	}
4867 
4868 	/* Compare the checksums */
4869 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
4870 		status = EINVAL;
4871 		goto error;
4872 	}
4873 
4874 	/* Validate the device id */
4875 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
4876 		status = EINVAL;
4877 		goto error;
4878 	}
4879 
4880 	/*
4881 	 * Store the device id in the driver soft state
4882 	 */
4883 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
4884 	tmpid = kmem_alloc(sz, KM_SLEEP);
4885 
4886 	mutex_enter(SD_MUTEX(un));
4887 
4888 	un->un_devid = tmpid;
4889 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
4890 
4891 	kmem_free(dkdevid, buffer_size);
4892 
4893 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
4894 
4895 	return (status);
4896 error:
4897 	mutex_enter(SD_MUTEX(un));
4898 	kmem_free(dkdevid, buffer_size);
4899 	return (status);
4900 }
4901 
4902 
4903 /*
4904  *    Function: sd_create_devid
4905  *
4906  * Description: This routine will fabricate the device id and write it
4907  *		to the disk.
4908  *
4909  *   Arguments: un - driver soft state (unit) structure
4910  *
4911  * Return Code: value of the fabricated device id
4912  *
4913  *     Context: Kernel Thread
4914  */
4915 
4916 static ddi_devid_t
4917 sd_create_devid(struct sd_lun *un)
4918 {
4919 	ASSERT(un != NULL);
4920 
4921 	/* Fabricate the devid */
4922 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
4923 	    == DDI_FAILURE) {
4924 		return (NULL);
4925 	}
4926 
4927 	/* Write the devid to disk */
4928 	if (sd_write_deviceid(un) != 0) {
4929 		ddi_devid_free(un->un_devid);
4930 		un->un_devid = NULL;
4931 	}
4932 
4933 	return (un->un_devid);
4934 }
4935 
4936 
4937 /*
4938  *    Function: sd_write_deviceid
4939  *
4940  * Description: This routine will write the device id to the disk
4941  *		reserved sector.
4942  *
4943  *   Arguments: un - driver soft state (unit) structure
4944  *
4945  * Return Code: EINVAL
4946  *		value returned by sd_send_scsi_cmd
4947  *
4948  *     Context: Kernel Thread
4949  */
4950 
4951 static int
4952 sd_write_deviceid(struct sd_lun *un)
4953 {
4954 	struct dk_devid		*dkdevid;
4955 	diskaddr_t		blk;
4956 	uint_t			*ip, chksum;
4957 	int			status;
4958 	int			i;
4959 
4960 	ASSERT(mutex_owned(SD_MUTEX(un)));
4961 
4962 	mutex_exit(SD_MUTEX(un));
4963 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
4964 	    (void *)SD_PATH_DIRECT) != 0) {
4965 		mutex_enter(SD_MUTEX(un));
4966 		return (-1);
4967 	}
4968 
4969 
4970 	/* Allocate the buffer */
4971 	dkdevid = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
4972 
4973 	/* Fill in the revision */
4974 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
4975 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
4976 
4977 	/* Copy in the device id */
4978 	mutex_enter(SD_MUTEX(un));
4979 	bcopy(un->un_devid, &dkdevid->dkd_devid,
4980 	    ddi_devid_sizeof(un->un_devid));
4981 	mutex_exit(SD_MUTEX(un));
4982 
4983 	/* Calculate the checksum */
4984 	chksum = 0;
4985 	ip = (uint_t *)dkdevid;
4986 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
4987 	    i++) {
4988 		chksum ^= ip[i];
4989 	}
4990 
4991 	/* Fill-in checksum */
4992 	DKD_FORMCHKSUM(chksum, dkdevid);
4993 
4994 	/* Write the reserved sector */
4995 	status = sd_send_scsi_WRITE(un, dkdevid, un->un_sys_blocksize, blk,
4996 	    SD_PATH_DIRECT);
4997 
4998 	kmem_free(dkdevid, un->un_sys_blocksize);
4999 
5000 	mutex_enter(SD_MUTEX(un));
5001 	return (status);
5002 }
5003 
5004 
5005 /*
5006  *    Function: sd_check_vpd_page_support
5007  *
5008  * Description: This routine sends an inquiry command with the EVPD bit set and
5009  *		a page code of 0x00 to the device. It is used to determine which
5010  *		vital product pages are availible to find the devid. We are
5011  *		looking for pages 0x83 or 0x80.  If we return a negative 1, the
5012  *		device does not support that command.
5013  *
5014  *   Arguments: un  - driver soft state (unit) structure
5015  *
5016  * Return Code: 0 - success
5017  *		1 - check condition
5018  *
5019  *     Context: This routine can sleep.
5020  */
5021 
5022 static int
5023 sd_check_vpd_page_support(struct sd_lun *un)
5024 {
5025 	uchar_t	*page_list	= NULL;
5026 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5027 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5028 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5029 	int    	rval		= 0;
5030 	int	counter;
5031 
5032 	ASSERT(un != NULL);
5033 	ASSERT(mutex_owned(SD_MUTEX(un)));
5034 
5035 	mutex_exit(SD_MUTEX(un));
5036 
5037 	/*
5038 	 * We'll set the page length to the maximum to save figuring it out
5039 	 * with an additional call.
5040 	 */
5041 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5042 
5043 	rval = sd_send_scsi_INQUIRY(un, page_list, page_length, evpd,
5044 	    page_code, NULL);
5045 
5046 	mutex_enter(SD_MUTEX(un));
5047 
5048 	/*
5049 	 * Now we must validate that the device accepted the command, as some
5050 	 * drives do not support it.  If the drive does support it, we will
5051 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5052 	 * not, we return -1.
5053 	 */
5054 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5055 		/* Loop to find one of the 2 pages we need */
5056 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5057 
5058 		/*
5059 		 * Pages are returned in ascending order, and 0x83 is what we
5060 		 * are hoping for.
5061 		 */
5062 		while ((page_list[counter] <= 0x83) &&
5063 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5064 		    VPD_HEAD_OFFSET))) {
5065 			/*
5066 			 * Add 3 because page_list[3] is the number of
5067 			 * pages minus 3
5068 			 */
5069 
5070 			switch (page_list[counter]) {
5071 			case 0x00:
5072 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5073 				break;
5074 			case 0x80:
5075 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5076 				break;
5077 			case 0x81:
5078 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5079 				break;
5080 			case 0x82:
5081 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5082 				break;
5083 			case 0x83:
5084 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5085 				break;
5086 			}
5087 			counter++;
5088 		}
5089 
5090 	} else {
5091 		rval = -1;
5092 
5093 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5094 		    "sd_check_vpd_page_support: This drive does not implement "
5095 		    "VPD pages.\n");
5096 	}
5097 
5098 	kmem_free(page_list, page_length);
5099 
5100 	return (rval);
5101 }
5102 
5103 
5104 /*
5105  *    Function: sd_setup_pm
5106  *
5107  * Description: Initialize Power Management on the device
5108  *
5109  *     Context: Kernel Thread
5110  */
5111 
5112 static void
5113 sd_setup_pm(struct sd_lun *un, dev_info_t *devi)
5114 {
5115 	uint_t	log_page_size;
5116 	uchar_t	*log_page_data;
5117 	int	rval;
5118 
5119 	/*
5120 	 * Since we are called from attach, holding a mutex for
5121 	 * un is unnecessary. Because some of the routines called
5122 	 * from here require SD_MUTEX to not be held, assert this
5123 	 * right up front.
5124 	 */
5125 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5126 	/*
5127 	 * Since the sd device does not have the 'reg' property,
5128 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5129 	 * The following code is to tell cpr that this device
5130 	 * DOES need to be suspended and resumed.
5131 	 */
5132 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5133 	    "pm-hardware-state", "needs-suspend-resume");
5134 
5135 	/*
5136 	 * This complies with the new power management framework
5137 	 * for certain desktop machines. Create the pm_components
5138 	 * property as a string array property.
5139 	 */
5140 	if (un->un_f_pm_supported) {
5141 		/*
5142 		 * not all devices have a motor, try it first.
5143 		 * some devices may return ILLEGAL REQUEST, some
5144 		 * will hang
5145 		 * The following START_STOP_UNIT is used to check if target
5146 		 * device has a motor.
5147 		 */
5148 		un->un_f_start_stop_supported = TRUE;
5149 		if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
5150 		    SD_PATH_DIRECT) != 0) {
5151 			un->un_f_start_stop_supported = FALSE;
5152 		}
5153 
5154 		/*
5155 		 * create pm properties anyways otherwise the parent can't
5156 		 * go to sleep
5157 		 */
5158 		(void) sd_create_pm_components(devi, un);
5159 		un->un_f_pm_is_enabled = TRUE;
5160 		return;
5161 	}
5162 
5163 	if (!un->un_f_log_sense_supported) {
5164 		un->un_power_level = SD_SPINDLE_ON;
5165 		un->un_f_pm_is_enabled = FALSE;
5166 		return;
5167 	}
5168 
5169 	rval = sd_log_page_supported(un, START_STOP_CYCLE_PAGE);
5170 
5171 #ifdef	SDDEBUG
5172 	if (sd_force_pm_supported) {
5173 		/* Force a successful result */
5174 		rval = 1;
5175 	}
5176 #endif
5177 
5178 	/*
5179 	 * If the start-stop cycle counter log page is not supported
5180 	 * or if the pm-capable property is SD_PM_CAPABLE_FALSE (0)
5181 	 * then we should not create the pm_components property.
5182 	 */
5183 	if (rval == -1) {
5184 		/*
5185 		 * Error.
5186 		 * Reading log sense failed, most likely this is
5187 		 * an older drive that does not support log sense.
5188 		 * If this fails auto-pm is not supported.
5189 		 */
5190 		un->un_power_level = SD_SPINDLE_ON;
5191 		un->un_f_pm_is_enabled = FALSE;
5192 
5193 	} else if (rval == 0) {
5194 		/*
5195 		 * Page not found.
5196 		 * The start stop cycle counter is implemented as page
5197 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
5198 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
5199 		 */
5200 		if (sd_log_page_supported(un, START_STOP_CYCLE_VU_PAGE) == 1) {
5201 			/*
5202 			 * Page found, use this one.
5203 			 */
5204 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
5205 			un->un_f_pm_is_enabled = TRUE;
5206 		} else {
5207 			/*
5208 			 * Error or page not found.
5209 			 * auto-pm is not supported for this device.
5210 			 */
5211 			un->un_power_level = SD_SPINDLE_ON;
5212 			un->un_f_pm_is_enabled = FALSE;
5213 		}
5214 	} else {
5215 		/*
5216 		 * Page found, use it.
5217 		 */
5218 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
5219 		un->un_f_pm_is_enabled = TRUE;
5220 	}
5221 
5222 
5223 	if (un->un_f_pm_is_enabled == TRUE) {
5224 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5225 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5226 
5227 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
5228 		    log_page_size, un->un_start_stop_cycle_page,
5229 		    0x01, 0, SD_PATH_DIRECT);
5230 #ifdef	SDDEBUG
5231 		if (sd_force_pm_supported) {
5232 			/* Force a successful result */
5233 			rval = 0;
5234 		}
5235 #endif
5236 
5237 		/*
5238 		 * If the Log sense for Page( Start/stop cycle counter page)
5239 		 * succeeds, then power managment is supported and we can
5240 		 * enable auto-pm.
5241 		 */
5242 		if (rval == 0)  {
5243 			(void) sd_create_pm_components(devi, un);
5244 		} else {
5245 			un->un_power_level = SD_SPINDLE_ON;
5246 			un->un_f_pm_is_enabled = FALSE;
5247 		}
5248 
5249 		kmem_free(log_page_data, log_page_size);
5250 	}
5251 }
5252 
5253 
5254 /*
5255  *    Function: sd_create_pm_components
5256  *
5257  * Description: Initialize PM property.
5258  *
5259  *     Context: Kernel thread context
5260  */
5261 
5262 static void
5263 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
5264 {
5265 	char *pm_comp[] = { "NAME=spindle-motor", "0=off", "1=on", NULL };
5266 
5267 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5268 
5269 	if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
5270 	    "pm-components", pm_comp, 3) == DDI_PROP_SUCCESS) {
5271 		/*
5272 		 * When components are initially created they are idle,
5273 		 * power up any non-removables.
5274 		 * Note: the return value of pm_raise_power can't be used
5275 		 * for determining if PM should be enabled for this device.
5276 		 * Even if you check the return values and remove this
5277 		 * property created above, the PM framework will not honor the
5278 		 * change after the first call to pm_raise_power. Hence,
5279 		 * removal of that property does not help if pm_raise_power
5280 		 * fails. In the case of removable media, the start/stop
5281 		 * will fail if the media is not present.
5282 		 */
5283 		if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
5284 		    SD_SPINDLE_ON) == DDI_SUCCESS)) {
5285 			mutex_enter(SD_MUTEX(un));
5286 			un->un_power_level = SD_SPINDLE_ON;
5287 			mutex_enter(&un->un_pm_mutex);
5288 			/* Set to on and not busy. */
5289 			un->un_pm_count = 0;
5290 		} else {
5291 			mutex_enter(SD_MUTEX(un));
5292 			un->un_power_level = SD_SPINDLE_OFF;
5293 			mutex_enter(&un->un_pm_mutex);
5294 			/* Set to off. */
5295 			un->un_pm_count = -1;
5296 		}
5297 		mutex_exit(&un->un_pm_mutex);
5298 		mutex_exit(SD_MUTEX(un));
5299 	} else {
5300 		un->un_power_level = SD_SPINDLE_ON;
5301 		un->un_f_pm_is_enabled = FALSE;
5302 	}
5303 }
5304 
5305 
5306 /*
5307  *    Function: sd_ddi_suspend
5308  *
5309  * Description: Performs system power-down operations. This includes
5310  *		setting the drive state to indicate its suspended so
5311  *		that no new commands will be accepted. Also, wait for
5312  *		all commands that are in transport or queued to a timer
5313  *		for retry to complete. All timeout threads are cancelled.
5314  *
5315  * Return Code: DDI_FAILURE or DDI_SUCCESS
5316  *
5317  *     Context: Kernel thread context
5318  */
5319 
5320 static int
5321 sd_ddi_suspend(dev_info_t *devi)
5322 {
5323 	struct	sd_lun	*un;
5324 	clock_t		wait_cmds_complete;
5325 
5326 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
5327 	if (un == NULL) {
5328 		return (DDI_FAILURE);
5329 	}
5330 
5331 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
5332 
5333 	mutex_enter(SD_MUTEX(un));
5334 
5335 	/* Return success if the device is already suspended. */
5336 	if (un->un_state == SD_STATE_SUSPENDED) {
5337 		mutex_exit(SD_MUTEX(un));
5338 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5339 		    "device already suspended, exiting\n");
5340 		return (DDI_SUCCESS);
5341 	}
5342 
5343 	/* Return failure if the device is being used by HA */
5344 	if (un->un_resvd_status &
5345 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
5346 		mutex_exit(SD_MUTEX(un));
5347 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5348 		    "device in use by HA, exiting\n");
5349 		return (DDI_FAILURE);
5350 	}
5351 
5352 	/*
5353 	 * Return failure if the device is in a resource wait
5354 	 * or power changing state.
5355 	 */
5356 	if ((un->un_state == SD_STATE_RWAIT) ||
5357 	    (un->un_state == SD_STATE_PM_CHANGING)) {
5358 		mutex_exit(SD_MUTEX(un));
5359 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5360 		    "device in resource wait state, exiting\n");
5361 		return (DDI_FAILURE);
5362 	}
5363 
5364 
5365 	un->un_save_state = un->un_last_state;
5366 	New_state(un, SD_STATE_SUSPENDED);
5367 
5368 	/*
5369 	 * Wait for all commands that are in transport or queued to a timer
5370 	 * for retry to complete.
5371 	 *
5372 	 * While waiting, no new commands will be accepted or sent because of
5373 	 * the new state we set above.
5374 	 *
5375 	 * Wait till current operation has completed. If we are in the resource
5376 	 * wait state (with an intr outstanding) then we need to wait till the
5377 	 * intr completes and starts the next cmd. We want to wait for
5378 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
5379 	 */
5380 	wait_cmds_complete = ddi_get_lbolt() +
5381 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
5382 
5383 	while (un->un_ncmds_in_transport != 0) {
5384 		/*
5385 		 * Fail if commands do not finish in the specified time.
5386 		 */
5387 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
5388 		    wait_cmds_complete) == -1) {
5389 			/*
5390 			 * Undo the state changes made above. Everything
5391 			 * must go back to it's original value.
5392 			 */
5393 			Restore_state(un);
5394 			un->un_last_state = un->un_save_state;
5395 			/* Wake up any threads that might be waiting. */
5396 			cv_broadcast(&un->un_suspend_cv);
5397 			mutex_exit(SD_MUTEX(un));
5398 			SD_ERROR(SD_LOG_IO_PM, un,
5399 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
5400 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
5401 			return (DDI_FAILURE);
5402 		}
5403 	}
5404 
5405 	/*
5406 	 * Cancel SCSI watch thread and timeouts, if any are active
5407 	 */
5408 
5409 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
5410 		opaque_t temp_token = un->un_swr_token;
5411 		mutex_exit(SD_MUTEX(un));
5412 		scsi_watch_suspend(temp_token);
5413 		mutex_enter(SD_MUTEX(un));
5414 	}
5415 
5416 	if (un->un_reset_throttle_timeid != NULL) {
5417 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
5418 		un->un_reset_throttle_timeid = NULL;
5419 		mutex_exit(SD_MUTEX(un));
5420 		(void) untimeout(temp_id);
5421 		mutex_enter(SD_MUTEX(un));
5422 	}
5423 
5424 	if (un->un_dcvb_timeid != NULL) {
5425 		timeout_id_t temp_id = un->un_dcvb_timeid;
5426 		un->un_dcvb_timeid = NULL;
5427 		mutex_exit(SD_MUTEX(un));
5428 		(void) untimeout(temp_id);
5429 		mutex_enter(SD_MUTEX(un));
5430 	}
5431 
5432 	mutex_enter(&un->un_pm_mutex);
5433 	if (un->un_pm_timeid != NULL) {
5434 		timeout_id_t temp_id = un->un_pm_timeid;
5435 		un->un_pm_timeid = NULL;
5436 		mutex_exit(&un->un_pm_mutex);
5437 		mutex_exit(SD_MUTEX(un));
5438 		(void) untimeout(temp_id);
5439 		mutex_enter(SD_MUTEX(un));
5440 	} else {
5441 		mutex_exit(&un->un_pm_mutex);
5442 	}
5443 
5444 	if (un->un_retry_timeid != NULL) {
5445 		timeout_id_t temp_id = un->un_retry_timeid;
5446 		un->un_retry_timeid = NULL;
5447 		mutex_exit(SD_MUTEX(un));
5448 		(void) untimeout(temp_id);
5449 		mutex_enter(SD_MUTEX(un));
5450 	}
5451 
5452 	if (un->un_direct_priority_timeid != NULL) {
5453 		timeout_id_t temp_id = un->un_direct_priority_timeid;
5454 		un->un_direct_priority_timeid = NULL;
5455 		mutex_exit(SD_MUTEX(un));
5456 		(void) untimeout(temp_id);
5457 		mutex_enter(SD_MUTEX(un));
5458 	}
5459 
5460 	if (un->un_f_is_fibre == TRUE) {
5461 		/*
5462 		 * Remove callbacks for insert and remove events
5463 		 */
5464 		if (un->un_insert_event != NULL) {
5465 			mutex_exit(SD_MUTEX(un));
5466 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
5467 			mutex_enter(SD_MUTEX(un));
5468 			un->un_insert_event = NULL;
5469 		}
5470 
5471 		if (un->un_remove_event != NULL) {
5472 			mutex_exit(SD_MUTEX(un));
5473 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
5474 			mutex_enter(SD_MUTEX(un));
5475 			un->un_remove_event = NULL;
5476 		}
5477 	}
5478 
5479 	mutex_exit(SD_MUTEX(un));
5480 
5481 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
5482 
5483 	return (DDI_SUCCESS);
5484 }
5485 
5486 
5487 /*
5488  *    Function: sd_ddi_pm_suspend
5489  *
5490  * Description: Set the drive state to low power.
5491  *		Someone else is required to actually change the drive
5492  *		power level.
5493  *
5494  *   Arguments: un - driver soft state (unit) structure
5495  *
5496  * Return Code: DDI_FAILURE or DDI_SUCCESS
5497  *
5498  *     Context: Kernel thread context
5499  */
5500 
5501 static int
5502 sd_ddi_pm_suspend(struct sd_lun *un)
5503 {
5504 	ASSERT(un != NULL);
5505 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: entry\n");
5506 
5507 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5508 	mutex_enter(SD_MUTEX(un));
5509 
5510 	/*
5511 	 * Exit if power management is not enabled for this device, or if
5512 	 * the device is being used by HA.
5513 	 */
5514 	if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
5515 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
5516 		mutex_exit(SD_MUTEX(un));
5517 		SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exiting\n");
5518 		return (DDI_SUCCESS);
5519 	}
5520 
5521 	SD_INFO(SD_LOG_POWER, un, "sd_ddi_pm_suspend: un_ncmds_in_driver=%ld\n",
5522 	    un->un_ncmds_in_driver);
5523 
5524 	/*
5525 	 * See if the device is not busy, ie.:
5526 	 *    - we have no commands in the driver for this device
5527 	 *    - not waiting for resources
5528 	 */
5529 	if ((un->un_ncmds_in_driver == 0) &&
5530 	    (un->un_state != SD_STATE_RWAIT)) {
5531 		/*
5532 		 * The device is not busy, so it is OK to go to low power state.
5533 		 * Indicate low power, but rely on someone else to actually
5534 		 * change it.
5535 		 */
5536 		mutex_enter(&un->un_pm_mutex);
5537 		un->un_pm_count = -1;
5538 		mutex_exit(&un->un_pm_mutex);
5539 		un->un_power_level = SD_SPINDLE_OFF;
5540 	}
5541 
5542 	mutex_exit(SD_MUTEX(un));
5543 
5544 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exit\n");
5545 
5546 	return (DDI_SUCCESS);
5547 }
5548 
5549 
5550 /*
5551  *    Function: sd_ddi_resume
5552  *
5553  * Description: Performs system power-up operations..
5554  *
5555  * Return Code: DDI_SUCCESS
5556  *		DDI_FAILURE
5557  *
5558  *     Context: Kernel thread context
5559  */
5560 
5561 static int
5562 sd_ddi_resume(dev_info_t *devi)
5563 {
5564 	struct	sd_lun	*un;
5565 
5566 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
5567 	if (un == NULL) {
5568 		return (DDI_FAILURE);
5569 	}
5570 
5571 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
5572 
5573 	mutex_enter(SD_MUTEX(un));
5574 	Restore_state(un);
5575 
5576 	/*
5577 	 * Restore the state which was saved to give the
5578 	 * the right state in un_last_state
5579 	 */
5580 	un->un_last_state = un->un_save_state;
5581 	/*
5582 	 * Note: throttle comes back at full.
5583 	 * Also note: this MUST be done before calling pm_raise_power
5584 	 * otherwise the system can get hung in biowait. The scenario where
5585 	 * this'll happen is under cpr suspend. Writing of the system
5586 	 * state goes through sddump, which writes 0 to un_throttle. If
5587 	 * writing the system state then fails, example if the partition is
5588 	 * too small, then cpr attempts a resume. If throttle isn't restored
5589 	 * from the saved value until after calling pm_raise_power then
5590 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
5591 	 * in biowait.
5592 	 */
5593 	un->un_throttle = un->un_saved_throttle;
5594 
5595 	/*
5596 	 * The chance of failure is very rare as the only command done in power
5597 	 * entry point is START command when you transition from 0->1 or
5598 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
5599 	 * which suspend was done. Ignore the return value as the resume should
5600 	 * not be failed. In the case of removable media the media need not be
5601 	 * inserted and hence there is a chance that raise power will fail with
5602 	 * media not present.
5603 	 */
5604 	if (un->un_f_attach_spinup) {
5605 		mutex_exit(SD_MUTEX(un));
5606 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
5607 		mutex_enter(SD_MUTEX(un));
5608 	}
5609 
5610 	/*
5611 	 * Don't broadcast to the suspend cv and therefore possibly
5612 	 * start I/O until after power has been restored.
5613 	 */
5614 	cv_broadcast(&un->un_suspend_cv);
5615 	cv_broadcast(&un->un_state_cv);
5616 
5617 	/* restart thread */
5618 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
5619 		scsi_watch_resume(un->un_swr_token);
5620 	}
5621 
5622 #if (defined(__fibre))
5623 	if (un->un_f_is_fibre == TRUE) {
5624 		/*
5625 		 * Add callbacks for insert and remove events
5626 		 */
5627 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
5628 			sd_init_event_callbacks(un);
5629 		}
5630 	}
5631 #endif
5632 
5633 	/*
5634 	 * Transport any pending commands to the target.
5635 	 *
5636 	 * If this is a low-activity device commands in queue will have to wait
5637 	 * until new commands come in, which may take awhile. Also, we
5638 	 * specifically don't check un_ncmds_in_transport because we know that
5639 	 * there really are no commands in progress after the unit was
5640 	 * suspended and we could have reached the throttle level, been
5641 	 * suspended, and have no new commands coming in for awhile. Highly
5642 	 * unlikely, but so is the low-activity disk scenario.
5643 	 */
5644 	ddi_xbuf_dispatch(un->un_xbuf_attr);
5645 
5646 	sd_start_cmds(un, NULL);
5647 	mutex_exit(SD_MUTEX(un));
5648 
5649 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
5650 
5651 	return (DDI_SUCCESS);
5652 }
5653 
5654 
5655 /*
5656  *    Function: sd_ddi_pm_resume
5657  *
5658  * Description: Set the drive state to powered on.
5659  *		Someone else is required to actually change the drive
5660  *		power level.
5661  *
5662  *   Arguments: un - driver soft state (unit) structure
5663  *
5664  * Return Code: DDI_SUCCESS
5665  *
5666  *     Context: Kernel thread context
5667  */
5668 
5669 static int
5670 sd_ddi_pm_resume(struct sd_lun *un)
5671 {
5672 	ASSERT(un != NULL);
5673 
5674 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5675 	mutex_enter(SD_MUTEX(un));
5676 	un->un_power_level = SD_SPINDLE_ON;
5677 
5678 	ASSERT(!mutex_owned(&un->un_pm_mutex));
5679 	mutex_enter(&un->un_pm_mutex);
5680 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
5681 		un->un_pm_count++;
5682 		ASSERT(un->un_pm_count == 0);
5683 		/*
5684 		 * Note: no longer do the cv_broadcast on un_suspend_cv. The
5685 		 * un_suspend_cv is for a system resume, not a power management
5686 		 * device resume. (4297749)
5687 		 *	 cv_broadcast(&un->un_suspend_cv);
5688 		 */
5689 	}
5690 	mutex_exit(&un->un_pm_mutex);
5691 	mutex_exit(SD_MUTEX(un));
5692 
5693 	return (DDI_SUCCESS);
5694 }
5695 
5696 
5697 /*
5698  *    Function: sd_pm_idletimeout_handler
5699  *
5700  * Description: A timer routine that's active only while a device is busy.
5701  *		The purpose is to extend slightly the pm framework's busy
5702  *		view of the device to prevent busy/idle thrashing for
5703  *		back-to-back commands. Do this by comparing the current time
5704  *		to the time at which the last command completed and when the
5705  *		difference is greater than sd_pm_idletime, call
5706  *		pm_idle_component. In addition to indicating idle to the pm
5707  *		framework, update the chain type to again use the internal pm
5708  *		layers of the driver.
5709  *
5710  *   Arguments: arg - driver soft state (unit) structure
5711  *
5712  *     Context: Executes in a timeout(9F) thread context
5713  */
5714 
5715 static void
5716 sd_pm_idletimeout_handler(void *arg)
5717 {
5718 	struct sd_lun *un = arg;
5719 
5720 	time_t	now;
5721 
5722 	mutex_enter(&sd_detach_mutex);
5723 	if (un->un_detach_count != 0) {
5724 		/* Abort if the instance is detaching */
5725 		mutex_exit(&sd_detach_mutex);
5726 		return;
5727 	}
5728 	mutex_exit(&sd_detach_mutex);
5729 
5730 	now = ddi_get_time();
5731 	/*
5732 	 * Grab both mutexes, in the proper order, since we're accessing
5733 	 * both PM and softstate variables.
5734 	 */
5735 	mutex_enter(SD_MUTEX(un));
5736 	mutex_enter(&un->un_pm_mutex);
5737 	if (((now - un->un_pm_idle_time) > sd_pm_idletime) &&
5738 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
5739 		/*
5740 		 * Update the chain types.
5741 		 * This takes affect on the next new command received.
5742 		 */
5743 		if (un->un_f_non_devbsize_supported) {
5744 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
5745 		} else {
5746 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
5747 		}
5748 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
5749 
5750 		SD_TRACE(SD_LOG_IO_PM, un,
5751 		    "sd_pm_idletimeout_handler: idling device\n");
5752 		(void) pm_idle_component(SD_DEVINFO(un), 0);
5753 		un->un_pm_idle_timeid = NULL;
5754 	} else {
5755 		un->un_pm_idle_timeid =
5756 		    timeout(sd_pm_idletimeout_handler, un,
5757 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
5758 	}
5759 	mutex_exit(&un->un_pm_mutex);
5760 	mutex_exit(SD_MUTEX(un));
5761 }
5762 
5763 
5764 /*
5765  *    Function: sd_pm_timeout_handler
5766  *
5767  * Description: Callback to tell framework we are idle.
5768  *
5769  *     Context: timeout(9f) thread context.
5770  */
5771 
5772 static void
5773 sd_pm_timeout_handler(void *arg)
5774 {
5775 	struct sd_lun *un = arg;
5776 
5777 	(void) pm_idle_component(SD_DEVINFO(un), 0);
5778 	mutex_enter(&un->un_pm_mutex);
5779 	un->un_pm_timeid = NULL;
5780 	mutex_exit(&un->un_pm_mutex);
5781 }
5782 
5783 
5784 /*
5785  *    Function: sdpower
5786  *
5787  * Description: PM entry point.
5788  *
5789  * Return Code: DDI_SUCCESS
5790  *		DDI_FAILURE
5791  *
5792  *     Context: Kernel thread context
5793  */
5794 
5795 static int
5796 sdpower(dev_info_t *devi, int component, int level)
5797 {
5798 	struct sd_lun	*un;
5799 	int		instance;
5800 	int		rval = DDI_SUCCESS;
5801 	uint_t		i, log_page_size, maxcycles, ncycles;
5802 	uchar_t		*log_page_data;
5803 	int		log_sense_page;
5804 	int		medium_present;
5805 	time_t		intvlp;
5806 	dev_t		dev;
5807 	struct pm_trans_data	sd_pm_tran_data;
5808 	uchar_t		save_state;
5809 	int		sval;
5810 	uchar_t		state_before_pm;
5811 	int		got_semaphore_here;
5812 
5813 	instance = ddi_get_instance(devi);
5814 
5815 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
5816 	    (SD_SPINDLE_OFF > level) || (level > SD_SPINDLE_ON) ||
5817 	    component != 0) {
5818 		return (DDI_FAILURE);
5819 	}
5820 
5821 	dev = sd_make_device(SD_DEVINFO(un));
5822 
5823 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
5824 
5825 	/*
5826 	 * Must synchronize power down with close.
5827 	 * Attempt to decrement/acquire the open/close semaphore,
5828 	 * but do NOT wait on it. If it's not greater than zero,
5829 	 * ie. it can't be decremented without waiting, then
5830 	 * someone else, either open or close, already has it
5831 	 * and the try returns 0. Use that knowledge here to determine
5832 	 * if it's OK to change the device power level.
5833 	 * Also, only increment it on exit if it was decremented, ie. gotten,
5834 	 * here.
5835 	 */
5836 	got_semaphore_here = sema_tryp(&un->un_semoclose);
5837 
5838 	mutex_enter(SD_MUTEX(un));
5839 
5840 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
5841 	    un->un_ncmds_in_driver);
5842 
5843 	/*
5844 	 * If un_ncmds_in_driver is non-zero it indicates commands are
5845 	 * already being processed in the driver, or if the semaphore was
5846 	 * not gotten here it indicates an open or close is being processed.
5847 	 * At the same time somebody is requesting to go low power which
5848 	 * can't happen, therefore we need to return failure.
5849 	 */
5850 	if ((level == SD_SPINDLE_OFF) &&
5851 	    ((un->un_ncmds_in_driver != 0) || (got_semaphore_here == 0))) {
5852 		mutex_exit(SD_MUTEX(un));
5853 
5854 		if (got_semaphore_here != 0) {
5855 			sema_v(&un->un_semoclose);
5856 		}
5857 		SD_TRACE(SD_LOG_IO_PM, un,
5858 		    "sdpower: exit, device has queued cmds.\n");
5859 		return (DDI_FAILURE);
5860 	}
5861 
5862 	/*
5863 	 * if it is OFFLINE that means the disk is completely dead
5864 	 * in our case we have to put the disk in on or off by sending commands
5865 	 * Of course that will fail anyway so return back here.
5866 	 *
5867 	 * Power changes to a device that's OFFLINE or SUSPENDED
5868 	 * are not allowed.
5869 	 */
5870 	if ((un->un_state == SD_STATE_OFFLINE) ||
5871 	    (un->un_state == SD_STATE_SUSPENDED)) {
5872 		mutex_exit(SD_MUTEX(un));
5873 
5874 		if (got_semaphore_here != 0) {
5875 			sema_v(&un->un_semoclose);
5876 		}
5877 		SD_TRACE(SD_LOG_IO_PM, un,
5878 		    "sdpower: exit, device is off-line.\n");
5879 		return (DDI_FAILURE);
5880 	}
5881 
5882 	/*
5883 	 * Change the device's state to indicate it's power level
5884 	 * is being changed. Do this to prevent a power off in the
5885 	 * middle of commands, which is especially bad on devices
5886 	 * that are really powered off instead of just spun down.
5887 	 */
5888 	state_before_pm = un->un_state;
5889 	un->un_state = SD_STATE_PM_CHANGING;
5890 
5891 	mutex_exit(SD_MUTEX(un));
5892 
5893 	/*
5894 	 * If "pm-capable" property is set to TRUE by HBA drivers,
5895 	 * bypass the following checking, otherwise, check the log
5896 	 * sense information for this device
5897 	 */
5898 	if ((level == SD_SPINDLE_OFF) && un->un_f_log_sense_supported) {
5899 		/*
5900 		 * Get the log sense information to understand whether the
5901 		 * the powercycle counts have gone beyond the threshhold.
5902 		 */
5903 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5904 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5905 
5906 		mutex_enter(SD_MUTEX(un));
5907 		log_sense_page = un->un_start_stop_cycle_page;
5908 		mutex_exit(SD_MUTEX(un));
5909 
5910 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
5911 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
5912 #ifdef	SDDEBUG
5913 		if (sd_force_pm_supported) {
5914 			/* Force a successful result */
5915 			rval = 0;
5916 		}
5917 #endif
5918 		if (rval != 0) {
5919 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5920 			    "Log Sense Failed\n");
5921 			kmem_free(log_page_data, log_page_size);
5922 			/* Cannot support power management on those drives */
5923 
5924 			if (got_semaphore_here != 0) {
5925 				sema_v(&un->un_semoclose);
5926 			}
5927 			/*
5928 			 * On exit put the state back to it's original value
5929 			 * and broadcast to anyone waiting for the power
5930 			 * change completion.
5931 			 */
5932 			mutex_enter(SD_MUTEX(un));
5933 			un->un_state = state_before_pm;
5934 			cv_broadcast(&un->un_suspend_cv);
5935 			mutex_exit(SD_MUTEX(un));
5936 			SD_TRACE(SD_LOG_IO_PM, un,
5937 			    "sdpower: exit, Log Sense Failed.\n");
5938 			return (DDI_FAILURE);
5939 		}
5940 
5941 		/*
5942 		 * From the page data - Convert the essential information to
5943 		 * pm_trans_data
5944 		 */
5945 		maxcycles =
5946 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
5947 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
5948 
5949 		sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
5950 
5951 		ncycles =
5952 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
5953 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
5954 
5955 		sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
5956 
5957 		for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
5958 			sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
5959 			    log_page_data[8+i];
5960 		}
5961 
5962 		kmem_free(log_page_data, log_page_size);
5963 
5964 		/*
5965 		 * Call pm_trans_check routine to get the Ok from
5966 		 * the global policy
5967 		 */
5968 
5969 		sd_pm_tran_data.format = DC_SCSI_FORMAT;
5970 		sd_pm_tran_data.un.scsi_cycles.flag = 0;
5971 
5972 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
5973 #ifdef	SDDEBUG
5974 		if (sd_force_pm_supported) {
5975 			/* Force a successful result */
5976 			rval = 1;
5977 		}
5978 #endif
5979 		switch (rval) {
5980 		case 0:
5981 			/*
5982 			 * Not Ok to Power cycle or error in parameters passed
5983 			 * Would have given the advised time to consider power
5984 			 * cycle. Based on the new intvlp parameter we are
5985 			 * supposed to pretend we are busy so that pm framework
5986 			 * will never call our power entry point. Because of
5987 			 * that install a timeout handler and wait for the
5988 			 * recommended time to elapse so that power management
5989 			 * can be effective again.
5990 			 *
5991 			 * To effect this behavior, call pm_busy_component to
5992 			 * indicate to the framework this device is busy.
5993 			 * By not adjusting un_pm_count the rest of PM in
5994 			 * the driver will function normally, and independant
5995 			 * of this but because the framework is told the device
5996 			 * is busy it won't attempt powering down until it gets
5997 			 * a matching idle. The timeout handler sends this.
5998 			 * Note: sd_pm_entry can't be called here to do this
5999 			 * because sdpower may have been called as a result
6000 			 * of a call to pm_raise_power from within sd_pm_entry.
6001 			 *
6002 			 * If a timeout handler is already active then
6003 			 * don't install another.
6004 			 */
6005 			mutex_enter(&un->un_pm_mutex);
6006 			if (un->un_pm_timeid == NULL) {
6007 				un->un_pm_timeid =
6008 				    timeout(sd_pm_timeout_handler,
6009 				    un, intvlp * drv_usectohz(1000000));
6010 				mutex_exit(&un->un_pm_mutex);
6011 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6012 			} else {
6013 				mutex_exit(&un->un_pm_mutex);
6014 			}
6015 			if (got_semaphore_here != 0) {
6016 				sema_v(&un->un_semoclose);
6017 			}
6018 			/*
6019 			 * On exit put the state back to it's original value
6020 			 * and broadcast to anyone waiting for the power
6021 			 * change completion.
6022 			 */
6023 			mutex_enter(SD_MUTEX(un));
6024 			un->un_state = state_before_pm;
6025 			cv_broadcast(&un->un_suspend_cv);
6026 			mutex_exit(SD_MUTEX(un));
6027 
6028 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6029 			    "trans check Failed, not ok to power cycle.\n");
6030 			return (DDI_FAILURE);
6031 
6032 		case -1:
6033 			if (got_semaphore_here != 0) {
6034 				sema_v(&un->un_semoclose);
6035 			}
6036 			/*
6037 			 * On exit put the state back to it's original value
6038 			 * and broadcast to anyone waiting for the power
6039 			 * change completion.
6040 			 */
6041 			mutex_enter(SD_MUTEX(un));
6042 			un->un_state = state_before_pm;
6043 			cv_broadcast(&un->un_suspend_cv);
6044 			mutex_exit(SD_MUTEX(un));
6045 			SD_TRACE(SD_LOG_IO_PM, un,
6046 			    "sdpower: exit, trans check command Failed.\n");
6047 			return (DDI_FAILURE);
6048 		}
6049 	}
6050 
6051 	if (level == SD_SPINDLE_OFF) {
6052 		/*
6053 		 * Save the last state... if the STOP FAILS we need it
6054 		 * for restoring
6055 		 */
6056 		mutex_enter(SD_MUTEX(un));
6057 		save_state = un->un_last_state;
6058 		/*
6059 		 * There must not be any cmds. getting processed
6060 		 * in the driver when we get here. Power to the
6061 		 * device is potentially going off.
6062 		 */
6063 		ASSERT(un->un_ncmds_in_driver == 0);
6064 		mutex_exit(SD_MUTEX(un));
6065 
6066 		/*
6067 		 * For now suspend the device completely before spindle is
6068 		 * turned off
6069 		 */
6070 		if ((rval = sd_ddi_pm_suspend(un)) == DDI_FAILURE) {
6071 			if (got_semaphore_here != 0) {
6072 				sema_v(&un->un_semoclose);
6073 			}
6074 			/*
6075 			 * On exit put the state back to it's original value
6076 			 * and broadcast to anyone waiting for the power
6077 			 * change completion.
6078 			 */
6079 			mutex_enter(SD_MUTEX(un));
6080 			un->un_state = state_before_pm;
6081 			cv_broadcast(&un->un_suspend_cv);
6082 			mutex_exit(SD_MUTEX(un));
6083 			SD_TRACE(SD_LOG_IO_PM, un,
6084 			    "sdpower: exit, PM suspend Failed.\n");
6085 			return (DDI_FAILURE);
6086 		}
6087 	}
6088 
6089 	/*
6090 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6091 	 * close, or strategy. Dump no long uses this routine, it uses it's
6092 	 * own code so it can be done in polled mode.
6093 	 */
6094 
6095 	medium_present = TRUE;
6096 
6097 	/*
6098 	 * When powering up, issue a TUR in case the device is at unit
6099 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6100 	 * a deadlock on un_pm_busy_cv will occur.
6101 	 */
6102 	if (level == SD_SPINDLE_ON) {
6103 		(void) sd_send_scsi_TEST_UNIT_READY(un,
6104 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6105 	}
6106 
6107 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
6108 	    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
6109 
6110 	sval = sd_send_scsi_START_STOP_UNIT(un,
6111 	    ((level == SD_SPINDLE_ON) ? SD_TARGET_START : SD_TARGET_STOP),
6112 	    SD_PATH_DIRECT);
6113 	/* Command failed, check for media present. */
6114 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
6115 		medium_present = FALSE;
6116 	}
6117 
6118 	/*
6119 	 * The conditions of interest here are:
6120 	 *   if a spindle off with media present fails,
6121 	 *	then restore the state and return an error.
6122 	 *   else if a spindle on fails,
6123 	 *	then return an error (there's no state to restore).
6124 	 * In all other cases we setup for the new state
6125 	 * and return success.
6126 	 */
6127 	switch (level) {
6128 	case SD_SPINDLE_OFF:
6129 		if ((medium_present == TRUE) && (sval != 0)) {
6130 			/* The stop command from above failed */
6131 			rval = DDI_FAILURE;
6132 			/*
6133 			 * The stop command failed, and we have media
6134 			 * present. Put the level back by calling the
6135 			 * sd_pm_resume() and set the state back to
6136 			 * it's previous value.
6137 			 */
6138 			(void) sd_ddi_pm_resume(un);
6139 			mutex_enter(SD_MUTEX(un));
6140 			un->un_last_state = save_state;
6141 			mutex_exit(SD_MUTEX(un));
6142 			break;
6143 		}
6144 		/*
6145 		 * The stop command from above succeeded.
6146 		 */
6147 		if (un->un_f_monitor_media_state) {
6148 			/*
6149 			 * Terminate watch thread in case of removable media
6150 			 * devices going into low power state. This is as per
6151 			 * the requirements of pm framework, otherwise commands
6152 			 * will be generated for the device (through watch
6153 			 * thread), even when the device is in low power state.
6154 			 */
6155 			mutex_enter(SD_MUTEX(un));
6156 			un->un_f_watcht_stopped = FALSE;
6157 			if (un->un_swr_token != NULL) {
6158 				opaque_t temp_token = un->un_swr_token;
6159 				un->un_f_watcht_stopped = TRUE;
6160 				un->un_swr_token = NULL;
6161 				mutex_exit(SD_MUTEX(un));
6162 				(void) scsi_watch_request_terminate(temp_token,
6163 				    SCSI_WATCH_TERMINATE_WAIT);
6164 			} else {
6165 				mutex_exit(SD_MUTEX(un));
6166 			}
6167 		}
6168 		break;
6169 
6170 	default:	/* The level requested is spindle on... */
6171 		/*
6172 		 * Legacy behavior: return success on a failed spinup
6173 		 * if there is no media in the drive.
6174 		 * Do this by looking at medium_present here.
6175 		 */
6176 		if ((sval != 0) && medium_present) {
6177 			/* The start command from above failed */
6178 			rval = DDI_FAILURE;
6179 			break;
6180 		}
6181 		/*
6182 		 * The start command from above succeeded
6183 		 * Resume the devices now that we have
6184 		 * started the disks
6185 		 */
6186 		(void) sd_ddi_pm_resume(un);
6187 
6188 		/*
6189 		 * Resume the watch thread since it was suspended
6190 		 * when the device went into low power mode.
6191 		 */
6192 		if (un->un_f_monitor_media_state) {
6193 			mutex_enter(SD_MUTEX(un));
6194 			if (un->un_f_watcht_stopped == TRUE) {
6195 				opaque_t temp_token;
6196 
6197 				un->un_f_watcht_stopped = FALSE;
6198 				mutex_exit(SD_MUTEX(un));
6199 				temp_token = scsi_watch_request_submit(
6200 				    SD_SCSI_DEVP(un),
6201 				    sd_check_media_time,
6202 				    SENSE_LENGTH, sd_media_watch_cb,
6203 				    (caddr_t)dev);
6204 				mutex_enter(SD_MUTEX(un));
6205 				un->un_swr_token = temp_token;
6206 			}
6207 			mutex_exit(SD_MUTEX(un));
6208 		}
6209 	}
6210 	if (got_semaphore_here != 0) {
6211 		sema_v(&un->un_semoclose);
6212 	}
6213 	/*
6214 	 * On exit put the state back to it's original value
6215 	 * and broadcast to anyone waiting for the power
6216 	 * change completion.
6217 	 */
6218 	mutex_enter(SD_MUTEX(un));
6219 	un->un_state = state_before_pm;
6220 	cv_broadcast(&un->un_suspend_cv);
6221 	mutex_exit(SD_MUTEX(un));
6222 
6223 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
6224 
6225 	return (rval);
6226 }
6227 
6228 
6229 
6230 /*
6231  *    Function: sdattach
6232  *
6233  * Description: Driver's attach(9e) entry point function.
6234  *
6235  *   Arguments: devi - opaque device info handle
6236  *		cmd  - attach  type
6237  *
6238  * Return Code: DDI_SUCCESS
6239  *		DDI_FAILURE
6240  *
6241  *     Context: Kernel thread context
6242  */
6243 
6244 static int
6245 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
6246 {
6247 	switch (cmd) {
6248 	case DDI_ATTACH:
6249 		return (sd_unit_attach(devi));
6250 	case DDI_RESUME:
6251 		return (sd_ddi_resume(devi));
6252 	default:
6253 		break;
6254 	}
6255 	return (DDI_FAILURE);
6256 }
6257 
6258 
6259 /*
6260  *    Function: sddetach
6261  *
6262  * Description: Driver's detach(9E) entry point function.
6263  *
6264  *   Arguments: devi - opaque device info handle
6265  *		cmd  - detach  type
6266  *
6267  * Return Code: DDI_SUCCESS
6268  *		DDI_FAILURE
6269  *
6270  *     Context: Kernel thread context
6271  */
6272 
6273 static int
6274 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
6275 {
6276 	switch (cmd) {
6277 	case DDI_DETACH:
6278 		return (sd_unit_detach(devi));
6279 	case DDI_SUSPEND:
6280 		return (sd_ddi_suspend(devi));
6281 	default:
6282 		break;
6283 	}
6284 	return (DDI_FAILURE);
6285 }
6286 
6287 
6288 /*
6289  *     Function: sd_sync_with_callback
6290  *
6291  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
6292  *		 state while the callback routine is active.
6293  *
6294  *    Arguments: un: softstate structure for the instance
6295  *
6296  *	Context: Kernel thread context
6297  */
6298 
6299 static void
6300 sd_sync_with_callback(struct sd_lun *un)
6301 {
6302 	ASSERT(un != NULL);
6303 
6304 	mutex_enter(SD_MUTEX(un));
6305 
6306 	ASSERT(un->un_in_callback >= 0);
6307 
6308 	while (un->un_in_callback > 0) {
6309 		mutex_exit(SD_MUTEX(un));
6310 		delay(2);
6311 		mutex_enter(SD_MUTEX(un));
6312 	}
6313 
6314 	mutex_exit(SD_MUTEX(un));
6315 }
6316 
6317 /*
6318  *    Function: sd_unit_attach
6319  *
6320  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
6321  *		the soft state structure for the device and performs
6322  *		all necessary structure and device initializations.
6323  *
6324  *   Arguments: devi: the system's dev_info_t for the device.
6325  *
6326  * Return Code: DDI_SUCCESS if attach is successful.
6327  *		DDI_FAILURE if any part of the attach fails.
6328  *
6329  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
6330  *		Kernel thread context only.  Can sleep.
6331  */
6332 
6333 static int
6334 sd_unit_attach(dev_info_t *devi)
6335 {
6336 	struct	scsi_device	*devp;
6337 	struct	sd_lun		*un;
6338 	char			*variantp;
6339 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
6340 	int	instance;
6341 	int	rval;
6342 	int	wc_enabled;
6343 	int	tgt;
6344 	uint64_t	capacity;
6345 	uint_t		lbasize = 0;
6346 	dev_info_t	*pdip = ddi_get_parent(devi);
6347 	int		offbyone = 0;
6348 	int		geom_label_valid = 0;
6349 
6350 	/*
6351 	 * Retrieve the target driver's private data area. This was set
6352 	 * up by the HBA.
6353 	 */
6354 	devp = ddi_get_driver_private(devi);
6355 
6356 	/*
6357 	 * Retrieve the target ID of the device.
6358 	 */
6359 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
6360 	    SCSI_ADDR_PROP_TARGET, -1);
6361 
6362 	/*
6363 	 * Since we have no idea what state things were left in by the last
6364 	 * user of the device, set up some 'default' settings, ie. turn 'em
6365 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
6366 	 * Do this before the scsi_probe, which sends an inquiry.
6367 	 * This is a fix for bug (4430280).
6368 	 * Of special importance is wide-xfer. The drive could have been left
6369 	 * in wide transfer mode by the last driver to communicate with it,
6370 	 * this includes us. If that's the case, and if the following is not
6371 	 * setup properly or we don't re-negotiate with the drive prior to
6372 	 * transferring data to/from the drive, it causes bus parity errors,
6373 	 * data overruns, and unexpected interrupts. This first occurred when
6374 	 * the fix for bug (4378686) was made.
6375 	 */
6376 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
6377 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
6378 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
6379 
6380 	/*
6381 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
6382 	 * on a target. Setting it per lun instance actually sets the
6383 	 * capability of this target, which affects those luns already
6384 	 * attached on the same target. So during attach, we can only disable
6385 	 * this capability only when no other lun has been attached on this
6386 	 * target. By doing this, we assume a target has the same tagged-qing
6387 	 * capability for every lun. The condition can be removed when HBA
6388 	 * is changed to support per lun based tagged-qing capability.
6389 	 */
6390 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
6391 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
6392 	}
6393 
6394 	/*
6395 	 * Use scsi_probe() to issue an INQUIRY command to the device.
6396 	 * This call will allocate and fill in the scsi_inquiry structure
6397 	 * and point the sd_inq member of the scsi_device structure to it.
6398 	 * If the attach succeeds, then this memory will not be de-allocated
6399 	 * (via scsi_unprobe()) until the instance is detached.
6400 	 */
6401 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
6402 		goto probe_failed;
6403 	}
6404 
6405 	/*
6406 	 * Check the device type as specified in the inquiry data and
6407 	 * claim it if it is of a type that we support.
6408 	 */
6409 	switch (devp->sd_inq->inq_dtype) {
6410 	case DTYPE_DIRECT:
6411 		break;
6412 	case DTYPE_RODIRECT:
6413 		break;
6414 	case DTYPE_OPTICAL:
6415 		break;
6416 	case DTYPE_NOTPRESENT:
6417 	default:
6418 		/* Unsupported device type; fail the attach. */
6419 		goto probe_failed;
6420 	}
6421 
6422 	/*
6423 	 * Allocate the soft state structure for this unit.
6424 	 *
6425 	 * We rely upon this memory being set to all zeroes by
6426 	 * ddi_soft_state_zalloc().  We assume that any member of the
6427 	 * soft state structure that is not explicitly initialized by
6428 	 * this routine will have a value of zero.
6429 	 */
6430 	instance = ddi_get_instance(devp->sd_dev);
6431 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
6432 		goto probe_failed;
6433 	}
6434 
6435 	/*
6436 	 * Retrieve a pointer to the newly-allocated soft state.
6437 	 *
6438 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
6439 	 * was successful, unless something has gone horribly wrong and the
6440 	 * ddi's soft state internals are corrupt (in which case it is
6441 	 * probably better to halt here than just fail the attach....)
6442 	 */
6443 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
6444 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
6445 		    instance);
6446 		/*NOTREACHED*/
6447 	}
6448 
6449 	/*
6450 	 * Link the back ptr of the driver soft state to the scsi_device
6451 	 * struct for this lun.
6452 	 * Save a pointer to the softstate in the driver-private area of
6453 	 * the scsi_device struct.
6454 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
6455 	 * we first set un->un_sd below.
6456 	 */
6457 	un->un_sd = devp;
6458 	devp->sd_private = (opaque_t)un;
6459 
6460 	/*
6461 	 * The following must be after devp is stored in the soft state struct.
6462 	 */
6463 #ifdef SDDEBUG
6464 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6465 	    "%s_unit_attach: un:0x%p instance:%d\n",
6466 	    ddi_driver_name(devi), un, instance);
6467 #endif
6468 
6469 	/*
6470 	 * Set up the device type and node type (for the minor nodes).
6471 	 * By default we assume that the device can at least support the
6472 	 * Common Command Set. Call it a CD-ROM if it reports itself
6473 	 * as a RODIRECT device.
6474 	 */
6475 	switch (devp->sd_inq->inq_dtype) {
6476 	case DTYPE_RODIRECT:
6477 		un->un_node_type = DDI_NT_CD_CHAN;
6478 		un->un_ctype	 = CTYPE_CDROM;
6479 		break;
6480 	case DTYPE_OPTICAL:
6481 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6482 		un->un_ctype	 = CTYPE_ROD;
6483 		break;
6484 	default:
6485 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6486 		un->un_ctype	 = CTYPE_CCS;
6487 		break;
6488 	}
6489 
6490 	/*
6491 	 * Try to read the interconnect type from the HBA.
6492 	 *
6493 	 * Note: This driver is currently compiled as two binaries, a parallel
6494 	 * scsi version (sd) and a fibre channel version (ssd). All functional
6495 	 * differences are determined at compile time. In the future a single
6496 	 * binary will be provided and the inteconnect type will be used to
6497 	 * differentiate between fibre and parallel scsi behaviors. At that time
6498 	 * it will be necessary for all fibre channel HBAs to support this
6499 	 * property.
6500 	 *
6501 	 * set un_f_is_fiber to TRUE ( default fiber )
6502 	 */
6503 	un->un_f_is_fibre = TRUE;
6504 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
6505 	case INTERCONNECT_SSA:
6506 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
6507 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6508 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
6509 		break;
6510 	case INTERCONNECT_PARALLEL:
6511 		un->un_f_is_fibre = FALSE;
6512 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
6513 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6514 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
6515 		break;
6516 	case INTERCONNECT_SATA:
6517 		un->un_f_is_fibre = FALSE;
6518 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
6519 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6520 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
6521 		break;
6522 	case INTERCONNECT_FIBRE:
6523 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
6524 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6525 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
6526 		break;
6527 	case INTERCONNECT_FABRIC:
6528 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
6529 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
6530 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6531 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
6532 		break;
6533 	default:
6534 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
6535 		/*
6536 		 * The HBA does not support the "interconnect-type" property
6537 		 * (or did not provide a recognized type).
6538 		 *
6539 		 * Note: This will be obsoleted when a single fibre channel
6540 		 * and parallel scsi driver is delivered. In the meantime the
6541 		 * interconnect type will be set to the platform default.If that
6542 		 * type is not parallel SCSI, it means that we should be
6543 		 * assuming "ssd" semantics. However, here this also means that
6544 		 * the FC HBA is not supporting the "interconnect-type" property
6545 		 * like we expect it to, so log this occurrence.
6546 		 */
6547 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
6548 		if (!SD_IS_PARALLEL_SCSI(un)) {
6549 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6550 			    "sd_unit_attach: un:0x%p Assuming "
6551 			    "INTERCONNECT_FIBRE\n", un);
6552 		} else {
6553 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6554 			    "sd_unit_attach: un:0x%p Assuming "
6555 			    "INTERCONNECT_PARALLEL\n", un);
6556 			un->un_f_is_fibre = FALSE;
6557 		}
6558 #else
6559 		/*
6560 		 * Note: This source will be implemented when a single fibre
6561 		 * channel and parallel scsi driver is delivered. The default
6562 		 * will be to assume that if a device does not support the
6563 		 * "interconnect-type" property it is a parallel SCSI HBA and
6564 		 * we will set the interconnect type for parallel scsi.
6565 		 */
6566 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
6567 		un->un_f_is_fibre = FALSE;
6568 #endif
6569 		break;
6570 	}
6571 
6572 	if (un->un_f_is_fibre == TRUE) {
6573 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
6574 		    SCSI_VERSION_3) {
6575 			switch (un->un_interconnect_type) {
6576 			case SD_INTERCONNECT_FIBRE:
6577 			case SD_INTERCONNECT_SSA:
6578 				un->un_node_type = DDI_NT_BLOCK_WWN;
6579 				break;
6580 			default:
6581 				break;
6582 			}
6583 		}
6584 	}
6585 
6586 	/*
6587 	 * Initialize the Request Sense command for the target
6588 	 */
6589 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
6590 		goto alloc_rqs_failed;
6591 	}
6592 
6593 	/*
6594 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
6595 	 * with separate binary for sd and ssd.
6596 	 *
6597 	 * x86 has 1 binary, un_retry_count is set base on connection type.
6598 	 * The hardcoded values will go away when Sparc uses 1 binary
6599 	 * for sd and ssd.  This hardcoded values need to match
6600 	 * SD_RETRY_COUNT in sddef.h
6601 	 * The value used is base on interconnect type.
6602 	 * fibre = 3, parallel = 5
6603 	 */
6604 #if defined(__i386) || defined(__amd64)
6605 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
6606 #else
6607 	un->un_retry_count = SD_RETRY_COUNT;
6608 #endif
6609 
6610 	/*
6611 	 * Set the per disk retry count to the default number of retries
6612 	 * for disks and CDROMs. This value can be overridden by the
6613 	 * disk property list or an entry in sd.conf.
6614 	 */
6615 	un->un_notready_retry_count =
6616 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
6617 	    : DISK_NOT_READY_RETRY_COUNT(un);
6618 
6619 	/*
6620 	 * Set the busy retry count to the default value of un_retry_count.
6621 	 * This can be overridden by entries in sd.conf or the device
6622 	 * config table.
6623 	 */
6624 	un->un_busy_retry_count = un->un_retry_count;
6625 
6626 	/*
6627 	 * Init the reset threshold for retries.  This number determines
6628 	 * how many retries must be performed before a reset can be issued
6629 	 * (for certain error conditions). This can be overridden by entries
6630 	 * in sd.conf or the device config table.
6631 	 */
6632 	un->un_reset_retry_count = (un->un_retry_count / 2);
6633 
6634 	/*
6635 	 * Set the victim_retry_count to the default un_retry_count
6636 	 */
6637 	un->un_victim_retry_count = (2 * un->un_retry_count);
6638 
6639 	/*
6640 	 * Set the reservation release timeout to the default value of
6641 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
6642 	 * device config table.
6643 	 */
6644 	un->un_reserve_release_time = 5;
6645 
6646 	/*
6647 	 * Set up the default maximum transfer size. Note that this may
6648 	 * get updated later in the attach, when setting up default wide
6649 	 * operations for disks.
6650 	 */
6651 #if defined(__i386) || defined(__amd64)
6652 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
6653 #else
6654 	un->un_max_xfer_size = (uint_t)maxphys;
6655 #endif
6656 
6657 	/*
6658 	 * Get "allow bus device reset" property (defaults to "enabled" if
6659 	 * the property was not defined). This is to disable bus resets for
6660 	 * certain kinds of error recovery. Note: In the future when a run-time
6661 	 * fibre check is available the soft state flag should default to
6662 	 * enabled.
6663 	 */
6664 	if (un->un_f_is_fibre == TRUE) {
6665 		un->un_f_allow_bus_device_reset = TRUE;
6666 	} else {
6667 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
6668 		    "allow-bus-device-reset", 1) != 0) {
6669 			un->un_f_allow_bus_device_reset = TRUE;
6670 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6671 			    "sd_unit_attach: un:0x%p Bus device reset "
6672 			    "enabled\n", un);
6673 		} else {
6674 			un->un_f_allow_bus_device_reset = FALSE;
6675 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6676 			    "sd_unit_attach: un:0x%p Bus device reset "
6677 			    "disabled\n", un);
6678 		}
6679 	}
6680 
6681 	/*
6682 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
6683 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
6684 	 *
6685 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
6686 	 * property. The new "variant" property with a value of "atapi" has been
6687 	 * introduced so that future 'variants' of standard SCSI behavior (like
6688 	 * atapi) could be specified by the underlying HBA drivers by supplying
6689 	 * a new value for the "variant" property, instead of having to define a
6690 	 * new property.
6691 	 */
6692 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
6693 		un->un_f_cfg_is_atapi = TRUE;
6694 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6695 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
6696 	}
6697 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
6698 	    &variantp) == DDI_PROP_SUCCESS) {
6699 		if (strcmp(variantp, "atapi") == 0) {
6700 			un->un_f_cfg_is_atapi = TRUE;
6701 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6702 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
6703 		}
6704 		ddi_prop_free(variantp);
6705 	}
6706 
6707 	un->un_cmd_timeout	= SD_IO_TIME;
6708 
6709 	/* Info on current states, statuses, etc. (Updated frequently) */
6710 	un->un_state		= SD_STATE_NORMAL;
6711 	un->un_last_state	= SD_STATE_NORMAL;
6712 
6713 	/* Control & status info for command throttling */
6714 	un->un_throttle		= sd_max_throttle;
6715 	un->un_saved_throttle	= sd_max_throttle;
6716 	un->un_min_throttle	= sd_min_throttle;
6717 
6718 	if (un->un_f_is_fibre == TRUE) {
6719 		un->un_f_use_adaptive_throttle = TRUE;
6720 	} else {
6721 		un->un_f_use_adaptive_throttle = FALSE;
6722 	}
6723 
6724 	/* Removable media support. */
6725 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
6726 	un->un_mediastate		= DKIO_NONE;
6727 	un->un_specified_mediastate	= DKIO_NONE;
6728 
6729 	/* CVs for suspend/resume (PM or DR) */
6730 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
6731 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
6732 
6733 	/* Power management support. */
6734 	un->un_power_level = SD_SPINDLE_UNINIT;
6735 
6736 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
6737 	un->un_f_wcc_inprog = 0;
6738 
6739 	/*
6740 	 * The open/close semaphore is used to serialize threads executing
6741 	 * in the driver's open & close entry point routines for a given
6742 	 * instance.
6743 	 */
6744 	(void) sema_init(&un->un_semoclose, 1, NULL, SEMA_DRIVER, NULL);
6745 
6746 	/*
6747 	 * The conf file entry and softstate variable is a forceful override,
6748 	 * meaning a non-zero value must be entered to change the default.
6749 	 */
6750 	un->un_f_disksort_disabled = FALSE;
6751 
6752 	/*
6753 	 * Retrieve the properties from the static driver table or the driver
6754 	 * configuration file (.conf) for this unit and update the soft state
6755 	 * for the device as needed for the indicated properties.
6756 	 * Note: the property configuration needs to occur here as some of the
6757 	 * following routines may have dependancies on soft state flags set
6758 	 * as part of the driver property configuration.
6759 	 */
6760 	sd_read_unit_properties(un);
6761 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6762 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
6763 
6764 	/*
6765 	 * Only if a device has "hotpluggable" property, it is
6766 	 * treated as hotpluggable device. Otherwise, it is
6767 	 * regarded as non-hotpluggable one.
6768 	 */
6769 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
6770 	    -1) != -1) {
6771 		un->un_f_is_hotpluggable = TRUE;
6772 	}
6773 
6774 	/*
6775 	 * set unit's attributes(flags) according to "hotpluggable" and
6776 	 * RMB bit in INQUIRY data.
6777 	 */
6778 	sd_set_unit_attributes(un, devi);
6779 
6780 	/*
6781 	 * By default, we mark the capacity, lbasize, and geometry
6782 	 * as invalid. Only if we successfully read a valid capacity
6783 	 * will we update the un_blockcount and un_tgt_blocksize with the
6784 	 * valid values (the geometry will be validated later).
6785 	 */
6786 	un->un_f_blockcount_is_valid	= FALSE;
6787 	un->un_f_tgt_blocksize_is_valid	= FALSE;
6788 
6789 	/*
6790 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
6791 	 * otherwise.
6792 	 */
6793 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
6794 	un->un_blockcount = 0;
6795 
6796 	/*
6797 	 * Set up the per-instance info needed to determine the correct
6798 	 * CDBs and other info for issuing commands to the target.
6799 	 */
6800 	sd_init_cdb_limits(un);
6801 
6802 	/*
6803 	 * Set up the IO chains to use, based upon the target type.
6804 	 */
6805 	if (un->un_f_non_devbsize_supported) {
6806 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
6807 	} else {
6808 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
6809 	}
6810 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
6811 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
6812 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
6813 
6814 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
6815 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
6816 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
6817 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
6818 
6819 
6820 	if (ISCD(un)) {
6821 		un->un_additional_codes = sd_additional_codes;
6822 	} else {
6823 		un->un_additional_codes = NULL;
6824 	}
6825 
6826 	/*
6827 	 * Create the kstats here so they can be available for attach-time
6828 	 * routines that send commands to the unit (either polled or via
6829 	 * sd_send_scsi_cmd).
6830 	 *
6831 	 * Note: This is a critical sequence that needs to be maintained:
6832 	 *	1) Instantiate the kstats here, before any routines using the
6833 	 *	   iopath (i.e. sd_send_scsi_cmd).
6834 	 *	2) Instantiate and initialize the partition stats
6835 	 *	   (sd_set_pstats).
6836 	 *	3) Initialize the error stats (sd_set_errstats), following
6837 	 *	   sd_validate_geometry(),sd_register_devid(),
6838 	 *	   and sd_cache_control().
6839 	 */
6840 
6841 	un->un_stats = kstat_create(sd_label, instance,
6842 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
6843 	if (un->un_stats != NULL) {
6844 		un->un_stats->ks_lock = SD_MUTEX(un);
6845 		kstat_install(un->un_stats);
6846 	}
6847 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6848 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
6849 
6850 	sd_create_errstats(un, instance);
6851 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6852 	    "sd_unit_attach: un:0x%p errstats created\n", un);
6853 
6854 	/*
6855 	 * The following if/else code was relocated here from below as part
6856 	 * of the fix for bug (4430280). However with the default setup added
6857 	 * on entry to this routine, it's no longer absolutely necessary for
6858 	 * this to be before the call to sd_spin_up_unit.
6859 	 */
6860 	if (SD_IS_PARALLEL_SCSI(un) || SD_IS_SERIAL(un)) {
6861 		/*
6862 		 * If SCSI-2 tagged queueing is supported by the target
6863 		 * and by the host adapter then we will enable it.
6864 		 */
6865 		un->un_tagflags = 0;
6866 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) &&
6867 		    (devp->sd_inq->inq_cmdque) &&
6868 		    (un->un_f_arq_enabled == TRUE)) {
6869 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
6870 			    1, 1) == 1) {
6871 				un->un_tagflags = FLAG_STAG;
6872 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6873 				    "sd_unit_attach: un:0x%p tag queueing "
6874 				    "enabled\n", un);
6875 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
6876 			    "untagged-qing", 0) == 1) {
6877 				un->un_f_opt_queueing = TRUE;
6878 				un->un_saved_throttle = un->un_throttle =
6879 				    min(un->un_throttle, 3);
6880 			} else {
6881 				un->un_f_opt_queueing = FALSE;
6882 				un->un_saved_throttle = un->un_throttle = 1;
6883 			}
6884 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
6885 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
6886 			/* The Host Adapter supports internal queueing. */
6887 			un->un_f_opt_queueing = TRUE;
6888 			un->un_saved_throttle = un->un_throttle =
6889 			    min(un->un_throttle, 3);
6890 		} else {
6891 			un->un_f_opt_queueing = FALSE;
6892 			un->un_saved_throttle = un->un_throttle = 1;
6893 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6894 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
6895 		}
6896 
6897 		/*
6898 		 * Enable large transfers for SATA/SAS drives
6899 		 */
6900 		if (SD_IS_SERIAL(un)) {
6901 			un->un_max_xfer_size =
6902 			    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
6903 			    sd_max_xfer_size, SD_MAX_XFER_SIZE);
6904 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6905 			    "sd_unit_attach: un:0x%p max transfer "
6906 			    "size=0x%x\n", un, un->un_max_xfer_size);
6907 
6908 		}
6909 
6910 		/* Setup or tear down default wide operations for disks */
6911 
6912 		/*
6913 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
6914 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
6915 		 * system and be set to different values. In the future this
6916 		 * code may need to be updated when the ssd module is
6917 		 * obsoleted and removed from the system. (4299588)
6918 		 */
6919 		if (SD_IS_PARALLEL_SCSI(un) &&
6920 		    (devp->sd_inq->inq_rdf == RDF_SCSI2) &&
6921 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
6922 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
6923 			    1, 1) == 1) {
6924 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6925 				    "sd_unit_attach: un:0x%p Wide Transfer "
6926 				    "enabled\n", un);
6927 			}
6928 
6929 			/*
6930 			 * If tagged queuing has also been enabled, then
6931 			 * enable large xfers
6932 			 */
6933 			if (un->un_saved_throttle == sd_max_throttle) {
6934 				un->un_max_xfer_size =
6935 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
6936 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
6937 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6938 				    "sd_unit_attach: un:0x%p max transfer "
6939 				    "size=0x%x\n", un, un->un_max_xfer_size);
6940 			}
6941 		} else {
6942 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
6943 			    0, 1) == 1) {
6944 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6945 				    "sd_unit_attach: un:0x%p "
6946 				    "Wide Transfer disabled\n", un);
6947 			}
6948 		}
6949 	} else {
6950 		un->un_tagflags = FLAG_STAG;
6951 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
6952 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
6953 	}
6954 
6955 	/*
6956 	 * If this target supports LUN reset, try to enable it.
6957 	 */
6958 	if (un->un_f_lun_reset_enabled) {
6959 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
6960 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
6961 			    "un:0x%p lun_reset capability set\n", un);
6962 		} else {
6963 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
6964 			    "un:0x%p lun-reset capability not set\n", un);
6965 		}
6966 	}
6967 
6968 	/*
6969 	 * At this point in the attach, we have enough info in the
6970 	 * soft state to be able to issue commands to the target.
6971 	 *
6972 	 * All command paths used below MUST issue their commands as
6973 	 * SD_PATH_DIRECT. This is important as intermediate layers
6974 	 * are not all initialized yet (such as PM).
6975 	 */
6976 
6977 	/*
6978 	 * Send a TEST UNIT READY command to the device. This should clear
6979 	 * any outstanding UNIT ATTENTION that may be present.
6980 	 *
6981 	 * Note: Don't check for success, just track if there is a reservation,
6982 	 * this is a throw away command to clear any unit attentions.
6983 	 *
6984 	 * Note: This MUST be the first command issued to the target during
6985 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
6986 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
6987 	 * with attempts at spinning up a device with no media.
6988 	 */
6989 	if (sd_send_scsi_TEST_UNIT_READY(un, SD_DONT_RETRY_TUR) == EACCES) {
6990 		reservation_flag = SD_TARGET_IS_RESERVED;
6991 	}
6992 
6993 	/*
6994 	 * If the device is NOT a removable media device, attempt to spin
6995 	 * it up (using the START_STOP_UNIT command) and read its capacity
6996 	 * (using the READ CAPACITY command).  Note, however, that either
6997 	 * of these could fail and in some cases we would continue with
6998 	 * the attach despite the failure (see below).
6999 	 */
7000 	if (un->un_f_descr_format_supported) {
7001 		switch (sd_spin_up_unit(un)) {
7002 		case 0:
7003 			/*
7004 			 * Spin-up was successful; now try to read the
7005 			 * capacity.  If successful then save the results
7006 			 * and mark the capacity & lbasize as valid.
7007 			 */
7008 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7009 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
7010 
7011 			switch (sd_send_scsi_READ_CAPACITY(un, &capacity,
7012 			    &lbasize, SD_PATH_DIRECT)) {
7013 			case 0: {
7014 				if (capacity > DK_MAX_BLOCKS) {
7015 #ifdef _LP64
7016 					if (capacity + 1 >
7017 					    SD_GROUP1_MAX_ADDRESS) {
7018 						/*
7019 						 * Enable descriptor format
7020 						 * sense data so that we can
7021 						 * get 64 bit sense data
7022 						 * fields.
7023 						 */
7024 						sd_enable_descr_sense(un);
7025 					}
7026 #else
7027 					/* 32-bit kernels can't handle this */
7028 					scsi_log(SD_DEVINFO(un),
7029 					    sd_label, CE_WARN,
7030 					    "disk has %llu blocks, which "
7031 					    "is too large for a 32-bit "
7032 					    "kernel", capacity);
7033 
7034 #if defined(__i386) || defined(__amd64)
7035 					/*
7036 					 * 1TB disk was treated as (1T - 512)B
7037 					 * in the past, so that it might have
7038 					 * valid VTOC and solaris partitions,
7039 					 * we have to allow it to continue to
7040 					 * work.
7041 					 */
7042 					if (capacity -1 > DK_MAX_BLOCKS)
7043 #endif
7044 					goto spinup_failed;
7045 #endif
7046 				}
7047 
7048 				/*
7049 				 * Here it's not necessary to check the case:
7050 				 * the capacity of the device is bigger than
7051 				 * what the max hba cdb can support. Because
7052 				 * sd_send_scsi_READ_CAPACITY will retrieve
7053 				 * the capacity by sending USCSI command, which
7054 				 * is constrained by the max hba cdb. Actually,
7055 				 * sd_send_scsi_READ_CAPACITY will return
7056 				 * EINVAL when using bigger cdb than required
7057 				 * cdb length. Will handle this case in
7058 				 * "case EINVAL".
7059 				 */
7060 
7061 				/*
7062 				 * The following relies on
7063 				 * sd_send_scsi_READ_CAPACITY never
7064 				 * returning 0 for capacity and/or lbasize.
7065 				 */
7066 				sd_update_block_info(un, lbasize, capacity);
7067 
7068 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7069 				    "sd_unit_attach: un:0x%p capacity = %ld "
7070 				    "blocks; lbasize= %ld.\n", un,
7071 				    un->un_blockcount, un->un_tgt_blocksize);
7072 
7073 				break;
7074 			}
7075 			case EINVAL:
7076 				/*
7077 				 * In the case where the max-cdb-length property
7078 				 * is smaller than the required CDB length for
7079 				 * a SCSI device, a target driver can fail to
7080 				 * attach to that device.
7081 				 */
7082 				scsi_log(SD_DEVINFO(un),
7083 				    sd_label, CE_WARN,
7084 				    "disk capacity is too large "
7085 				    "for current cdb length");
7086 				goto spinup_failed;
7087 			case EACCES:
7088 				/*
7089 				 * Should never get here if the spin-up
7090 				 * succeeded, but code it in anyway.
7091 				 * From here, just continue with the attach...
7092 				 */
7093 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7094 				    "sd_unit_attach: un:0x%p "
7095 				    "sd_send_scsi_READ_CAPACITY "
7096 				    "returned reservation conflict\n", un);
7097 				reservation_flag = SD_TARGET_IS_RESERVED;
7098 				break;
7099 			default:
7100 				/*
7101 				 * Likewise, should never get here if the
7102 				 * spin-up succeeded. Just continue with
7103 				 * the attach...
7104 				 */
7105 				break;
7106 			}
7107 			break;
7108 		case EACCES:
7109 			/*
7110 			 * Device is reserved by another host.  In this case
7111 			 * we could not spin it up or read the capacity, but
7112 			 * we continue with the attach anyway.
7113 			 */
7114 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7115 			    "sd_unit_attach: un:0x%p spin-up reservation "
7116 			    "conflict.\n", un);
7117 			reservation_flag = SD_TARGET_IS_RESERVED;
7118 			break;
7119 		default:
7120 			/* Fail the attach if the spin-up failed. */
7121 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7122 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
7123 			goto spinup_failed;
7124 		}
7125 	}
7126 
7127 	/*
7128 	 * Check to see if this is a MMC drive
7129 	 */
7130 	if (ISCD(un)) {
7131 		sd_set_mmc_caps(un);
7132 	}
7133 
7134 
7135 	/*
7136 	 * Add a zero-length attribute to tell the world we support
7137 	 * kernel ioctls (for layered drivers)
7138 	 */
7139 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7140 	    DDI_KERNEL_IOCTL, NULL, 0);
7141 
7142 	/*
7143 	 * Add a boolean property to tell the world we support
7144 	 * the B_FAILFAST flag (for layered drivers)
7145 	 */
7146 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7147 	    "ddi-failfast-supported", NULL, 0);
7148 
7149 	/*
7150 	 * Initialize power management
7151 	 */
7152 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
7153 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
7154 	sd_setup_pm(un, devi);
7155 	if (un->un_f_pm_is_enabled == FALSE) {
7156 		/*
7157 		 * For performance, point to a jump table that does
7158 		 * not include pm.
7159 		 * The direct and priority chains don't change with PM.
7160 		 *
7161 		 * Note: this is currently done based on individual device
7162 		 * capabilities. When an interface for determining system
7163 		 * power enabled state becomes available, or when additional
7164 		 * layers are added to the command chain, these values will
7165 		 * have to be re-evaluated for correctness.
7166 		 */
7167 		if (un->un_f_non_devbsize_supported) {
7168 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
7169 		} else {
7170 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
7171 		}
7172 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
7173 	}
7174 
7175 	/*
7176 	 * This property is set to 0 by HA software to avoid retries
7177 	 * on a reserved disk. (The preferred property name is
7178 	 * "retry-on-reservation-conflict") (1189689)
7179 	 *
7180 	 * Note: The use of a global here can have unintended consequences. A
7181 	 * per instance variable is preferrable to match the capabilities of
7182 	 * different underlying hba's (4402600)
7183 	 */
7184 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
7185 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
7186 	    sd_retry_on_reservation_conflict);
7187 	if (sd_retry_on_reservation_conflict != 0) {
7188 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
7189 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
7190 		    sd_retry_on_reservation_conflict);
7191 	}
7192 
7193 	/* Set up options for QFULL handling. */
7194 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7195 	    "qfull-retries", -1)) != -1) {
7196 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
7197 		    rval, 1);
7198 	}
7199 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7200 	    "qfull-retry-interval", -1)) != -1) {
7201 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
7202 		    rval, 1);
7203 	}
7204 
7205 	/*
7206 	 * This just prints a message that announces the existence of the
7207 	 * device. The message is always printed in the system logfile, but
7208 	 * only appears on the console if the system is booted with the
7209 	 * -v (verbose) argument.
7210 	 */
7211 	ddi_report_dev(devi);
7212 
7213 	un->un_mediastate = DKIO_NONE;
7214 
7215 	cmlb_alloc_handle(&un->un_cmlbhandle);
7216 
7217 #if defined(__i386) || defined(__amd64)
7218 	/*
7219 	 * On x86, compensate for off-by-1 legacy error
7220 	 */
7221 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
7222 	    (lbasize == un->un_sys_blocksize))
7223 		offbyone = CMLB_OFF_BY_ONE;
7224 #endif
7225 
7226 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
7227 	    un->un_f_has_removable_media, un->un_f_is_hotpluggable,
7228 	    un->un_node_type, offbyone, un->un_cmlbhandle,
7229 	    (void *)SD_PATH_DIRECT) != 0) {
7230 		goto cmlb_attach_failed;
7231 	}
7232 
7233 
7234 	/*
7235 	 * Read and validate the device's geometry (ie, disk label)
7236 	 * A new unformatted drive will not have a valid geometry, but
7237 	 * the driver needs to successfully attach to this device so
7238 	 * the drive can be formatted via ioctls.
7239 	 */
7240 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
7241 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
7242 
7243 	mutex_enter(SD_MUTEX(un));
7244 
7245 	/*
7246 	 * Read and initialize the devid for the unit.
7247 	 */
7248 	ASSERT(un->un_errstats != NULL);
7249 	if (un->un_f_devid_supported) {
7250 		sd_register_devid(un, devi, reservation_flag);
7251 	}
7252 	mutex_exit(SD_MUTEX(un));
7253 
7254 #if (defined(__fibre))
7255 	/*
7256 	 * Register callbacks for fibre only.  You can't do this soley
7257 	 * on the basis of the devid_type because this is hba specific.
7258 	 * We need to query our hba capabilities to find out whether to
7259 	 * register or not.
7260 	 */
7261 	if (un->un_f_is_fibre) {
7262 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
7263 			sd_init_event_callbacks(un);
7264 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7265 			    "sd_unit_attach: un:0x%p event callbacks inserted",
7266 			    un);
7267 		}
7268 	}
7269 #endif
7270 
7271 	if (un->un_f_opt_disable_cache == TRUE) {
7272 		/*
7273 		 * Disable both read cache and write cache.  This is
7274 		 * the historic behavior of the keywords in the config file.
7275 		 */
7276 		if (sd_cache_control(un, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
7277 		    0) {
7278 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7279 			    "sd_unit_attach: un:0x%p Could not disable "
7280 			    "caching", un);
7281 			goto devid_failed;
7282 		}
7283 	}
7284 
7285 	/*
7286 	 * Check the value of the WCE bit now and
7287 	 * set un_f_write_cache_enabled accordingly.
7288 	 */
7289 	(void) sd_get_write_cache_enabled(un, &wc_enabled);
7290 	mutex_enter(SD_MUTEX(un));
7291 	un->un_f_write_cache_enabled = (wc_enabled != 0);
7292 	mutex_exit(SD_MUTEX(un));
7293 
7294 	/*
7295 	 * Find out what type of reservation this disk supports.
7296 	 */
7297 	switch (sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS, 0, NULL)) {
7298 	case 0:
7299 		/*
7300 		 * SCSI-3 reservations are supported.
7301 		 */
7302 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7303 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7304 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
7305 		break;
7306 	case ENOTSUP:
7307 		/*
7308 		 * The PERSISTENT RESERVE IN command would not be recognized by
7309 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
7310 		 */
7311 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7312 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
7313 		un->un_reservation_type = SD_SCSI2_RESERVATION;
7314 		break;
7315 	default:
7316 		/*
7317 		 * default to SCSI-3 reservations
7318 		 */
7319 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7320 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
7321 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7322 		break;
7323 	}
7324 
7325 	/*
7326 	 * Set the pstat and error stat values here, so data obtained during the
7327 	 * previous attach-time routines is available.
7328 	 *
7329 	 * Note: This is a critical sequence that needs to be maintained:
7330 	 *	1) Instantiate the kstats before any routines using the iopath
7331 	 *	   (i.e. sd_send_scsi_cmd).
7332 	 *	2) Initialize the error stats (sd_set_errstats) and partition
7333 	 *	   stats (sd_set_pstats)here, following
7334 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
7335 	 *	   sd_cache_control().
7336 	 */
7337 
7338 	if (un->un_f_pkstats_enabled && geom_label_valid) {
7339 		sd_set_pstats(un);
7340 		SD_TRACE(SD_LOG_IO_PARTITION, un,
7341 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
7342 	}
7343 
7344 	sd_set_errstats(un);
7345 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7346 	    "sd_unit_attach: un:0x%p errstats set\n", un);
7347 
7348 
7349 	/*
7350 	 * After successfully attaching an instance, we record the information
7351 	 * of how many luns have been attached on the relative target and
7352 	 * controller for parallel SCSI. This information is used when sd tries
7353 	 * to set the tagged queuing capability in HBA.
7354 	 */
7355 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
7356 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
7357 	}
7358 
7359 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7360 	    "sd_unit_attach: un:0x%p exit success\n", un);
7361 
7362 	return (DDI_SUCCESS);
7363 
7364 	/*
7365 	 * An error occurred during the attach; clean up & return failure.
7366 	 */
7367 
7368 devid_failed:
7369 
7370 setup_pm_failed:
7371 	ddi_remove_minor_node(devi, NULL);
7372 
7373 cmlb_attach_failed:
7374 	/*
7375 	 * Cleanup from the scsi_ifsetcap() calls (437868)
7376 	 */
7377 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
7378 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
7379 
7380 	/*
7381 	 * Refer to the comments of setting tagged-qing in the beginning of
7382 	 * sd_unit_attach. We can only disable tagged queuing when there is
7383 	 * no lun attached on the target.
7384 	 */
7385 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7386 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
7387 	}
7388 
7389 	if (un->un_f_is_fibre == FALSE) {
7390 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
7391 	}
7392 
7393 spinup_failed:
7394 
7395 	mutex_enter(SD_MUTEX(un));
7396 
7397 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
7398 	if (un->un_direct_priority_timeid != NULL) {
7399 		timeout_id_t temp_id = un->un_direct_priority_timeid;
7400 		un->un_direct_priority_timeid = NULL;
7401 		mutex_exit(SD_MUTEX(un));
7402 		(void) untimeout(temp_id);
7403 		mutex_enter(SD_MUTEX(un));
7404 	}
7405 
7406 	/* Cancel any pending start/stop timeouts */
7407 	if (un->un_startstop_timeid != NULL) {
7408 		timeout_id_t temp_id = un->un_startstop_timeid;
7409 		un->un_startstop_timeid = NULL;
7410 		mutex_exit(SD_MUTEX(un));
7411 		(void) untimeout(temp_id);
7412 		mutex_enter(SD_MUTEX(un));
7413 	}
7414 
7415 	/* Cancel any pending reset-throttle timeouts */
7416 	if (un->un_reset_throttle_timeid != NULL) {
7417 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
7418 		un->un_reset_throttle_timeid = NULL;
7419 		mutex_exit(SD_MUTEX(un));
7420 		(void) untimeout(temp_id);
7421 		mutex_enter(SD_MUTEX(un));
7422 	}
7423 
7424 	/* Cancel any pending retry timeouts */
7425 	if (un->un_retry_timeid != NULL) {
7426 		timeout_id_t temp_id = un->un_retry_timeid;
7427 		un->un_retry_timeid = NULL;
7428 		mutex_exit(SD_MUTEX(un));
7429 		(void) untimeout(temp_id);
7430 		mutex_enter(SD_MUTEX(un));
7431 	}
7432 
7433 	/* Cancel any pending delayed cv broadcast timeouts */
7434 	if (un->un_dcvb_timeid != NULL) {
7435 		timeout_id_t temp_id = un->un_dcvb_timeid;
7436 		un->un_dcvb_timeid = NULL;
7437 		mutex_exit(SD_MUTEX(un));
7438 		(void) untimeout(temp_id);
7439 		mutex_enter(SD_MUTEX(un));
7440 	}
7441 
7442 	mutex_exit(SD_MUTEX(un));
7443 
7444 	/* There should not be any in-progress I/O so ASSERT this check */
7445 	ASSERT(un->un_ncmds_in_transport == 0);
7446 	ASSERT(un->un_ncmds_in_driver == 0);
7447 
7448 	/* Do not free the softstate if the callback routine is active */
7449 	sd_sync_with_callback(un);
7450 
7451 	/*
7452 	 * Partition stats apparently are not used with removables. These would
7453 	 * not have been created during attach, so no need to clean them up...
7454 	 */
7455 	if (un->un_stats != NULL) {
7456 		kstat_delete(un->un_stats);
7457 		un->un_stats = NULL;
7458 	}
7459 	if (un->un_errstats != NULL) {
7460 		kstat_delete(un->un_errstats);
7461 		un->un_errstats = NULL;
7462 	}
7463 
7464 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
7465 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
7466 
7467 	ddi_prop_remove_all(devi);
7468 	sema_destroy(&un->un_semoclose);
7469 	cv_destroy(&un->un_state_cv);
7470 
7471 getrbuf_failed:
7472 
7473 	sd_free_rqs(un);
7474 
7475 alloc_rqs_failed:
7476 
7477 	devp->sd_private = NULL;
7478 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
7479 
7480 get_softstate_failed:
7481 	/*
7482 	 * Note: the man pages are unclear as to whether or not doing a
7483 	 * ddi_soft_state_free(sd_state, instance) is the right way to
7484 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
7485 	 * ddi_get_soft_state() fails.  The implication seems to be
7486 	 * that the get_soft_state cannot fail if the zalloc succeeds.
7487 	 */
7488 	ddi_soft_state_free(sd_state, instance);
7489 
7490 probe_failed:
7491 	scsi_unprobe(devp);
7492 #ifdef SDDEBUG
7493 	if ((sd_component_mask & SD_LOG_ATTACH_DETACH) &&
7494 	    (sd_level_mask & SD_LOGMASK_TRACE)) {
7495 		cmn_err(CE_CONT, "sd_unit_attach: un:0x%p exit failure\n",
7496 		    (void *)un);
7497 	}
7498 #endif
7499 	return (DDI_FAILURE);
7500 }
7501 
7502 
7503 /*
7504  *    Function: sd_unit_detach
7505  *
7506  * Description: Performs DDI_DETACH processing for sddetach().
7507  *
7508  * Return Code: DDI_SUCCESS
7509  *		DDI_FAILURE
7510  *
7511  *     Context: Kernel thread context
7512  */
7513 
7514 static int
7515 sd_unit_detach(dev_info_t *devi)
7516 {
7517 	struct scsi_device	*devp;
7518 	struct sd_lun		*un;
7519 	int			i;
7520 	int			tgt;
7521 	dev_t			dev;
7522 	dev_info_t		*pdip = ddi_get_parent(devi);
7523 	int			instance = ddi_get_instance(devi);
7524 
7525 	mutex_enter(&sd_detach_mutex);
7526 
7527 	/*
7528 	 * Fail the detach for any of the following:
7529 	 *  - Unable to get the sd_lun struct for the instance
7530 	 *  - A layered driver has an outstanding open on the instance
7531 	 *  - Another thread is already detaching this instance
7532 	 *  - Another thread is currently performing an open
7533 	 */
7534 	devp = ddi_get_driver_private(devi);
7535 	if ((devp == NULL) ||
7536 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
7537 	    (un->un_ncmds_in_driver != 0) || (un->un_layer_count != 0) ||
7538 	    (un->un_detach_count != 0) || (un->un_opens_in_progress != 0)) {
7539 		mutex_exit(&sd_detach_mutex);
7540 		return (DDI_FAILURE);
7541 	}
7542 
7543 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
7544 
7545 	/*
7546 	 * Mark this instance as currently in a detach, to inhibit any
7547 	 * opens from a layered driver.
7548 	 */
7549 	un->un_detach_count++;
7550 	mutex_exit(&sd_detach_mutex);
7551 
7552 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7553 	    SCSI_ADDR_PROP_TARGET, -1);
7554 
7555 	dev = sd_make_device(SD_DEVINFO(un));
7556 
7557 #ifndef lint
7558 	_NOTE(COMPETING_THREADS_NOW);
7559 #endif
7560 
7561 	mutex_enter(SD_MUTEX(un));
7562 
7563 	/*
7564 	 * Fail the detach if there are any outstanding layered
7565 	 * opens on this device.
7566 	 */
7567 	for (i = 0; i < NDKMAP; i++) {
7568 		if (un->un_ocmap.lyropen[i] != 0) {
7569 			goto err_notclosed;
7570 		}
7571 	}
7572 
7573 	/*
7574 	 * Verify there are NO outstanding commands issued to this device.
7575 	 * ie, un_ncmds_in_transport == 0.
7576 	 * It's possible to have outstanding commands through the physio
7577 	 * code path, even though everything's closed.
7578 	 */
7579 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
7580 	    (un->un_direct_priority_timeid != NULL) ||
7581 	    (un->un_state == SD_STATE_RWAIT)) {
7582 		mutex_exit(SD_MUTEX(un));
7583 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7584 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
7585 		goto err_stillbusy;
7586 	}
7587 
7588 	/*
7589 	 * If we have the device reserved, release the reservation.
7590 	 */
7591 	if ((un->un_resvd_status & SD_RESERVE) &&
7592 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
7593 		mutex_exit(SD_MUTEX(un));
7594 		/*
7595 		 * Note: sd_reserve_release sends a command to the device
7596 		 * via the sd_ioctlcmd() path, and can sleep.
7597 		 */
7598 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
7599 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7600 			    "sd_dr_detach: Cannot release reservation \n");
7601 		}
7602 	} else {
7603 		mutex_exit(SD_MUTEX(un));
7604 	}
7605 
7606 	/*
7607 	 * Untimeout any reserve recover, throttle reset, restart unit
7608 	 * and delayed broadcast timeout threads. Protect the timeout pointer
7609 	 * from getting nulled by their callback functions.
7610 	 */
7611 	mutex_enter(SD_MUTEX(un));
7612 	if (un->un_resvd_timeid != NULL) {
7613 		timeout_id_t temp_id = un->un_resvd_timeid;
7614 		un->un_resvd_timeid = NULL;
7615 		mutex_exit(SD_MUTEX(un));
7616 		(void) untimeout(temp_id);
7617 		mutex_enter(SD_MUTEX(un));
7618 	}
7619 
7620 	if (un->un_reset_throttle_timeid != NULL) {
7621 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
7622 		un->un_reset_throttle_timeid = NULL;
7623 		mutex_exit(SD_MUTEX(un));
7624 		(void) untimeout(temp_id);
7625 		mutex_enter(SD_MUTEX(un));
7626 	}
7627 
7628 	if (un->un_startstop_timeid != NULL) {
7629 		timeout_id_t temp_id = un->un_startstop_timeid;
7630 		un->un_startstop_timeid = NULL;
7631 		mutex_exit(SD_MUTEX(un));
7632 		(void) untimeout(temp_id);
7633 		mutex_enter(SD_MUTEX(un));
7634 	}
7635 
7636 	if (un->un_dcvb_timeid != NULL) {
7637 		timeout_id_t temp_id = un->un_dcvb_timeid;
7638 		un->un_dcvb_timeid = NULL;
7639 		mutex_exit(SD_MUTEX(un));
7640 		(void) untimeout(temp_id);
7641 	} else {
7642 		mutex_exit(SD_MUTEX(un));
7643 	}
7644 
7645 	/* Remove any pending reservation reclaim requests for this device */
7646 	sd_rmv_resv_reclaim_req(dev);
7647 
7648 	mutex_enter(SD_MUTEX(un));
7649 
7650 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
7651 	if (un->un_direct_priority_timeid != NULL) {
7652 		timeout_id_t temp_id = un->un_direct_priority_timeid;
7653 		un->un_direct_priority_timeid = NULL;
7654 		mutex_exit(SD_MUTEX(un));
7655 		(void) untimeout(temp_id);
7656 		mutex_enter(SD_MUTEX(un));
7657 	}
7658 
7659 	/* Cancel any active multi-host disk watch thread requests */
7660 	if (un->un_mhd_token != NULL) {
7661 		mutex_exit(SD_MUTEX(un));
7662 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
7663 		if (scsi_watch_request_terminate(un->un_mhd_token,
7664 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
7665 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7666 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
7667 			/*
7668 			 * Note: We are returning here after having removed
7669 			 * some driver timeouts above. This is consistent with
7670 			 * the legacy implementation but perhaps the watch
7671 			 * terminate call should be made with the wait flag set.
7672 			 */
7673 			goto err_stillbusy;
7674 		}
7675 		mutex_enter(SD_MUTEX(un));
7676 		un->un_mhd_token = NULL;
7677 	}
7678 
7679 	if (un->un_swr_token != NULL) {
7680 		mutex_exit(SD_MUTEX(un));
7681 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
7682 		if (scsi_watch_request_terminate(un->un_swr_token,
7683 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
7684 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7685 			    "sd_dr_detach: Cannot cancel swr watch request\n");
7686 			/*
7687 			 * Note: We are returning here after having removed
7688 			 * some driver timeouts above. This is consistent with
7689 			 * the legacy implementation but perhaps the watch
7690 			 * terminate call should be made with the wait flag set.
7691 			 */
7692 			goto err_stillbusy;
7693 		}
7694 		mutex_enter(SD_MUTEX(un));
7695 		un->un_swr_token = NULL;
7696 	}
7697 
7698 	mutex_exit(SD_MUTEX(un));
7699 
7700 	/*
7701 	 * Clear any scsi_reset_notifies. We clear the reset notifies
7702 	 * if we have not registered one.
7703 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
7704 	 */
7705 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
7706 	    sd_mhd_reset_notify_cb, (caddr_t)un);
7707 
7708 	/*
7709 	 * protect the timeout pointers from getting nulled by
7710 	 * their callback functions during the cancellation process.
7711 	 * In such a scenario untimeout can be invoked with a null value.
7712 	 */
7713 	_NOTE(NO_COMPETING_THREADS_NOW);
7714 
7715 	mutex_enter(&un->un_pm_mutex);
7716 	if (un->un_pm_idle_timeid != NULL) {
7717 		timeout_id_t temp_id = un->un_pm_idle_timeid;
7718 		un->un_pm_idle_timeid = NULL;
7719 		mutex_exit(&un->un_pm_mutex);
7720 
7721 		/*
7722 		 * Timeout is active; cancel it.
7723 		 * Note that it'll never be active on a device
7724 		 * that does not support PM therefore we don't
7725 		 * have to check before calling pm_idle_component.
7726 		 */
7727 		(void) untimeout(temp_id);
7728 		(void) pm_idle_component(SD_DEVINFO(un), 0);
7729 		mutex_enter(&un->un_pm_mutex);
7730 	}
7731 
7732 	/*
7733 	 * Check whether there is already a timeout scheduled for power
7734 	 * management. If yes then don't lower the power here, that's.
7735 	 * the timeout handler's job.
7736 	 */
7737 	if (un->un_pm_timeid != NULL) {
7738 		timeout_id_t temp_id = un->un_pm_timeid;
7739 		un->un_pm_timeid = NULL;
7740 		mutex_exit(&un->un_pm_mutex);
7741 		/*
7742 		 * Timeout is active; cancel it.
7743 		 * Note that it'll never be active on a device
7744 		 * that does not support PM therefore we don't
7745 		 * have to check before calling pm_idle_component.
7746 		 */
7747 		(void) untimeout(temp_id);
7748 		(void) pm_idle_component(SD_DEVINFO(un), 0);
7749 
7750 	} else {
7751 		mutex_exit(&un->un_pm_mutex);
7752 		if ((un->un_f_pm_is_enabled == TRUE) &&
7753 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_SPINDLE_OFF) !=
7754 		    DDI_SUCCESS)) {
7755 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7756 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
7757 			/*
7758 			 * Fix for bug: 4297749, item # 13
7759 			 * The above test now includes a check to see if PM is
7760 			 * supported by this device before call
7761 			 * pm_lower_power().
7762 			 * Note, the following is not dead code. The call to
7763 			 * pm_lower_power above will generate a call back into
7764 			 * our sdpower routine which might result in a timeout
7765 			 * handler getting activated. Therefore the following
7766 			 * code is valid and necessary.
7767 			 */
7768 			mutex_enter(&un->un_pm_mutex);
7769 			if (un->un_pm_timeid != NULL) {
7770 				timeout_id_t temp_id = un->un_pm_timeid;
7771 				un->un_pm_timeid = NULL;
7772 				mutex_exit(&un->un_pm_mutex);
7773 				(void) untimeout(temp_id);
7774 				(void) pm_idle_component(SD_DEVINFO(un), 0);
7775 			} else {
7776 				mutex_exit(&un->un_pm_mutex);
7777 			}
7778 		}
7779 	}
7780 
7781 	/*
7782 	 * Cleanup from the scsi_ifsetcap() calls (437868)
7783 	 * Relocated here from above to be after the call to
7784 	 * pm_lower_power, which was getting errors.
7785 	 */
7786 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
7787 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
7788 
7789 	/*
7790 	 * Currently, tagged queuing is supported per target based by HBA.
7791 	 * Setting this per lun instance actually sets the capability of this
7792 	 * target in HBA, which affects those luns already attached on the
7793 	 * same target. So during detach, we can only disable this capability
7794 	 * only when this is the only lun left on this target. By doing
7795 	 * this, we assume a target has the same tagged queuing capability
7796 	 * for every lun. The condition can be removed when HBA is changed to
7797 	 * support per lun based tagged queuing capability.
7798 	 */
7799 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
7800 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
7801 	}
7802 
7803 	if (un->un_f_is_fibre == FALSE) {
7804 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
7805 	}
7806 
7807 	/*
7808 	 * Remove any event callbacks, fibre only
7809 	 */
7810 	if (un->un_f_is_fibre == TRUE) {
7811 		if ((un->un_insert_event != NULL) &&
7812 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
7813 		    DDI_SUCCESS)) {
7814 			/*
7815 			 * Note: We are returning here after having done
7816 			 * substantial cleanup above. This is consistent
7817 			 * with the legacy implementation but this may not
7818 			 * be the right thing to do.
7819 			 */
7820 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7821 			    "sd_dr_detach: Cannot cancel insert event\n");
7822 			goto err_remove_event;
7823 		}
7824 		un->un_insert_event = NULL;
7825 
7826 		if ((un->un_remove_event != NULL) &&
7827 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
7828 		    DDI_SUCCESS)) {
7829 			/*
7830 			 * Note: We are returning here after having done
7831 			 * substantial cleanup above. This is consistent
7832 			 * with the legacy implementation but this may not
7833 			 * be the right thing to do.
7834 			 */
7835 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7836 			    "sd_dr_detach: Cannot cancel remove event\n");
7837 			goto err_remove_event;
7838 		}
7839 		un->un_remove_event = NULL;
7840 	}
7841 
7842 	/* Do not free the softstate if the callback routine is active */
7843 	sd_sync_with_callback(un);
7844 
7845 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
7846 	cmlb_free_handle(&un->un_cmlbhandle);
7847 
7848 	/*
7849 	 * Hold the detach mutex here, to make sure that no other threads ever
7850 	 * can access a (partially) freed soft state structure.
7851 	 */
7852 	mutex_enter(&sd_detach_mutex);
7853 
7854 	/*
7855 	 * Clean up the soft state struct.
7856 	 * Cleanup is done in reverse order of allocs/inits.
7857 	 * At this point there should be no competing threads anymore.
7858 	 */
7859 
7860 	/* Unregister and free device id. */
7861 	ddi_devid_unregister(devi);
7862 	if (un->un_devid) {
7863 		ddi_devid_free(un->un_devid);
7864 		un->un_devid = NULL;
7865 	}
7866 
7867 	/*
7868 	 * Destroy wmap cache if it exists.
7869 	 */
7870 	if (un->un_wm_cache != NULL) {
7871 		kmem_cache_destroy(un->un_wm_cache);
7872 		un->un_wm_cache = NULL;
7873 	}
7874 
7875 	/*
7876 	 * kstat cleanup is done in detach for all device types (4363169).
7877 	 * We do not want to fail detach if the device kstats are not deleted
7878 	 * since there is a confusion about the devo_refcnt for the device.
7879 	 * We just delete the kstats and let detach complete successfully.
7880 	 */
7881 	if (un->un_stats != NULL) {
7882 		kstat_delete(un->un_stats);
7883 		un->un_stats = NULL;
7884 	}
7885 	if (un->un_errstats != NULL) {
7886 		kstat_delete(un->un_errstats);
7887 		un->un_errstats = NULL;
7888 	}
7889 
7890 	/* Remove partition stats */
7891 	if (un->un_f_pkstats_enabled) {
7892 		for (i = 0; i < NSDMAP; i++) {
7893 			if (un->un_pstats[i] != NULL) {
7894 				kstat_delete(un->un_pstats[i]);
7895 				un->un_pstats[i] = NULL;
7896 			}
7897 		}
7898 	}
7899 
7900 	/* Remove xbuf registration */
7901 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
7902 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
7903 
7904 	/* Remove driver properties */
7905 	ddi_prop_remove_all(devi);
7906 
7907 	mutex_destroy(&un->un_pm_mutex);
7908 	cv_destroy(&un->un_pm_busy_cv);
7909 
7910 	cv_destroy(&un->un_wcc_cv);
7911 
7912 	/* Open/close semaphore */
7913 	sema_destroy(&un->un_semoclose);
7914 
7915 	/* Removable media condvar. */
7916 	cv_destroy(&un->un_state_cv);
7917 
7918 	/* Suspend/resume condvar. */
7919 	cv_destroy(&un->un_suspend_cv);
7920 	cv_destroy(&un->un_disk_busy_cv);
7921 
7922 	sd_free_rqs(un);
7923 
7924 	/* Free up soft state */
7925 	devp->sd_private = NULL;
7926 
7927 	bzero(un, sizeof (struct sd_lun));
7928 	ddi_soft_state_free(sd_state, instance);
7929 
7930 	mutex_exit(&sd_detach_mutex);
7931 
7932 	/* This frees up the INQUIRY data associated with the device. */
7933 	scsi_unprobe(devp);
7934 
7935 	/*
7936 	 * After successfully detaching an instance, we update the information
7937 	 * of how many luns have been attached in the relative target and
7938 	 * controller for parallel SCSI. This information is used when sd tries
7939 	 * to set the tagged queuing capability in HBA.
7940 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
7941 	 * check if the device is parallel SCSI. However, we don't need to
7942 	 * check here because we've already checked during attach. No device
7943 	 * that is not parallel SCSI is in the chain.
7944 	 */
7945 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
7946 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
7947 	}
7948 
7949 	return (DDI_SUCCESS);
7950 
7951 err_notclosed:
7952 	mutex_exit(SD_MUTEX(un));
7953 
7954 err_stillbusy:
7955 	_NOTE(NO_COMPETING_THREADS_NOW);
7956 
7957 err_remove_event:
7958 	mutex_enter(&sd_detach_mutex);
7959 	un->un_detach_count--;
7960 	mutex_exit(&sd_detach_mutex);
7961 
7962 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
7963 	return (DDI_FAILURE);
7964 }
7965 
7966 
7967 /*
7968  *    Function: sd_create_errstats
7969  *
7970  * Description: This routine instantiates the device error stats.
7971  *
7972  *		Note: During attach the stats are instantiated first so they are
7973  *		available for attach-time routines that utilize the driver
7974  *		iopath to send commands to the device. The stats are initialized
7975  *		separately so data obtained during some attach-time routines is
7976  *		available. (4362483)
7977  *
7978  *   Arguments: un - driver soft state (unit) structure
7979  *		instance - driver instance
7980  *
7981  *     Context: Kernel thread context
7982  */
7983 
7984 static void
7985 sd_create_errstats(struct sd_lun *un, int instance)
7986 {
7987 	struct	sd_errstats	*stp;
7988 	char	kstatmodule_err[KSTAT_STRLEN];
7989 	char	kstatname[KSTAT_STRLEN];
7990 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
7991 
7992 	ASSERT(un != NULL);
7993 
7994 	if (un->un_errstats != NULL) {
7995 		return;
7996 	}
7997 
7998 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
7999 	    "%serr", sd_label);
8000 	(void) snprintf(kstatname, sizeof (kstatname),
8001 	    "%s%d,err", sd_label, instance);
8002 
8003 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
8004 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
8005 
8006 	if (un->un_errstats == NULL) {
8007 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8008 		    "sd_create_errstats: Failed kstat_create\n");
8009 		return;
8010 	}
8011 
8012 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8013 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
8014 	    KSTAT_DATA_UINT32);
8015 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
8016 	    KSTAT_DATA_UINT32);
8017 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
8018 	    KSTAT_DATA_UINT32);
8019 	kstat_named_init(&stp->sd_vid,		"Vendor",
8020 	    KSTAT_DATA_CHAR);
8021 	kstat_named_init(&stp->sd_pid,		"Product",
8022 	    KSTAT_DATA_CHAR);
8023 	kstat_named_init(&stp->sd_revision,	"Revision",
8024 	    KSTAT_DATA_CHAR);
8025 	kstat_named_init(&stp->sd_serial,	"Serial No",
8026 	    KSTAT_DATA_CHAR);
8027 	kstat_named_init(&stp->sd_capacity,	"Size",
8028 	    KSTAT_DATA_ULONGLONG);
8029 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
8030 	    KSTAT_DATA_UINT32);
8031 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
8032 	    KSTAT_DATA_UINT32);
8033 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
8034 	    KSTAT_DATA_UINT32);
8035 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
8036 	    KSTAT_DATA_UINT32);
8037 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
8038 	    KSTAT_DATA_UINT32);
8039 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
8040 	    KSTAT_DATA_UINT32);
8041 
8042 	un->un_errstats->ks_private = un;
8043 	un->un_errstats->ks_update  = nulldev;
8044 
8045 	kstat_install(un->un_errstats);
8046 }
8047 
8048 
8049 /*
8050  *    Function: sd_set_errstats
8051  *
8052  * Description: This routine sets the value of the vendor id, product id,
8053  *		revision, serial number, and capacity device error stats.
8054  *
8055  *		Note: During attach the stats are instantiated first so they are
8056  *		available for attach-time routines that utilize the driver
8057  *		iopath to send commands to the device. The stats are initialized
8058  *		separately so data obtained during some attach-time routines is
8059  *		available. (4362483)
8060  *
8061  *   Arguments: un - driver soft state (unit) structure
8062  *
8063  *     Context: Kernel thread context
8064  */
8065 
8066 static void
8067 sd_set_errstats(struct sd_lun *un)
8068 {
8069 	struct	sd_errstats	*stp;
8070 
8071 	ASSERT(un != NULL);
8072 	ASSERT(un->un_errstats != NULL);
8073 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8074 	ASSERT(stp != NULL);
8075 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
8076 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
8077 	(void) strncpy(stp->sd_revision.value.c,
8078 	    un->un_sd->sd_inq->inq_revision, 4);
8079 
8080 	/*
8081 	 * All the errstats are persistent across detach/attach,
8082 	 * so reset all the errstats here in case of the hot
8083 	 * replacement of disk drives, except for not changed
8084 	 * Sun qualified drives.
8085 	 */
8086 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
8087 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8088 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
8089 		stp->sd_softerrs.value.ui32 = 0;
8090 		stp->sd_harderrs.value.ui32 = 0;
8091 		stp->sd_transerrs.value.ui32 = 0;
8092 		stp->sd_rq_media_err.value.ui32 = 0;
8093 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
8094 		stp->sd_rq_nodev_err.value.ui32 = 0;
8095 		stp->sd_rq_recov_err.value.ui32 = 0;
8096 		stp->sd_rq_illrq_err.value.ui32 = 0;
8097 		stp->sd_rq_pfa_err.value.ui32 = 0;
8098 	}
8099 
8100 	/*
8101 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
8102 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
8103 	 * (4376302))
8104 	 */
8105 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
8106 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8107 		    sizeof (SD_INQUIRY(un)->inq_serial));
8108 	}
8109 
8110 	if (un->un_f_blockcount_is_valid != TRUE) {
8111 		/*
8112 		 * Set capacity error stat to 0 for no media. This ensures
8113 		 * a valid capacity is displayed in response to 'iostat -E'
8114 		 * when no media is present in the device.
8115 		 */
8116 		stp->sd_capacity.value.ui64 = 0;
8117 	} else {
8118 		/*
8119 		 * Multiply un_blockcount by un->un_sys_blocksize to get
8120 		 * capacity.
8121 		 *
8122 		 * Note: for non-512 blocksize devices "un_blockcount" has been
8123 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
8124 		 * (un_tgt_blocksize / un->un_sys_blocksize).
8125 		 */
8126 		stp->sd_capacity.value.ui64 = (uint64_t)
8127 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
8128 	}
8129 }
8130 
8131 
8132 /*
8133  *    Function: sd_set_pstats
8134  *
8135  * Description: This routine instantiates and initializes the partition
8136  *              stats for each partition with more than zero blocks.
8137  *		(4363169)
8138  *
8139  *   Arguments: un - driver soft state (unit) structure
8140  *
8141  *     Context: Kernel thread context
8142  */
8143 
8144 static void
8145 sd_set_pstats(struct sd_lun *un)
8146 {
8147 	char	kstatname[KSTAT_STRLEN];
8148 	int	instance;
8149 	int	i;
8150 	diskaddr_t	nblks = 0;
8151 	char	*partname = NULL;
8152 
8153 	ASSERT(un != NULL);
8154 
8155 	instance = ddi_get_instance(SD_DEVINFO(un));
8156 
8157 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
8158 	for (i = 0; i < NSDMAP; i++) {
8159 
8160 		if (cmlb_partinfo(un->un_cmlbhandle, i,
8161 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
8162 			continue;
8163 		mutex_enter(SD_MUTEX(un));
8164 
8165 		if ((un->un_pstats[i] == NULL) &&
8166 		    (nblks != 0)) {
8167 
8168 			(void) snprintf(kstatname, sizeof (kstatname),
8169 			    "%s%d,%s", sd_label, instance,
8170 			    partname);
8171 
8172 			un->un_pstats[i] = kstat_create(sd_label,
8173 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
8174 			    1, KSTAT_FLAG_PERSISTENT);
8175 			if (un->un_pstats[i] != NULL) {
8176 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
8177 				kstat_install(un->un_pstats[i]);
8178 			}
8179 		}
8180 		mutex_exit(SD_MUTEX(un));
8181 	}
8182 }
8183 
8184 
8185 #if (defined(__fibre))
8186 /*
8187  *    Function: sd_init_event_callbacks
8188  *
8189  * Description: This routine initializes the insertion and removal event
8190  *		callbacks. (fibre only)
8191  *
8192  *   Arguments: un - driver soft state (unit) structure
8193  *
8194  *     Context: Kernel thread context
8195  */
8196 
8197 static void
8198 sd_init_event_callbacks(struct sd_lun *un)
8199 {
8200 	ASSERT(un != NULL);
8201 
8202 	if ((un->un_insert_event == NULL) &&
8203 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
8204 	    &un->un_insert_event) == DDI_SUCCESS)) {
8205 		/*
8206 		 * Add the callback for an insertion event
8207 		 */
8208 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8209 		    un->un_insert_event, sd_event_callback, (void *)un,
8210 		    &(un->un_insert_cb_id));
8211 	}
8212 
8213 	if ((un->un_remove_event == NULL) &&
8214 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
8215 	    &un->un_remove_event) == DDI_SUCCESS)) {
8216 		/*
8217 		 * Add the callback for a removal event
8218 		 */
8219 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8220 		    un->un_remove_event, sd_event_callback, (void *)un,
8221 		    &(un->un_remove_cb_id));
8222 	}
8223 }
8224 
8225 
8226 /*
8227  *    Function: sd_event_callback
8228  *
8229  * Description: This routine handles insert/remove events (photon). The
8230  *		state is changed to OFFLINE which can be used to supress
8231  *		error msgs. (fibre only)
8232  *
8233  *   Arguments: un - driver soft state (unit) structure
8234  *
8235  *     Context: Callout thread context
8236  */
8237 /* ARGSUSED */
8238 static void
8239 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
8240     void *bus_impldata)
8241 {
8242 	struct sd_lun *un = (struct sd_lun *)arg;
8243 
8244 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
8245 	if (event == un->un_insert_event) {
8246 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
8247 		mutex_enter(SD_MUTEX(un));
8248 		if (un->un_state == SD_STATE_OFFLINE) {
8249 			if (un->un_last_state != SD_STATE_SUSPENDED) {
8250 				un->un_state = un->un_last_state;
8251 			} else {
8252 				/*
8253 				 * We have gone through SUSPEND/RESUME while
8254 				 * we were offline. Restore the last state
8255 				 */
8256 				un->un_state = un->un_save_state;
8257 			}
8258 		}
8259 		mutex_exit(SD_MUTEX(un));
8260 
8261 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
8262 	} else if (event == un->un_remove_event) {
8263 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
8264 		mutex_enter(SD_MUTEX(un));
8265 		/*
8266 		 * We need to handle an event callback that occurs during
8267 		 * the suspend operation, since we don't prevent it.
8268 		 */
8269 		if (un->un_state != SD_STATE_OFFLINE) {
8270 			if (un->un_state != SD_STATE_SUSPENDED) {
8271 				New_state(un, SD_STATE_OFFLINE);
8272 			} else {
8273 				un->un_last_state = SD_STATE_OFFLINE;
8274 			}
8275 		}
8276 		mutex_exit(SD_MUTEX(un));
8277 	} else {
8278 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
8279 		    "!Unknown event\n");
8280 	}
8281 
8282 }
8283 #endif
8284 
8285 /*
8286  *    Function: sd_cache_control()
8287  *
8288  * Description: This routine is the driver entry point for setting
8289  *		read and write caching by modifying the WCE (write cache
8290  *		enable) and RCD (read cache disable) bits of mode
8291  *		page 8 (MODEPAGE_CACHING).
8292  *
8293  *   Arguments: un - driver soft state (unit) structure
8294  *		rcd_flag - flag for controlling the read cache
8295  *		wce_flag - flag for controlling the write cache
8296  *
8297  * Return Code: EIO
8298  *		code returned by sd_send_scsi_MODE_SENSE and
8299  *		sd_send_scsi_MODE_SELECT
8300  *
8301  *     Context: Kernel Thread
8302  */
8303 
8304 static int
8305 sd_cache_control(struct sd_lun *un, int rcd_flag, int wce_flag)
8306 {
8307 	struct mode_caching	*mode_caching_page;
8308 	uchar_t			*header;
8309 	size_t			buflen;
8310 	int			hdrlen;
8311 	int			bd_len;
8312 	int			rval = 0;
8313 	struct mode_header_grp2	*mhp;
8314 
8315 	ASSERT(un != NULL);
8316 
8317 	/*
8318 	 * Do a test unit ready, otherwise a mode sense may not work if this
8319 	 * is the first command sent to the device after boot.
8320 	 */
8321 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
8322 
8323 	if (un->un_f_cfg_is_atapi == TRUE) {
8324 		hdrlen = MODE_HEADER_LENGTH_GRP2;
8325 	} else {
8326 		hdrlen = MODE_HEADER_LENGTH;
8327 	}
8328 
8329 	/*
8330 	 * Allocate memory for the retrieved mode page and its headers.  Set
8331 	 * a pointer to the page itself.  Use mode_cache_scsi3 to insure
8332 	 * we get all of the mode sense data otherwise, the mode select
8333 	 * will fail.  mode_cache_scsi3 is a superset of mode_caching.
8334 	 */
8335 	buflen = hdrlen + MODE_BLK_DESC_LENGTH +
8336 	    sizeof (struct mode_cache_scsi3);
8337 
8338 	header = kmem_zalloc(buflen, KM_SLEEP);
8339 
8340 	/* Get the information from the device. */
8341 	if (un->un_f_cfg_is_atapi == TRUE) {
8342 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
8343 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8344 	} else {
8345 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
8346 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8347 	}
8348 	if (rval != 0) {
8349 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
8350 		    "sd_cache_control: Mode Sense Failed\n");
8351 		kmem_free(header, buflen);
8352 		return (rval);
8353 	}
8354 
8355 	/*
8356 	 * Determine size of Block Descriptors in order to locate
8357 	 * the mode page data. ATAPI devices return 0, SCSI devices
8358 	 * should return MODE_BLK_DESC_LENGTH.
8359 	 */
8360 	if (un->un_f_cfg_is_atapi == TRUE) {
8361 		mhp	= (struct mode_header_grp2 *)header;
8362 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
8363 	} else {
8364 		bd_len  = ((struct mode_header *)header)->bdesc_length;
8365 	}
8366 
8367 	if (bd_len > MODE_BLK_DESC_LENGTH) {
8368 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
8369 		    "sd_cache_control: Mode Sense returned invalid "
8370 		    "block descriptor length\n");
8371 		kmem_free(header, buflen);
8372 		return (EIO);
8373 	}
8374 
8375 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
8376 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
8377 		SD_ERROR(SD_LOG_COMMON, un, "sd_cache_control: Mode Sense"
8378 		    " caching page code mismatch %d\n",
8379 		    mode_caching_page->mode_page.code);
8380 		kmem_free(header, buflen);
8381 		return (EIO);
8382 	}
8383 
8384 	/* Check the relevant bits on successful mode sense. */
8385 	if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
8386 	    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
8387 	    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
8388 	    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
8389 
8390 		size_t sbuflen;
8391 		uchar_t save_pg;
8392 
8393 		/*
8394 		 * Construct select buffer length based on the
8395 		 * length of the sense data returned.
8396 		 */
8397 		sbuflen =  hdrlen + MODE_BLK_DESC_LENGTH +
8398 		    sizeof (struct mode_page) +
8399 		    (int)mode_caching_page->mode_page.length;
8400 
8401 		/*
8402 		 * Set the caching bits as requested.
8403 		 */
8404 		if (rcd_flag == SD_CACHE_ENABLE)
8405 			mode_caching_page->rcd = 0;
8406 		else if (rcd_flag == SD_CACHE_DISABLE)
8407 			mode_caching_page->rcd = 1;
8408 
8409 		if (wce_flag == SD_CACHE_ENABLE)
8410 			mode_caching_page->wce = 1;
8411 		else if (wce_flag == SD_CACHE_DISABLE)
8412 			mode_caching_page->wce = 0;
8413 
8414 		/*
8415 		 * Save the page if the mode sense says the
8416 		 * drive supports it.
8417 		 */
8418 		save_pg = mode_caching_page->mode_page.ps ?
8419 		    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
8420 
8421 		/* Clear reserved bits before mode select. */
8422 		mode_caching_page->mode_page.ps = 0;
8423 
8424 		/*
8425 		 * Clear out mode header for mode select.
8426 		 * The rest of the retrieved page will be reused.
8427 		 */
8428 		bzero(header, hdrlen);
8429 
8430 		if (un->un_f_cfg_is_atapi == TRUE) {
8431 			mhp = (struct mode_header_grp2 *)header;
8432 			mhp->bdesc_length_hi = bd_len >> 8;
8433 			mhp->bdesc_length_lo = (uchar_t)bd_len & 0xff;
8434 		} else {
8435 			((struct mode_header *)header)->bdesc_length = bd_len;
8436 		}
8437 
8438 		/* Issue mode select to change the cache settings */
8439 		if (un->un_f_cfg_is_atapi == TRUE) {
8440 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, header,
8441 			    sbuflen, save_pg, SD_PATH_DIRECT);
8442 		} else {
8443 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
8444 			    sbuflen, save_pg, SD_PATH_DIRECT);
8445 		}
8446 	}
8447 
8448 	kmem_free(header, buflen);
8449 	return (rval);
8450 }
8451 
8452 
8453 /*
8454  *    Function: sd_get_write_cache_enabled()
8455  *
8456  * Description: This routine is the driver entry point for determining if
8457  *		write caching is enabled.  It examines the WCE (write cache
8458  *		enable) bits of mode page 8 (MODEPAGE_CACHING).
8459  *
8460  *   Arguments: un - driver soft state (unit) structure
8461  *		is_enabled - pointer to int where write cache enabled state
8462  *		is returned (non-zero -> write cache enabled)
8463  *
8464  *
8465  * Return Code: EIO
8466  *		code returned by sd_send_scsi_MODE_SENSE
8467  *
8468  *     Context: Kernel Thread
8469  *
8470  * NOTE: If ioctl is added to disable write cache, this sequence should
8471  * be followed so that no locking is required for accesses to
8472  * un->un_f_write_cache_enabled:
8473  * 	do mode select to clear wce
8474  * 	do synchronize cache to flush cache
8475  * 	set un->un_f_write_cache_enabled = FALSE
8476  *
8477  * Conversely, an ioctl to enable the write cache should be done
8478  * in this order:
8479  * 	set un->un_f_write_cache_enabled = TRUE
8480  * 	do mode select to set wce
8481  */
8482 
8483 static int
8484 sd_get_write_cache_enabled(struct sd_lun *un, int *is_enabled)
8485 {
8486 	struct mode_caching	*mode_caching_page;
8487 	uchar_t			*header;
8488 	size_t			buflen;
8489 	int			hdrlen;
8490 	int			bd_len;
8491 	int			rval = 0;
8492 
8493 	ASSERT(un != NULL);
8494 	ASSERT(is_enabled != NULL);
8495 
8496 	/* in case of error, flag as enabled */
8497 	*is_enabled = TRUE;
8498 
8499 	/*
8500 	 * Do a test unit ready, otherwise a mode sense may not work if this
8501 	 * is the first command sent to the device after boot.
8502 	 */
8503 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
8504 
8505 	if (un->un_f_cfg_is_atapi == TRUE) {
8506 		hdrlen = MODE_HEADER_LENGTH_GRP2;
8507 	} else {
8508 		hdrlen = MODE_HEADER_LENGTH;
8509 	}
8510 
8511 	/*
8512 	 * Allocate memory for the retrieved mode page and its headers.  Set
8513 	 * a pointer to the page itself.
8514 	 */
8515 	buflen = hdrlen + MODE_BLK_DESC_LENGTH + sizeof (struct mode_caching);
8516 	header = kmem_zalloc(buflen, KM_SLEEP);
8517 
8518 	/* Get the information from the device. */
8519 	if (un->un_f_cfg_is_atapi == TRUE) {
8520 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
8521 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8522 	} else {
8523 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
8524 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8525 	}
8526 	if (rval != 0) {
8527 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
8528 		    "sd_get_write_cache_enabled: Mode Sense Failed\n");
8529 		kmem_free(header, buflen);
8530 		return (rval);
8531 	}
8532 
8533 	/*
8534 	 * Determine size of Block Descriptors in order to locate
8535 	 * the mode page data. ATAPI devices return 0, SCSI devices
8536 	 * should return MODE_BLK_DESC_LENGTH.
8537 	 */
8538 	if (un->un_f_cfg_is_atapi == TRUE) {
8539 		struct mode_header_grp2	*mhp;
8540 		mhp	= (struct mode_header_grp2 *)header;
8541 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
8542 	} else {
8543 		bd_len  = ((struct mode_header *)header)->bdesc_length;
8544 	}
8545 
8546 	if (bd_len > MODE_BLK_DESC_LENGTH) {
8547 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
8548 		    "sd_get_write_cache_enabled: Mode Sense returned invalid "
8549 		    "block descriptor length\n");
8550 		kmem_free(header, buflen);
8551 		return (EIO);
8552 	}
8553 
8554 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
8555 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
8556 		SD_ERROR(SD_LOG_COMMON, un, "sd_cache_control: Mode Sense"
8557 		    " caching page code mismatch %d\n",
8558 		    mode_caching_page->mode_page.code);
8559 		kmem_free(header, buflen);
8560 		return (EIO);
8561 	}
8562 	*is_enabled = mode_caching_page->wce;
8563 
8564 	kmem_free(header, buflen);
8565 	return (0);
8566 }
8567 
8568 
8569 /*
8570  *    Function: sd_make_device
8571  *
8572  * Description: Utility routine to return the Solaris device number from
8573  *		the data in the device's dev_info structure.
8574  *
8575  * Return Code: The Solaris device number
8576  *
8577  *     Context: Any
8578  */
8579 
8580 static dev_t
8581 sd_make_device(dev_info_t *devi)
8582 {
8583 	return (makedevice(ddi_name_to_major(ddi_get_name(devi)),
8584 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
8585 }
8586 
8587 
8588 /*
8589  *    Function: sd_pm_entry
8590  *
8591  * Description: Called at the start of a new command to manage power
8592  *		and busy status of a device. This includes determining whether
8593  *		the current power state of the device is sufficient for
8594  *		performing the command or whether it must be changed.
8595  *		The PM framework is notified appropriately.
8596  *		Only with a return status of DDI_SUCCESS will the
8597  *		component be busy to the framework.
8598  *
8599  *		All callers of sd_pm_entry must check the return status
8600  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
8601  *		of DDI_FAILURE indicates the device failed to power up.
8602  *		In this case un_pm_count has been adjusted so the result
8603  *		on exit is still powered down, ie. count is less than 0.
8604  *		Calling sd_pm_exit with this count value hits an ASSERT.
8605  *
8606  * Return Code: DDI_SUCCESS or DDI_FAILURE
8607  *
8608  *     Context: Kernel thread context.
8609  */
8610 
8611 static int
8612 sd_pm_entry(struct sd_lun *un)
8613 {
8614 	int return_status = DDI_SUCCESS;
8615 
8616 	ASSERT(!mutex_owned(SD_MUTEX(un)));
8617 	ASSERT(!mutex_owned(&un->un_pm_mutex));
8618 
8619 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
8620 
8621 	if (un->un_f_pm_is_enabled == FALSE) {
8622 		SD_TRACE(SD_LOG_IO_PM, un,
8623 		    "sd_pm_entry: exiting, PM not enabled\n");
8624 		return (return_status);
8625 	}
8626 
8627 	/*
8628 	 * Just increment a counter if PM is enabled. On the transition from
8629 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
8630 	 * the count with each IO and mark the device as idle when the count
8631 	 * hits 0.
8632 	 *
8633 	 * If the count is less than 0 the device is powered down. If a powered
8634 	 * down device is successfully powered up then the count must be
8635 	 * incremented to reflect the power up. Note that it'll get incremented
8636 	 * a second time to become busy.
8637 	 *
8638 	 * Because the following has the potential to change the device state
8639 	 * and must release the un_pm_mutex to do so, only one thread can be
8640 	 * allowed through at a time.
8641 	 */
8642 
8643 	mutex_enter(&un->un_pm_mutex);
8644 	while (un->un_pm_busy == TRUE) {
8645 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
8646 	}
8647 	un->un_pm_busy = TRUE;
8648 
8649 	if (un->un_pm_count < 1) {
8650 
8651 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
8652 
8653 		/*
8654 		 * Indicate we are now busy so the framework won't attempt to
8655 		 * power down the device. This call will only fail if either
8656 		 * we passed a bad component number or the device has no
8657 		 * components. Neither of these should ever happen.
8658 		 */
8659 		mutex_exit(&un->un_pm_mutex);
8660 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
8661 		ASSERT(return_status == DDI_SUCCESS);
8662 
8663 		mutex_enter(&un->un_pm_mutex);
8664 
8665 		if (un->un_pm_count < 0) {
8666 			mutex_exit(&un->un_pm_mutex);
8667 
8668 			SD_TRACE(SD_LOG_IO_PM, un,
8669 			    "sd_pm_entry: power up component\n");
8670 
8671 			/*
8672 			 * pm_raise_power will cause sdpower to be called
8673 			 * which brings the device power level to the
8674 			 * desired state, ON in this case. If successful,
8675 			 * un_pm_count and un_power_level will be updated
8676 			 * appropriately.
8677 			 */
8678 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
8679 			    SD_SPINDLE_ON);
8680 
8681 			mutex_enter(&un->un_pm_mutex);
8682 
8683 			if (return_status != DDI_SUCCESS) {
8684 				/*
8685 				 * Power up failed.
8686 				 * Idle the device and adjust the count
8687 				 * so the result on exit is that we're
8688 				 * still powered down, ie. count is less than 0.
8689 				 */
8690 				SD_TRACE(SD_LOG_IO_PM, un,
8691 				    "sd_pm_entry: power up failed,"
8692 				    " idle the component\n");
8693 
8694 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8695 				un->un_pm_count--;
8696 			} else {
8697 				/*
8698 				 * Device is powered up, verify the
8699 				 * count is non-negative.
8700 				 * This is debug only.
8701 				 */
8702 				ASSERT(un->un_pm_count == 0);
8703 			}
8704 		}
8705 
8706 		if (return_status == DDI_SUCCESS) {
8707 			/*
8708 			 * For performance, now that the device has been tagged
8709 			 * as busy, and it's known to be powered up, update the
8710 			 * chain types to use jump tables that do not include
8711 			 * pm. This significantly lowers the overhead and
8712 			 * therefore improves performance.
8713 			 */
8714 
8715 			mutex_exit(&un->un_pm_mutex);
8716 			mutex_enter(SD_MUTEX(un));
8717 			SD_TRACE(SD_LOG_IO_PM, un,
8718 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
8719 			    un->un_uscsi_chain_type);
8720 
8721 			if (un->un_f_non_devbsize_supported) {
8722 				un->un_buf_chain_type =
8723 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
8724 			} else {
8725 				un->un_buf_chain_type =
8726 				    SD_CHAIN_INFO_DISK_NO_PM;
8727 			}
8728 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8729 
8730 			SD_TRACE(SD_LOG_IO_PM, un,
8731 			    "             changed  uscsi_chain_type to   %d\n",
8732 			    un->un_uscsi_chain_type);
8733 			mutex_exit(SD_MUTEX(un));
8734 			mutex_enter(&un->un_pm_mutex);
8735 
8736 			if (un->un_pm_idle_timeid == NULL) {
8737 				/* 300 ms. */
8738 				un->un_pm_idle_timeid =
8739 				    timeout(sd_pm_idletimeout_handler, un,
8740 				    (drv_usectohz((clock_t)300000)));
8741 				/*
8742 				 * Include an extra call to busy which keeps the
8743 				 * device busy with-respect-to the PM layer
8744 				 * until the timer fires, at which time it'll
8745 				 * get the extra idle call.
8746 				 */
8747 				(void) pm_busy_component(SD_DEVINFO(un), 0);
8748 			}
8749 		}
8750 	}
8751 	un->un_pm_busy = FALSE;
8752 	/* Next... */
8753 	cv_signal(&un->un_pm_busy_cv);
8754 
8755 	un->un_pm_count++;
8756 
8757 	SD_TRACE(SD_LOG_IO_PM, un,
8758 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
8759 
8760 	mutex_exit(&un->un_pm_mutex);
8761 
8762 	return (return_status);
8763 }
8764 
8765 
8766 /*
8767  *    Function: sd_pm_exit
8768  *
8769  * Description: Called at the completion of a command to manage busy
8770  *		status for the device. If the device becomes idle the
8771  *		PM framework is notified.
8772  *
8773  *     Context: Kernel thread context
8774  */
8775 
8776 static void
8777 sd_pm_exit(struct sd_lun *un)
8778 {
8779 	ASSERT(!mutex_owned(SD_MUTEX(un)));
8780 	ASSERT(!mutex_owned(&un->un_pm_mutex));
8781 
8782 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
8783 
8784 	/*
8785 	 * After attach the following flag is only read, so don't
8786 	 * take the penalty of acquiring a mutex for it.
8787 	 */
8788 	if (un->un_f_pm_is_enabled == TRUE) {
8789 
8790 		mutex_enter(&un->un_pm_mutex);
8791 		un->un_pm_count--;
8792 
8793 		SD_TRACE(SD_LOG_IO_PM, un,
8794 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
8795 
8796 		ASSERT(un->un_pm_count >= 0);
8797 		if (un->un_pm_count == 0) {
8798 			mutex_exit(&un->un_pm_mutex);
8799 
8800 			SD_TRACE(SD_LOG_IO_PM, un,
8801 			    "sd_pm_exit: idle component\n");
8802 
8803 			(void) pm_idle_component(SD_DEVINFO(un), 0);
8804 
8805 		} else {
8806 			mutex_exit(&un->un_pm_mutex);
8807 		}
8808 	}
8809 
8810 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
8811 }
8812 
8813 
8814 /*
8815  *    Function: sdopen
8816  *
8817  * Description: Driver's open(9e) entry point function.
8818  *
8819  *   Arguments: dev_i   - pointer to device number
8820  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
8821  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
8822  *		cred_p  - user credential pointer
8823  *
8824  * Return Code: EINVAL
8825  *		ENXIO
8826  *		EIO
8827  *		EROFS
8828  *		EBUSY
8829  *
8830  *     Context: Kernel thread context
8831  */
8832 /* ARGSUSED */
8833 static int
8834 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
8835 {
8836 	struct sd_lun	*un;
8837 	int		nodelay;
8838 	int		part;
8839 	uint64_t	partmask;
8840 	int		instance;
8841 	dev_t		dev;
8842 	int		rval = EIO;
8843 	diskaddr_t	nblks = 0;
8844 
8845 	/* Validate the open type */
8846 	if (otyp >= OTYPCNT) {
8847 		return (EINVAL);
8848 	}
8849 
8850 	dev = *dev_p;
8851 	instance = SDUNIT(dev);
8852 	mutex_enter(&sd_detach_mutex);
8853 
8854 	/*
8855 	 * Fail the open if there is no softstate for the instance, or
8856 	 * if another thread somewhere is trying to detach the instance.
8857 	 */
8858 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
8859 	    (un->un_detach_count != 0)) {
8860 		mutex_exit(&sd_detach_mutex);
8861 		/*
8862 		 * The probe cache only needs to be cleared when open (9e) fails
8863 		 * with ENXIO (4238046).
8864 		 */
8865 		/*
8866 		 * un-conditionally clearing probe cache is ok with
8867 		 * separate sd/ssd binaries
8868 		 * x86 platform can be an issue with both parallel
8869 		 * and fibre in 1 binary
8870 		 */
8871 		sd_scsi_clear_probe_cache();
8872 		return (ENXIO);
8873 	}
8874 
8875 	/*
8876 	 * The un_layer_count is to prevent another thread in specfs from
8877 	 * trying to detach the instance, which can happen when we are
8878 	 * called from a higher-layer driver instead of thru specfs.
8879 	 * This will not be needed when DDI provides a layered driver
8880 	 * interface that allows specfs to know that an instance is in
8881 	 * use by a layered driver & should not be detached.
8882 	 *
8883 	 * Note: the semantics for layered driver opens are exactly one
8884 	 * close for every open.
8885 	 */
8886 	if (otyp == OTYP_LYR) {
8887 		un->un_layer_count++;
8888 	}
8889 
8890 	/*
8891 	 * Keep a count of the current # of opens in progress. This is because
8892 	 * some layered drivers try to call us as a regular open. This can
8893 	 * cause problems that we cannot prevent, however by keeping this count
8894 	 * we can at least keep our open and detach routines from racing against
8895 	 * each other under such conditions.
8896 	 */
8897 	un->un_opens_in_progress++;
8898 	mutex_exit(&sd_detach_mutex);
8899 
8900 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
8901 	part	 = SDPART(dev);
8902 	partmask = 1 << part;
8903 
8904 	/*
8905 	 * We use a semaphore here in order to serialize
8906 	 * open and close requests on the device.
8907 	 */
8908 	sema_p(&un->un_semoclose);
8909 
8910 	mutex_enter(SD_MUTEX(un));
8911 
8912 	/*
8913 	 * All device accesses go thru sdstrategy() where we check
8914 	 * on suspend status but there could be a scsi_poll command,
8915 	 * which bypasses sdstrategy(), so we need to check pm
8916 	 * status.
8917 	 */
8918 
8919 	if (!nodelay) {
8920 		while ((un->un_state == SD_STATE_SUSPENDED) ||
8921 		    (un->un_state == SD_STATE_PM_CHANGING)) {
8922 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
8923 		}
8924 
8925 		mutex_exit(SD_MUTEX(un));
8926 		if (sd_pm_entry(un) != DDI_SUCCESS) {
8927 			rval = EIO;
8928 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
8929 			    "sdopen: sd_pm_entry failed\n");
8930 			goto open_failed_with_pm;
8931 		}
8932 		mutex_enter(SD_MUTEX(un));
8933 	}
8934 
8935 	/* check for previous exclusive open */
8936 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
8937 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
8938 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
8939 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
8940 
8941 	if (un->un_exclopen & (partmask)) {
8942 		goto excl_open_fail;
8943 	}
8944 
8945 	if (flag & FEXCL) {
8946 		int i;
8947 		if (un->un_ocmap.lyropen[part]) {
8948 			goto excl_open_fail;
8949 		}
8950 		for (i = 0; i < (OTYPCNT - 1); i++) {
8951 			if (un->un_ocmap.regopen[i] & (partmask)) {
8952 				goto excl_open_fail;
8953 			}
8954 		}
8955 	}
8956 
8957 	/*
8958 	 * Check the write permission if this is a removable media device,
8959 	 * NDELAY has not been set, and writable permission is requested.
8960 	 *
8961 	 * Note: If NDELAY was set and this is write-protected media the WRITE
8962 	 * attempt will fail with EIO as part of the I/O processing. This is a
8963 	 * more permissive implementation that allows the open to succeed and
8964 	 * WRITE attempts to fail when appropriate.
8965 	 */
8966 	if (un->un_f_chk_wp_open) {
8967 		if ((flag & FWRITE) && (!nodelay)) {
8968 			mutex_exit(SD_MUTEX(un));
8969 			/*
8970 			 * Defer the check for write permission on writable
8971 			 * DVD drive till sdstrategy and will not fail open even
8972 			 * if FWRITE is set as the device can be writable
8973 			 * depending upon the media and the media can change
8974 			 * after the call to open().
8975 			 */
8976 			if (un->un_f_dvdram_writable_device == FALSE) {
8977 				if (ISCD(un) || sr_check_wp(dev)) {
8978 				rval = EROFS;
8979 				mutex_enter(SD_MUTEX(un));
8980 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
8981 				    "write to cd or write protected media\n");
8982 				goto open_fail;
8983 				}
8984 			}
8985 			mutex_enter(SD_MUTEX(un));
8986 		}
8987 	}
8988 
8989 	/*
8990 	 * If opening in NDELAY/NONBLOCK mode, just return.
8991 	 * Check if disk is ready and has a valid geometry later.
8992 	 */
8993 	if (!nodelay) {
8994 		mutex_exit(SD_MUTEX(un));
8995 		rval = sd_ready_and_valid(un);
8996 		mutex_enter(SD_MUTEX(un));
8997 		/*
8998 		 * Fail if device is not ready or if the number of disk
8999 		 * blocks is zero or negative for non CD devices.
9000 		 */
9001 
9002 		nblks = 0;
9003 
9004 		if (rval == SD_READY_VALID && (!ISCD(un))) {
9005 			/* if cmlb_partinfo fails, nblks remains 0 */
9006 			mutex_exit(SD_MUTEX(un));
9007 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
9008 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
9009 			mutex_enter(SD_MUTEX(un));
9010 		}
9011 
9012 		if ((rval != SD_READY_VALID) ||
9013 		    (!ISCD(un) && nblks <= 0)) {
9014 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
9015 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9016 			    "device not ready or invalid disk block value\n");
9017 			goto open_fail;
9018 		}
9019 #if defined(__i386) || defined(__amd64)
9020 	} else {
9021 		uchar_t *cp;
9022 		/*
9023 		 * x86 requires special nodelay handling, so that p0 is
9024 		 * always defined and accessible.
9025 		 * Invalidate geometry only if device is not already open.
9026 		 */
9027 		cp = &un->un_ocmap.chkd[0];
9028 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9029 			if (*cp != (uchar_t)0) {
9030 				break;
9031 			}
9032 			cp++;
9033 		}
9034 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9035 			mutex_exit(SD_MUTEX(un));
9036 			cmlb_invalidate(un->un_cmlbhandle,
9037 			    (void *)SD_PATH_DIRECT);
9038 			mutex_enter(SD_MUTEX(un));
9039 		}
9040 
9041 #endif
9042 	}
9043 
9044 	if (otyp == OTYP_LYR) {
9045 		un->un_ocmap.lyropen[part]++;
9046 	} else {
9047 		un->un_ocmap.regopen[otyp] |= partmask;
9048 	}
9049 
9050 	/* Set up open and exclusive open flags */
9051 	if (flag & FEXCL) {
9052 		un->un_exclopen |= (partmask);
9053 	}
9054 
9055 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9056 	    "open of part %d type %d\n", part, otyp);
9057 
9058 	mutex_exit(SD_MUTEX(un));
9059 	if (!nodelay) {
9060 		sd_pm_exit(un);
9061 	}
9062 
9063 	sema_v(&un->un_semoclose);
9064 
9065 	mutex_enter(&sd_detach_mutex);
9066 	un->un_opens_in_progress--;
9067 	mutex_exit(&sd_detach_mutex);
9068 
9069 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
9070 	return (DDI_SUCCESS);
9071 
9072 excl_open_fail:
9073 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
9074 	rval = EBUSY;
9075 
9076 open_fail:
9077 	mutex_exit(SD_MUTEX(un));
9078 
9079 	/*
9080 	 * On a failed open we must exit the pm management.
9081 	 */
9082 	if (!nodelay) {
9083 		sd_pm_exit(un);
9084 	}
9085 open_failed_with_pm:
9086 	sema_v(&un->un_semoclose);
9087 
9088 	mutex_enter(&sd_detach_mutex);
9089 	un->un_opens_in_progress--;
9090 	if (otyp == OTYP_LYR) {
9091 		un->un_layer_count--;
9092 	}
9093 	mutex_exit(&sd_detach_mutex);
9094 
9095 	return (rval);
9096 }
9097 
9098 
9099 /*
9100  *    Function: sdclose
9101  *
9102  * Description: Driver's close(9e) entry point function.
9103  *
9104  *   Arguments: dev    - device number
9105  *		flag   - file status flag, informational only
9106  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9107  *		cred_p - user credential pointer
9108  *
9109  * Return Code: ENXIO
9110  *
9111  *     Context: Kernel thread context
9112  */
9113 /* ARGSUSED */
9114 static int
9115 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
9116 {
9117 	struct sd_lun	*un;
9118 	uchar_t		*cp;
9119 	int		part;
9120 	int		nodelay;
9121 	int		rval = 0;
9122 
9123 	/* Validate the open type */
9124 	if (otyp >= OTYPCNT) {
9125 		return (ENXIO);
9126 	}
9127 
9128 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9129 		return (ENXIO);
9130 	}
9131 
9132 	part = SDPART(dev);
9133 	nodelay = flag & (FNDELAY | FNONBLOCK);
9134 
9135 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
9136 	    "sdclose: close of part %d type %d\n", part, otyp);
9137 
9138 	/*
9139 	 * We use a semaphore here in order to serialize
9140 	 * open and close requests on the device.
9141 	 */
9142 	sema_p(&un->un_semoclose);
9143 
9144 	mutex_enter(SD_MUTEX(un));
9145 
9146 	/* Don't proceed if power is being changed. */
9147 	while (un->un_state == SD_STATE_PM_CHANGING) {
9148 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9149 	}
9150 
9151 	if (un->un_exclopen & (1 << part)) {
9152 		un->un_exclopen &= ~(1 << part);
9153 	}
9154 
9155 	/* Update the open partition map */
9156 	if (otyp == OTYP_LYR) {
9157 		un->un_ocmap.lyropen[part] -= 1;
9158 	} else {
9159 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
9160 	}
9161 
9162 	cp = &un->un_ocmap.chkd[0];
9163 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9164 		if (*cp != NULL) {
9165 			break;
9166 		}
9167 		cp++;
9168 	}
9169 
9170 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9171 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
9172 
9173 		/*
9174 		 * We avoid persistance upon the last close, and set
9175 		 * the throttle back to the maximum.
9176 		 */
9177 		un->un_throttle = un->un_saved_throttle;
9178 
9179 		if (un->un_state == SD_STATE_OFFLINE) {
9180 			if (un->un_f_is_fibre == FALSE) {
9181 				scsi_log(SD_DEVINFO(un), sd_label,
9182 				    CE_WARN, "offline\n");
9183 			}
9184 			mutex_exit(SD_MUTEX(un));
9185 			cmlb_invalidate(un->un_cmlbhandle,
9186 			    (void *)SD_PATH_DIRECT);
9187 			mutex_enter(SD_MUTEX(un));
9188 
9189 		} else {
9190 			/*
9191 			 * Flush any outstanding writes in NVRAM cache.
9192 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
9193 			 * cmd, it may not work for non-Pluto devices.
9194 			 * SYNCHRONIZE CACHE is not required for removables,
9195 			 * except DVD-RAM drives.
9196 			 *
9197 			 * Also note: because SYNCHRONIZE CACHE is currently
9198 			 * the only command issued here that requires the
9199 			 * drive be powered up, only do the power up before
9200 			 * sending the Sync Cache command. If additional
9201 			 * commands are added which require a powered up
9202 			 * drive, the following sequence may have to change.
9203 			 *
9204 			 * And finally, note that parallel SCSI on SPARC
9205 			 * only issues a Sync Cache to DVD-RAM, a newly
9206 			 * supported device.
9207 			 */
9208 #if defined(__i386) || defined(__amd64)
9209 			if (un->un_f_sync_cache_supported ||
9210 			    un->un_f_dvdram_writable_device == TRUE) {
9211 #else
9212 			if (un->un_f_dvdram_writable_device == TRUE) {
9213 #endif
9214 				mutex_exit(SD_MUTEX(un));
9215 				if (sd_pm_entry(un) == DDI_SUCCESS) {
9216 					rval =
9217 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
9218 					    NULL);
9219 					/* ignore error if not supported */
9220 					if (rval == ENOTSUP) {
9221 						rval = 0;
9222 					} else if (rval != 0) {
9223 						rval = EIO;
9224 					}
9225 					sd_pm_exit(un);
9226 				} else {
9227 					rval = EIO;
9228 				}
9229 				mutex_enter(SD_MUTEX(un));
9230 			}
9231 
9232 			/*
9233 			 * For devices which supports DOOR_LOCK, send an ALLOW
9234 			 * MEDIA REMOVAL command, but don't get upset if it
9235 			 * fails. We need to raise the power of the drive before
9236 			 * we can call sd_send_scsi_DOORLOCK()
9237 			 */
9238 			if (un->un_f_doorlock_supported) {
9239 				mutex_exit(SD_MUTEX(un));
9240 				if (sd_pm_entry(un) == DDI_SUCCESS) {
9241 					rval = sd_send_scsi_DOORLOCK(un,
9242 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
9243 
9244 					sd_pm_exit(un);
9245 					if (ISCD(un) && (rval != 0) &&
9246 					    (nodelay != 0)) {
9247 						rval = ENXIO;
9248 					}
9249 				} else {
9250 					rval = EIO;
9251 				}
9252 				mutex_enter(SD_MUTEX(un));
9253 			}
9254 
9255 			/*
9256 			 * If a device has removable media, invalidate all
9257 			 * parameters related to media, such as geometry,
9258 			 * blocksize, and blockcount.
9259 			 */
9260 			if (un->un_f_has_removable_media) {
9261 				sr_ejected(un);
9262 			}
9263 
9264 			/*
9265 			 * Destroy the cache (if it exists) which was
9266 			 * allocated for the write maps since this is
9267 			 * the last close for this media.
9268 			 */
9269 			if (un->un_wm_cache) {
9270 				/*
9271 				 * Check if there are pending commands.
9272 				 * and if there are give a warning and
9273 				 * do not destroy the cache.
9274 				 */
9275 				if (un->un_ncmds_in_driver > 0) {
9276 					scsi_log(SD_DEVINFO(un),
9277 					    sd_label, CE_WARN,
9278 					    "Unable to clean up memory "
9279 					    "because of pending I/O\n");
9280 				} else {
9281 					kmem_cache_destroy(
9282 					    un->un_wm_cache);
9283 					un->un_wm_cache = NULL;
9284 				}
9285 			}
9286 		}
9287 	}
9288 
9289 	mutex_exit(SD_MUTEX(un));
9290 	sema_v(&un->un_semoclose);
9291 
9292 	if (otyp == OTYP_LYR) {
9293 		mutex_enter(&sd_detach_mutex);
9294 		/*
9295 		 * The detach routine may run when the layer count
9296 		 * drops to zero.
9297 		 */
9298 		un->un_layer_count--;
9299 		mutex_exit(&sd_detach_mutex);
9300 	}
9301 
9302 	return (rval);
9303 }
9304 
9305 
9306 /*
9307  *    Function: sd_ready_and_valid
9308  *
9309  * Description: Test if device is ready and has a valid geometry.
9310  *
9311  *   Arguments: dev - device number
9312  *		un  - driver soft state (unit) structure
9313  *
9314  * Return Code: SD_READY_VALID		ready and valid label
9315  *		SD_NOT_READY_VALID	not ready, no label
9316  *		SD_RESERVED_BY_OTHERS	reservation conflict
9317  *
9318  *     Context: Never called at interrupt context.
9319  */
9320 
9321 static int
9322 sd_ready_and_valid(struct sd_lun *un)
9323 {
9324 	struct sd_errstats	*stp;
9325 	uint64_t		capacity;
9326 	uint_t			lbasize;
9327 	int			rval = SD_READY_VALID;
9328 	char			name_str[48];
9329 	int			is_valid;
9330 
9331 	ASSERT(un != NULL);
9332 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9333 
9334 	mutex_enter(SD_MUTEX(un));
9335 	/*
9336 	 * If a device has removable media, we must check if media is
9337 	 * ready when checking if this device is ready and valid.
9338 	 */
9339 	if (un->un_f_has_removable_media) {
9340 		mutex_exit(SD_MUTEX(un));
9341 		if (sd_send_scsi_TEST_UNIT_READY(un, 0) != 0) {
9342 			rval = SD_NOT_READY_VALID;
9343 			mutex_enter(SD_MUTEX(un));
9344 			goto done;
9345 		}
9346 
9347 		is_valid = SD_IS_VALID_LABEL(un);
9348 		mutex_enter(SD_MUTEX(un));
9349 		if (!is_valid ||
9350 		    (un->un_f_blockcount_is_valid == FALSE) ||
9351 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
9352 
9353 			/* capacity has to be read every open. */
9354 			mutex_exit(SD_MUTEX(un));
9355 			if (sd_send_scsi_READ_CAPACITY(un, &capacity,
9356 			    &lbasize, SD_PATH_DIRECT) != 0) {
9357 				cmlb_invalidate(un->un_cmlbhandle,
9358 				    (void *)SD_PATH_DIRECT);
9359 				mutex_enter(SD_MUTEX(un));
9360 				rval = SD_NOT_READY_VALID;
9361 				goto done;
9362 			} else {
9363 				mutex_enter(SD_MUTEX(un));
9364 				sd_update_block_info(un, lbasize, capacity);
9365 			}
9366 		}
9367 
9368 		/*
9369 		 * Check if the media in the device is writable or not.
9370 		 */
9371 		if (!is_valid && ISCD(un)) {
9372 			sd_check_for_writable_cd(un, SD_PATH_DIRECT);
9373 		}
9374 
9375 	} else {
9376 		/*
9377 		 * Do a test unit ready to clear any unit attention from non-cd
9378 		 * devices.
9379 		 */
9380 		mutex_exit(SD_MUTEX(un));
9381 		(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
9382 		mutex_enter(SD_MUTEX(un));
9383 	}
9384 
9385 
9386 	/*
9387 	 * If this is a non 512 block device, allocate space for
9388 	 * the wmap cache. This is being done here since every time
9389 	 * a media is changed this routine will be called and the
9390 	 * block size is a function of media rather than device.
9391 	 */
9392 	if (un->un_f_non_devbsize_supported && NOT_DEVBSIZE(un)) {
9393 		if (!(un->un_wm_cache)) {
9394 			(void) snprintf(name_str, sizeof (name_str),
9395 			    "%s%d_cache",
9396 			    ddi_driver_name(SD_DEVINFO(un)),
9397 			    ddi_get_instance(SD_DEVINFO(un)));
9398 			un->un_wm_cache = kmem_cache_create(
9399 			    name_str, sizeof (struct sd_w_map),
9400 			    8, sd_wm_cache_constructor,
9401 			    sd_wm_cache_destructor, NULL,
9402 			    (void *)un, NULL, 0);
9403 			if (!(un->un_wm_cache)) {
9404 					rval = ENOMEM;
9405 					goto done;
9406 			}
9407 		}
9408 	}
9409 
9410 	if (un->un_state == SD_STATE_NORMAL) {
9411 		/*
9412 		 * If the target is not yet ready here (defined by a TUR
9413 		 * failure), invalidate the geometry and print an 'offline'
9414 		 * message. This is a legacy message, as the state of the
9415 		 * target is not actually changed to SD_STATE_OFFLINE.
9416 		 *
9417 		 * If the TUR fails for EACCES (Reservation Conflict),
9418 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
9419 		 * reservation conflict. If the TUR fails for other
9420 		 * reasons, SD_NOT_READY_VALID will be returned.
9421 		 */
9422 		int err;
9423 
9424 		mutex_exit(SD_MUTEX(un));
9425 		err = sd_send_scsi_TEST_UNIT_READY(un, 0);
9426 		mutex_enter(SD_MUTEX(un));
9427 
9428 		if (err != 0) {
9429 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
9430 			    "offline or reservation conflict\n");
9431 			mutex_exit(SD_MUTEX(un));
9432 			cmlb_invalidate(un->un_cmlbhandle,
9433 			    (void *)SD_PATH_DIRECT);
9434 			mutex_enter(SD_MUTEX(un));
9435 			if (err == EACCES) {
9436 				rval = SD_RESERVED_BY_OTHERS;
9437 			} else {
9438 				rval = SD_NOT_READY_VALID;
9439 			}
9440 			goto done;
9441 		}
9442 	}
9443 
9444 	if (un->un_f_format_in_progress == FALSE) {
9445 		mutex_exit(SD_MUTEX(un));
9446 		if (cmlb_validate(un->un_cmlbhandle, 0,
9447 		    (void *)SD_PATH_DIRECT) != 0) {
9448 			rval = SD_NOT_READY_VALID;
9449 			mutex_enter(SD_MUTEX(un));
9450 			goto done;
9451 		}
9452 		if (un->un_f_pkstats_enabled) {
9453 			sd_set_pstats(un);
9454 			SD_TRACE(SD_LOG_IO_PARTITION, un,
9455 			    "sd_ready_and_valid: un:0x%p pstats created and "
9456 			    "set\n", un);
9457 		}
9458 		mutex_enter(SD_MUTEX(un));
9459 	}
9460 
9461 	/*
9462 	 * If this device supports DOOR_LOCK command, try and send
9463 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
9464 	 * if it fails. For a CD, however, it is an error
9465 	 */
9466 	if (un->un_f_doorlock_supported) {
9467 		mutex_exit(SD_MUTEX(un));
9468 		if ((sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
9469 		    SD_PATH_DIRECT) != 0) && ISCD(un)) {
9470 			rval = SD_NOT_READY_VALID;
9471 			mutex_enter(SD_MUTEX(un));
9472 			goto done;
9473 		}
9474 		mutex_enter(SD_MUTEX(un));
9475 	}
9476 
9477 	/* The state has changed, inform the media watch routines */
9478 	un->un_mediastate = DKIO_INSERTED;
9479 	cv_broadcast(&un->un_state_cv);
9480 	rval = SD_READY_VALID;
9481 
9482 done:
9483 
9484 	/*
9485 	 * Initialize the capacity kstat value, if no media previously
9486 	 * (capacity kstat is 0) and a media has been inserted
9487 	 * (un_blockcount > 0).
9488 	 */
9489 	if (un->un_errstats != NULL) {
9490 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
9491 		if ((stp->sd_capacity.value.ui64 == 0) &&
9492 		    (un->un_f_blockcount_is_valid == TRUE)) {
9493 			stp->sd_capacity.value.ui64 =
9494 			    (uint64_t)((uint64_t)un->un_blockcount *
9495 			    un->un_sys_blocksize);
9496 		}
9497 	}
9498 
9499 	mutex_exit(SD_MUTEX(un));
9500 	return (rval);
9501 }
9502 
9503 
9504 /*
9505  *    Function: sdmin
9506  *
9507  * Description: Routine to limit the size of a data transfer. Used in
9508  *		conjunction with physio(9F).
9509  *
9510  *   Arguments: bp - pointer to the indicated buf(9S) struct.
9511  *
9512  *     Context: Kernel thread context.
9513  */
9514 
9515 static void
9516 sdmin(struct buf *bp)
9517 {
9518 	struct sd_lun	*un;
9519 	int		instance;
9520 
9521 	instance = SDUNIT(bp->b_edev);
9522 
9523 	un = ddi_get_soft_state(sd_state, instance);
9524 	ASSERT(un != NULL);
9525 
9526 	if (bp->b_bcount > un->un_max_xfer_size) {
9527 		bp->b_bcount = un->un_max_xfer_size;
9528 	}
9529 }
9530 
9531 
9532 /*
9533  *    Function: sdread
9534  *
9535  * Description: Driver's read(9e) entry point function.
9536  *
9537  *   Arguments: dev   - device number
9538  *		uio   - structure pointer describing where data is to be stored
9539  *			in user's space
9540  *		cred_p  - user credential pointer
9541  *
9542  * Return Code: ENXIO
9543  *		EIO
9544  *		EINVAL
9545  *		value returned by physio
9546  *
9547  *     Context: Kernel thread context.
9548  */
9549 /* ARGSUSED */
9550 static int
9551 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
9552 {
9553 	struct sd_lun	*un = NULL;
9554 	int		secmask;
9555 	int		err;
9556 
9557 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9558 		return (ENXIO);
9559 	}
9560 
9561 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9562 
9563 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9564 		mutex_enter(SD_MUTEX(un));
9565 		/*
9566 		 * Because the call to sd_ready_and_valid will issue I/O we
9567 		 * must wait here if either the device is suspended or
9568 		 * if it's power level is changing.
9569 		 */
9570 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9571 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9572 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9573 		}
9574 		un->un_ncmds_in_driver++;
9575 		mutex_exit(SD_MUTEX(un));
9576 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9577 			mutex_enter(SD_MUTEX(un));
9578 			un->un_ncmds_in_driver--;
9579 			ASSERT(un->un_ncmds_in_driver >= 0);
9580 			mutex_exit(SD_MUTEX(un));
9581 			return (EIO);
9582 		}
9583 		mutex_enter(SD_MUTEX(un));
9584 		un->un_ncmds_in_driver--;
9585 		ASSERT(un->un_ncmds_in_driver >= 0);
9586 		mutex_exit(SD_MUTEX(un));
9587 	}
9588 
9589 	/*
9590 	 * Read requests are restricted to multiples of the system block size.
9591 	 */
9592 	secmask = un->un_sys_blocksize - 1;
9593 
9594 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9595 		SD_ERROR(SD_LOG_READ_WRITE, un,
9596 		    "sdread: file offset not modulo %d\n",
9597 		    un->un_sys_blocksize);
9598 		err = EINVAL;
9599 	} else if (uio->uio_iov->iov_len & (secmask)) {
9600 		SD_ERROR(SD_LOG_READ_WRITE, un,
9601 		    "sdread: transfer length not modulo %d\n",
9602 		    un->un_sys_blocksize);
9603 		err = EINVAL;
9604 	} else {
9605 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
9606 	}
9607 	return (err);
9608 }
9609 
9610 
9611 /*
9612  *    Function: sdwrite
9613  *
9614  * Description: Driver's write(9e) entry point function.
9615  *
9616  *   Arguments: dev   - device number
9617  *		uio   - structure pointer describing where data is stored in
9618  *			user's space
9619  *		cred_p  - user credential pointer
9620  *
9621  * Return Code: ENXIO
9622  *		EIO
9623  *		EINVAL
9624  *		value returned by physio
9625  *
9626  *     Context: Kernel thread context.
9627  */
9628 /* ARGSUSED */
9629 static int
9630 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
9631 {
9632 	struct sd_lun	*un = NULL;
9633 	int		secmask;
9634 	int		err;
9635 
9636 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9637 		return (ENXIO);
9638 	}
9639 
9640 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9641 
9642 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9643 		mutex_enter(SD_MUTEX(un));
9644 		/*
9645 		 * Because the call to sd_ready_and_valid will issue I/O we
9646 		 * must wait here if either the device is suspended or
9647 		 * if it's power level is changing.
9648 		 */
9649 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9650 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9651 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9652 		}
9653 		un->un_ncmds_in_driver++;
9654 		mutex_exit(SD_MUTEX(un));
9655 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9656 			mutex_enter(SD_MUTEX(un));
9657 			un->un_ncmds_in_driver--;
9658 			ASSERT(un->un_ncmds_in_driver >= 0);
9659 			mutex_exit(SD_MUTEX(un));
9660 			return (EIO);
9661 		}
9662 		mutex_enter(SD_MUTEX(un));
9663 		un->un_ncmds_in_driver--;
9664 		ASSERT(un->un_ncmds_in_driver >= 0);
9665 		mutex_exit(SD_MUTEX(un));
9666 	}
9667 
9668 	/*
9669 	 * Write requests are restricted to multiples of the system block size.
9670 	 */
9671 	secmask = un->un_sys_blocksize - 1;
9672 
9673 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9674 		SD_ERROR(SD_LOG_READ_WRITE, un,
9675 		    "sdwrite: file offset not modulo %d\n",
9676 		    un->un_sys_blocksize);
9677 		err = EINVAL;
9678 	} else if (uio->uio_iov->iov_len & (secmask)) {
9679 		SD_ERROR(SD_LOG_READ_WRITE, un,
9680 		    "sdwrite: transfer length not modulo %d\n",
9681 		    un->un_sys_blocksize);
9682 		err = EINVAL;
9683 	} else {
9684 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
9685 	}
9686 	return (err);
9687 }
9688 
9689 
9690 /*
9691  *    Function: sdaread
9692  *
9693  * Description: Driver's aread(9e) entry point function.
9694  *
9695  *   Arguments: dev   - device number
9696  *		aio   - structure pointer describing where data is to be stored
9697  *		cred_p  - user credential pointer
9698  *
9699  * Return Code: ENXIO
9700  *		EIO
9701  *		EINVAL
9702  *		value returned by aphysio
9703  *
9704  *     Context: Kernel thread context.
9705  */
9706 /* ARGSUSED */
9707 static int
9708 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
9709 {
9710 	struct sd_lun	*un = NULL;
9711 	struct uio	*uio = aio->aio_uio;
9712 	int		secmask;
9713 	int		err;
9714 
9715 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9716 		return (ENXIO);
9717 	}
9718 
9719 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9720 
9721 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9722 		mutex_enter(SD_MUTEX(un));
9723 		/*
9724 		 * Because the call to sd_ready_and_valid will issue I/O we
9725 		 * must wait here if either the device is suspended or
9726 		 * if it's power level is changing.
9727 		 */
9728 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9729 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9730 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9731 		}
9732 		un->un_ncmds_in_driver++;
9733 		mutex_exit(SD_MUTEX(un));
9734 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9735 			mutex_enter(SD_MUTEX(un));
9736 			un->un_ncmds_in_driver--;
9737 			ASSERT(un->un_ncmds_in_driver >= 0);
9738 			mutex_exit(SD_MUTEX(un));
9739 			return (EIO);
9740 		}
9741 		mutex_enter(SD_MUTEX(un));
9742 		un->un_ncmds_in_driver--;
9743 		ASSERT(un->un_ncmds_in_driver >= 0);
9744 		mutex_exit(SD_MUTEX(un));
9745 	}
9746 
9747 	/*
9748 	 * Read requests are restricted to multiples of the system block size.
9749 	 */
9750 	secmask = un->un_sys_blocksize - 1;
9751 
9752 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9753 		SD_ERROR(SD_LOG_READ_WRITE, un,
9754 		    "sdaread: file offset not modulo %d\n",
9755 		    un->un_sys_blocksize);
9756 		err = EINVAL;
9757 	} else if (uio->uio_iov->iov_len & (secmask)) {
9758 		SD_ERROR(SD_LOG_READ_WRITE, un,
9759 		    "sdaread: transfer length not modulo %d\n",
9760 		    un->un_sys_blocksize);
9761 		err = EINVAL;
9762 	} else {
9763 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
9764 	}
9765 	return (err);
9766 }
9767 
9768 
9769 /*
9770  *    Function: sdawrite
9771  *
9772  * Description: Driver's awrite(9e) entry point function.
9773  *
9774  *   Arguments: dev   - device number
9775  *		aio   - structure pointer describing where data is stored
9776  *		cred_p  - user credential pointer
9777  *
9778  * Return Code: ENXIO
9779  *		EIO
9780  *		EINVAL
9781  *		value returned by aphysio
9782  *
9783  *     Context: Kernel thread context.
9784  */
9785 /* ARGSUSED */
9786 static int
9787 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
9788 {
9789 	struct sd_lun	*un = NULL;
9790 	struct uio	*uio = aio->aio_uio;
9791 	int		secmask;
9792 	int		err;
9793 
9794 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9795 		return (ENXIO);
9796 	}
9797 
9798 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9799 
9800 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9801 		mutex_enter(SD_MUTEX(un));
9802 		/*
9803 		 * Because the call to sd_ready_and_valid will issue I/O we
9804 		 * must wait here if either the device is suspended or
9805 		 * if it's power level is changing.
9806 		 */
9807 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9808 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9809 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9810 		}
9811 		un->un_ncmds_in_driver++;
9812 		mutex_exit(SD_MUTEX(un));
9813 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9814 			mutex_enter(SD_MUTEX(un));
9815 			un->un_ncmds_in_driver--;
9816 			ASSERT(un->un_ncmds_in_driver >= 0);
9817 			mutex_exit(SD_MUTEX(un));
9818 			return (EIO);
9819 		}
9820 		mutex_enter(SD_MUTEX(un));
9821 		un->un_ncmds_in_driver--;
9822 		ASSERT(un->un_ncmds_in_driver >= 0);
9823 		mutex_exit(SD_MUTEX(un));
9824 	}
9825 
9826 	/*
9827 	 * Write requests are restricted to multiples of the system block size.
9828 	 */
9829 	secmask = un->un_sys_blocksize - 1;
9830 
9831 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9832 		SD_ERROR(SD_LOG_READ_WRITE, un,
9833 		    "sdawrite: file offset not modulo %d\n",
9834 		    un->un_sys_blocksize);
9835 		err = EINVAL;
9836 	} else if (uio->uio_iov->iov_len & (secmask)) {
9837 		SD_ERROR(SD_LOG_READ_WRITE, un,
9838 		    "sdawrite: transfer length not modulo %d\n",
9839 		    un->un_sys_blocksize);
9840 		err = EINVAL;
9841 	} else {
9842 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
9843 	}
9844 	return (err);
9845 }
9846 
9847 
9848 
9849 
9850 
9851 /*
9852  * Driver IO processing follows the following sequence:
9853  *
9854  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
9855  *         |                |                     ^
9856  *         v                v                     |
9857  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
9858  *         |                |                     |                   |
9859  *         v                |                     |                   |
9860  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
9861  *         |                |                     ^                   ^
9862  *         v                v                     |                   |
9863  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
9864  *         |                |                     |                   |
9865  *     +---+                |                     +------------+      +-------+
9866  *     |                    |                                  |              |
9867  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
9868  *     |                    v                                  |              |
9869  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
9870  *     |                    |                                  ^              |
9871  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
9872  *     |                    v                                  |              |
9873  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
9874  *     |                    |                                  ^              |
9875  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
9876  *     |                    v                                  |              |
9877  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
9878  *     |                    |                                  ^              |
9879  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
9880  *     |                    v                                  |              |
9881  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
9882  *     |                    |                                  ^              |
9883  *     |                    |                                  |              |
9884  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
9885  *                          |                           ^
9886  *                          v                           |
9887  *                   sd_core_iostart()                  |
9888  *                          |                           |
9889  *                          |                           +------>(*destroypkt)()
9890  *                          +-> sd_start_cmds() <-+     |           |
9891  *                          |                     |     |           v
9892  *                          |                     |     |  scsi_destroy_pkt(9F)
9893  *                          |                     |     |
9894  *                          +->(*initpkt)()       +- sdintr()
9895  *                          |  |                        |  |
9896  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
9897  *                          |  +-> scsi_setup_cdb(9F)   |
9898  *                          |                           |
9899  *                          +--> scsi_transport(9F)     |
9900  *                                     |                |
9901  *                                     +----> SCSA ---->+
9902  *
9903  *
9904  * This code is based upon the following presumptions:
9905  *
9906  *   - iostart and iodone functions operate on buf(9S) structures. These
9907  *     functions perform the necessary operations on the buf(9S) and pass
9908  *     them along to the next function in the chain by using the macros
9909  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
9910  *     (for iodone side functions).
9911  *
9912  *   - The iostart side functions may sleep. The iodone side functions
9913  *     are called under interrupt context and may NOT sleep. Therefore
9914  *     iodone side functions also may not call iostart side functions.
9915  *     (NOTE: iostart side functions should NOT sleep for memory, as
9916  *     this could result in deadlock.)
9917  *
9918  *   - An iostart side function may call its corresponding iodone side
9919  *     function directly (if necessary).
9920  *
9921  *   - In the event of an error, an iostart side function can return a buf(9S)
9922  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
9923  *     b_error in the usual way of course).
9924  *
9925  *   - The taskq mechanism may be used by the iodone side functions to dispatch
9926  *     requests to the iostart side functions.  The iostart side functions in
9927  *     this case would be called under the context of a taskq thread, so it's
9928  *     OK for them to block/sleep/spin in this case.
9929  *
9930  *   - iostart side functions may allocate "shadow" buf(9S) structs and
9931  *     pass them along to the next function in the chain.  The corresponding
9932  *     iodone side functions must coalesce the "shadow" bufs and return
9933  *     the "original" buf to the next higher layer.
9934  *
9935  *   - The b_private field of the buf(9S) struct holds a pointer to
9936  *     an sd_xbuf struct, which contains information needed to
9937  *     construct the scsi_pkt for the command.
9938  *
9939  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
9940  *     layer must acquire & release the SD_MUTEX(un) as needed.
9941  */
9942 
9943 
9944 /*
9945  * Create taskq for all targets in the system. This is created at
9946  * _init(9E) and destroyed at _fini(9E).
9947  *
9948  * Note: here we set the minalloc to a reasonably high number to ensure that
9949  * we will have an adequate supply of task entries available at interrupt time.
9950  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
9951  * sd_create_taskq().  Since we do not want to sleep for allocations at
9952  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
9953  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
9954  * requests any one instant in time.
9955  */
9956 #define	SD_TASKQ_NUMTHREADS	8
9957 #define	SD_TASKQ_MINALLOC	256
9958 #define	SD_TASKQ_MAXALLOC	256
9959 
9960 static taskq_t	*sd_tq = NULL;
9961 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
9962 
9963 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
9964 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
9965 
9966 /*
9967  * The following task queue is being created for the write part of
9968  * read-modify-write of non-512 block size devices.
9969  * Limit the number of threads to 1 for now. This number has been chosen
9970  * considering the fact that it applies only to dvd ram drives/MO drives
9971  * currently. Performance for which is not main criteria at this stage.
9972  * Note: It needs to be explored if we can use a single taskq in future
9973  */
9974 #define	SD_WMR_TASKQ_NUMTHREADS	1
9975 static taskq_t	*sd_wmr_tq = NULL;
9976 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
9977 
9978 /*
9979  *    Function: sd_taskq_create
9980  *
9981  * Description: Create taskq thread(s) and preallocate task entries
9982  *
9983  * Return Code: Returns a pointer to the allocated taskq_t.
9984  *
9985  *     Context: Can sleep. Requires blockable context.
9986  *
9987  *       Notes: - The taskq() facility currently is NOT part of the DDI.
9988  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
9989  *		- taskq_create() will block for memory, also it will panic
9990  *		  if it cannot create the requested number of threads.
9991  *		- Currently taskq_create() creates threads that cannot be
9992  *		  swapped.
9993  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
9994  *		  supply of taskq entries at interrupt time (ie, so that we
9995  *		  do not have to sleep for memory)
9996  */
9997 
9998 static void
9999 sd_taskq_create(void)
10000 {
10001 	char	taskq_name[TASKQ_NAMELEN];
10002 
10003 	ASSERT(sd_tq == NULL);
10004 	ASSERT(sd_wmr_tq == NULL);
10005 
10006 	(void) snprintf(taskq_name, sizeof (taskq_name),
10007 	    "%s_drv_taskq", sd_label);
10008 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
10009 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10010 	    TASKQ_PREPOPULATE));
10011 
10012 	(void) snprintf(taskq_name, sizeof (taskq_name),
10013 	    "%s_rmw_taskq", sd_label);
10014 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
10015 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10016 	    TASKQ_PREPOPULATE));
10017 }
10018 
10019 
10020 /*
10021  *    Function: sd_taskq_delete
10022  *
10023  * Description: Complementary cleanup routine for sd_taskq_create().
10024  *
10025  *     Context: Kernel thread context.
10026  */
10027 
10028 static void
10029 sd_taskq_delete(void)
10030 {
10031 	ASSERT(sd_tq != NULL);
10032 	ASSERT(sd_wmr_tq != NULL);
10033 	taskq_destroy(sd_tq);
10034 	taskq_destroy(sd_wmr_tq);
10035 	sd_tq = NULL;
10036 	sd_wmr_tq = NULL;
10037 }
10038 
10039 
10040 /*
10041  *    Function: sdstrategy
10042  *
10043  * Description: Driver's strategy (9E) entry point function.
10044  *
10045  *   Arguments: bp - pointer to buf(9S)
10046  *
10047  * Return Code: Always returns zero
10048  *
10049  *     Context: Kernel thread context.
10050  */
10051 
10052 static int
10053 sdstrategy(struct buf *bp)
10054 {
10055 	struct sd_lun *un;
10056 
10057 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
10058 	if (un == NULL) {
10059 		bioerror(bp, EIO);
10060 		bp->b_resid = bp->b_bcount;
10061 		biodone(bp);
10062 		return (0);
10063 	}
10064 	/* As was done in the past, fail new cmds. if state is dumping. */
10065 	if (un->un_state == SD_STATE_DUMPING) {
10066 		bioerror(bp, ENXIO);
10067 		bp->b_resid = bp->b_bcount;
10068 		biodone(bp);
10069 		return (0);
10070 	}
10071 
10072 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10073 
10074 	/*
10075 	 * Commands may sneak in while we released the mutex in
10076 	 * DDI_SUSPEND, we should block new commands. However, old
10077 	 * commands that are still in the driver at this point should
10078 	 * still be allowed to drain.
10079 	 */
10080 	mutex_enter(SD_MUTEX(un));
10081 	/*
10082 	 * Must wait here if either the device is suspended or
10083 	 * if it's power level is changing.
10084 	 */
10085 	while ((un->un_state == SD_STATE_SUSPENDED) ||
10086 	    (un->un_state == SD_STATE_PM_CHANGING)) {
10087 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10088 	}
10089 
10090 	un->un_ncmds_in_driver++;
10091 
10092 	/*
10093 	 * atapi: Since we are running the CD for now in PIO mode we need to
10094 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
10095 	 * the HBA's init_pkt routine.
10096 	 */
10097 	if (un->un_f_cfg_is_atapi == TRUE) {
10098 		mutex_exit(SD_MUTEX(un));
10099 		bp_mapin(bp);
10100 		mutex_enter(SD_MUTEX(un));
10101 	}
10102 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
10103 	    un->un_ncmds_in_driver);
10104 
10105 	mutex_exit(SD_MUTEX(un));
10106 
10107 	/*
10108 	 * This will (eventually) allocate the sd_xbuf area and
10109 	 * call sd_xbuf_strategy().  We just want to return the
10110 	 * result of ddi_xbuf_qstrategy so that we have an opt-
10111 	 * imized tail call which saves us a stack frame.
10112 	 */
10113 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
10114 }
10115 
10116 
10117 /*
10118  *    Function: sd_xbuf_strategy
10119  *
10120  * Description: Function for initiating IO operations via the
10121  *		ddi_xbuf_qstrategy() mechanism.
10122  *
10123  *     Context: Kernel thread context.
10124  */
10125 
10126 static void
10127 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
10128 {
10129 	struct sd_lun *un = arg;
10130 
10131 	ASSERT(bp != NULL);
10132 	ASSERT(xp != NULL);
10133 	ASSERT(un != NULL);
10134 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10135 
10136 	/*
10137 	 * Initialize the fields in the xbuf and save a pointer to the
10138 	 * xbuf in bp->b_private.
10139 	 */
10140 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
10141 
10142 	/* Send the buf down the iostart chain */
10143 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
10144 }
10145 
10146 
10147 /*
10148  *    Function: sd_xbuf_init
10149  *
10150  * Description: Prepare the given sd_xbuf struct for use.
10151  *
10152  *   Arguments: un - ptr to softstate
10153  *		bp - ptr to associated buf(9S)
10154  *		xp - ptr to associated sd_xbuf
10155  *		chain_type - IO chain type to use:
10156  *			SD_CHAIN_NULL
10157  *			SD_CHAIN_BUFIO
10158  *			SD_CHAIN_USCSI
10159  *			SD_CHAIN_DIRECT
10160  *			SD_CHAIN_DIRECT_PRIORITY
10161  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
10162  *			initialization; may be NULL if none.
10163  *
10164  *     Context: Kernel thread context
10165  */
10166 
10167 static void
10168 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
10169 	uchar_t chain_type, void *pktinfop)
10170 {
10171 	int index;
10172 
10173 	ASSERT(un != NULL);
10174 	ASSERT(bp != NULL);
10175 	ASSERT(xp != NULL);
10176 
10177 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
10178 	    bp, chain_type);
10179 
10180 	xp->xb_un	= un;
10181 	xp->xb_pktp	= NULL;
10182 	xp->xb_pktinfo	= pktinfop;
10183 	xp->xb_private	= bp->b_private;
10184 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
10185 
10186 	/*
10187 	 * Set up the iostart and iodone chain indexes in the xbuf, based
10188 	 * upon the specified chain type to use.
10189 	 */
10190 	switch (chain_type) {
10191 	case SD_CHAIN_NULL:
10192 		/*
10193 		 * Fall thru to just use the values for the buf type, even
10194 		 * tho for the NULL chain these values will never be used.
10195 		 */
10196 		/* FALLTHRU */
10197 	case SD_CHAIN_BUFIO:
10198 		index = un->un_buf_chain_type;
10199 		break;
10200 	case SD_CHAIN_USCSI:
10201 		index = un->un_uscsi_chain_type;
10202 		break;
10203 	case SD_CHAIN_DIRECT:
10204 		index = un->un_direct_chain_type;
10205 		break;
10206 	case SD_CHAIN_DIRECT_PRIORITY:
10207 		index = un->un_priority_chain_type;
10208 		break;
10209 	default:
10210 		/* We're really broken if we ever get here... */
10211 		panic("sd_xbuf_init: illegal chain type!");
10212 		/*NOTREACHED*/
10213 	}
10214 
10215 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
10216 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
10217 
10218 	/*
10219 	 * It might be a bit easier to simply bzero the entire xbuf above,
10220 	 * but it turns out that since we init a fair number of members anyway,
10221 	 * we save a fair number cycles by doing explicit assignment of zero.
10222 	 */
10223 	xp->xb_pkt_flags	= 0;
10224 	xp->xb_dma_resid	= 0;
10225 	xp->xb_retry_count	= 0;
10226 	xp->xb_victim_retry_count = 0;
10227 	xp->xb_ua_retry_count	= 0;
10228 	xp->xb_nr_retry_count	= 0;
10229 	xp->xb_sense_bp		= NULL;
10230 	xp->xb_sense_status	= 0;
10231 	xp->xb_sense_state	= 0;
10232 	xp->xb_sense_resid	= 0;
10233 
10234 	bp->b_private	= xp;
10235 	bp->b_flags	&= ~(B_DONE | B_ERROR);
10236 	bp->b_resid	= 0;
10237 	bp->av_forw	= NULL;
10238 	bp->av_back	= NULL;
10239 	bioerror(bp, 0);
10240 
10241 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
10242 }
10243 
10244 
10245 /*
10246  *    Function: sd_uscsi_strategy
10247  *
10248  * Description: Wrapper for calling into the USCSI chain via physio(9F)
10249  *
10250  *   Arguments: bp - buf struct ptr
10251  *
10252  * Return Code: Always returns 0
10253  *
10254  *     Context: Kernel thread context
10255  */
10256 
10257 static int
10258 sd_uscsi_strategy(struct buf *bp)
10259 {
10260 	struct sd_lun		*un;
10261 	struct sd_uscsi_info	*uip;
10262 	struct sd_xbuf		*xp;
10263 	uchar_t			chain_type;
10264 
10265 	ASSERT(bp != NULL);
10266 
10267 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
10268 	if (un == NULL) {
10269 		bioerror(bp, EIO);
10270 		bp->b_resid = bp->b_bcount;
10271 		biodone(bp);
10272 		return (0);
10273 	}
10274 
10275 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10276 
10277 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
10278 
10279 	mutex_enter(SD_MUTEX(un));
10280 	/*
10281 	 * atapi: Since we are running the CD for now in PIO mode we need to
10282 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
10283 	 * the HBA's init_pkt routine.
10284 	 */
10285 	if (un->un_f_cfg_is_atapi == TRUE) {
10286 		mutex_exit(SD_MUTEX(un));
10287 		bp_mapin(bp);
10288 		mutex_enter(SD_MUTEX(un));
10289 	}
10290 	un->un_ncmds_in_driver++;
10291 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
10292 	    un->un_ncmds_in_driver);
10293 	mutex_exit(SD_MUTEX(un));
10294 
10295 	/*
10296 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
10297 	 */
10298 	ASSERT(bp->b_private != NULL);
10299 	uip = (struct sd_uscsi_info *)bp->b_private;
10300 
10301 	switch (uip->ui_flags) {
10302 	case SD_PATH_DIRECT:
10303 		chain_type = SD_CHAIN_DIRECT;
10304 		break;
10305 	case SD_PATH_DIRECT_PRIORITY:
10306 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
10307 		break;
10308 	default:
10309 		chain_type = SD_CHAIN_USCSI;
10310 		break;
10311 	}
10312 
10313 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
10314 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
10315 
10316 	/* Use the index obtained within xbuf_init */
10317 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
10318 
10319 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
10320 
10321 	return (0);
10322 }
10323 
10324 /*
10325  *    Function: sd_send_scsi_cmd
10326  *
10327  * Description: Runs a USCSI command for user (when called thru sdioctl),
10328  *		or for the driver
10329  *
10330  *   Arguments: dev - the dev_t for the device
10331  *		incmd - ptr to a valid uscsi_cmd struct
10332  *		flag - bit flag, indicating open settings, 32/64 bit type
10333  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
10334  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
10335  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
10336  *			to use the USCSI "direct" chain and bypass the normal
10337  *			command waitq.
10338  *
10339  * Return Code: 0 -  successful completion of the given command
10340  *		EIO - scsi_uscsi_handle_command() failed
10341  *		ENXIO  - soft state not found for specified dev
10342  *		EINVAL
10343  *		EFAULT - copyin/copyout error
10344  *		return code of scsi_uscsi_handle_command():
10345  *			EIO
10346  *			ENXIO
10347  *			EACCES
10348  *
10349  *     Context: Waits for command to complete. Can sleep.
10350  */
10351 
10352 static int
10353 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
10354 	enum uio_seg dataspace, int path_flag)
10355 {
10356 	struct sd_uscsi_info	*uip;
10357 	struct uscsi_cmd	*uscmd;
10358 	struct sd_lun	*un;
10359 	int	format = 0;
10360 	int	rval;
10361 
10362 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
10363 	if (un == NULL) {
10364 		return (ENXIO);
10365 	}
10366 
10367 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10368 
10369 #ifdef SDDEBUG
10370 	switch (dataspace) {
10371 	case UIO_USERSPACE:
10372 		SD_TRACE(SD_LOG_IO, un,
10373 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_USERSPACE\n", un);
10374 		break;
10375 	case UIO_SYSSPACE:
10376 		SD_TRACE(SD_LOG_IO, un,
10377 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_SYSSPACE\n", un);
10378 		break;
10379 	default:
10380 		SD_TRACE(SD_LOG_IO, un,
10381 		    "sd_send_scsi_cmd: entry: un:0x%p UNEXPECTED SPACE\n", un);
10382 		break;
10383 	}
10384 #endif
10385 
10386 	rval = scsi_uscsi_alloc_and_copyin((intptr_t)incmd, flag,
10387 	    SD_ADDRESS(un), &uscmd);
10388 	if (rval != 0) {
10389 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
10390 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
10391 		return (rval);
10392 	}
10393 
10394 	if ((uscmd->uscsi_cdb != NULL) &&
10395 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
10396 		mutex_enter(SD_MUTEX(un));
10397 		un->un_f_format_in_progress = TRUE;
10398 		mutex_exit(SD_MUTEX(un));
10399 		format = 1;
10400 	}
10401 
10402 	/*
10403 	 * Allocate an sd_uscsi_info struct and fill it with the info
10404 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
10405 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
10406 	 * since we allocate the buf here in this function, we do not
10407 	 * need to preserve the prior contents of b_private.
10408 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
10409 	 */
10410 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
10411 	uip->ui_flags = path_flag;
10412 	uip->ui_cmdp = uscmd;
10413 
10414 	/*
10415 	 * Commands sent with priority are intended for error recovery
10416 	 * situations, and do not have retries performed.
10417 	 */
10418 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
10419 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
10420 	}
10421 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
10422 
10423 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
10424 	    sd_uscsi_strategy, NULL, uip);
10425 
10426 #ifdef SDDEBUG
10427 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10428 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
10429 	    uscmd->uscsi_status, uscmd->uscsi_resid);
10430 	if (uscmd->uscsi_bufaddr != NULL) {
10431 		SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10432 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
10433 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
10434 		if (dataspace == UIO_SYSSPACE) {
10435 			SD_DUMP_MEMORY(un, SD_LOG_IO,
10436 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
10437 			    uscmd->uscsi_buflen, SD_LOG_HEX);
10438 		}
10439 	}
10440 #endif
10441 
10442 	if (format == 1) {
10443 		mutex_enter(SD_MUTEX(un));
10444 		un->un_f_format_in_progress = FALSE;
10445 		mutex_exit(SD_MUTEX(un));
10446 	}
10447 
10448 	(void) scsi_uscsi_copyout_and_free((intptr_t)incmd, uscmd);
10449 	kmem_free(uip, sizeof (struct sd_uscsi_info));
10450 
10451 	return (rval);
10452 }
10453 
10454 
10455 /*
10456  *    Function: sd_buf_iodone
10457  *
10458  * Description: Frees the sd_xbuf & returns the buf to its originator.
10459  *
10460  *     Context: May be called from interrupt context.
10461  */
10462 /* ARGSUSED */
10463 static void
10464 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
10465 {
10466 	struct sd_xbuf *xp;
10467 
10468 	ASSERT(un != NULL);
10469 	ASSERT(bp != NULL);
10470 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10471 
10472 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
10473 
10474 	xp = SD_GET_XBUF(bp);
10475 	ASSERT(xp != NULL);
10476 
10477 	mutex_enter(SD_MUTEX(un));
10478 
10479 	/*
10480 	 * Grab time when the cmd completed.
10481 	 * This is used for determining if the system has been
10482 	 * idle long enough to make it idle to the PM framework.
10483 	 * This is for lowering the overhead, and therefore improving
10484 	 * performance per I/O operation.
10485 	 */
10486 	un->un_pm_idle_time = ddi_get_time();
10487 
10488 	un->un_ncmds_in_driver--;
10489 	ASSERT(un->un_ncmds_in_driver >= 0);
10490 	SD_INFO(SD_LOG_IO, un, "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
10491 	    un->un_ncmds_in_driver);
10492 
10493 	mutex_exit(SD_MUTEX(un));
10494 
10495 	ddi_xbuf_done(bp, un->un_xbuf_attr);	/* xbuf is gone after this */
10496 	biodone(bp);				/* bp is gone after this */
10497 
10498 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
10499 }
10500 
10501 
10502 /*
10503  *    Function: sd_uscsi_iodone
10504  *
10505  * Description: Frees the sd_xbuf & returns the buf to its originator.
10506  *
10507  *     Context: May be called from interrupt context.
10508  */
10509 /* ARGSUSED */
10510 static void
10511 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
10512 {
10513 	struct sd_xbuf *xp;
10514 
10515 	ASSERT(un != NULL);
10516 	ASSERT(bp != NULL);
10517 
10518 	xp = SD_GET_XBUF(bp);
10519 	ASSERT(xp != NULL);
10520 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10521 
10522 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
10523 
10524 	bp->b_private = xp->xb_private;
10525 
10526 	mutex_enter(SD_MUTEX(un));
10527 
10528 	/*
10529 	 * Grab time when the cmd completed.
10530 	 * This is used for determining if the system has been
10531 	 * idle long enough to make it idle to the PM framework.
10532 	 * This is for lowering the overhead, and therefore improving
10533 	 * performance per I/O operation.
10534 	 */
10535 	un->un_pm_idle_time = ddi_get_time();
10536 
10537 	un->un_ncmds_in_driver--;
10538 	ASSERT(un->un_ncmds_in_driver >= 0);
10539 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
10540 	    un->un_ncmds_in_driver);
10541 
10542 	mutex_exit(SD_MUTEX(un));
10543 
10544 	kmem_free(xp, sizeof (struct sd_xbuf));
10545 	biodone(bp);
10546 
10547 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
10548 }
10549 
10550 
10551 /*
10552  *    Function: sd_mapblockaddr_iostart
10553  *
10554  * Description: Verify request lies within the partition limits for
10555  *		the indicated minor device.  Issue "overrun" buf if
10556  *		request would exceed partition range.  Converts
10557  *		partition-relative block address to absolute.
10558  *
10559  *     Context: Can sleep
10560  *
10561  *      Issues: This follows what the old code did, in terms of accessing
10562  *		some of the partition info in the unit struct without holding
10563  *		the mutext.  This is a general issue, if the partition info
10564  *		can be altered while IO is in progress... as soon as we send
10565  *		a buf, its partitioning can be invalid before it gets to the
10566  *		device.  Probably the right fix is to move partitioning out
10567  *		of the driver entirely.
10568  */
10569 
10570 static void
10571 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
10572 {
10573 	diskaddr_t	nblocks;	/* #blocks in the given partition */
10574 	daddr_t	blocknum;	/* Block number specified by the buf */
10575 	size_t	requested_nblocks;
10576 	size_t	available_nblocks;
10577 	int	partition;
10578 	diskaddr_t	partition_offset;
10579 	struct sd_xbuf *xp;
10580 
10581 
10582 	ASSERT(un != NULL);
10583 	ASSERT(bp != NULL);
10584 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10585 
10586 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10587 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
10588 
10589 	xp = SD_GET_XBUF(bp);
10590 	ASSERT(xp != NULL);
10591 
10592 	/*
10593 	 * If the geometry is not indicated as valid, attempt to access
10594 	 * the unit & verify the geometry/label. This can be the case for
10595 	 * removable-media devices, of if the device was opened in
10596 	 * NDELAY/NONBLOCK mode.
10597 	 */
10598 	if (!SD_IS_VALID_LABEL(un) &&
10599 	    (sd_ready_and_valid(un) != SD_READY_VALID)) {
10600 		/*
10601 		 * For removable devices it is possible to start an I/O
10602 		 * without a media by opening the device in nodelay mode.
10603 		 * Also for writable CDs there can be many scenarios where
10604 		 * there is no geometry yet but volume manager is trying to
10605 		 * issue a read() just because it can see TOC on the CD. So
10606 		 * do not print a message for removables.
10607 		 */
10608 		if (!un->un_f_has_removable_media) {
10609 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10610 			    "i/o to invalid geometry\n");
10611 		}
10612 		bioerror(bp, EIO);
10613 		bp->b_resid = bp->b_bcount;
10614 		SD_BEGIN_IODONE(index, un, bp);
10615 		return;
10616 	}
10617 
10618 	partition = SDPART(bp->b_edev);
10619 
10620 	nblocks = 0;
10621 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
10622 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
10623 
10624 	/*
10625 	 * blocknum is the starting block number of the request. At this
10626 	 * point it is still relative to the start of the minor device.
10627 	 */
10628 	blocknum = xp->xb_blkno;
10629 
10630 	/*
10631 	 * Legacy: If the starting block number is one past the last block
10632 	 * in the partition, do not set B_ERROR in the buf.
10633 	 */
10634 	if (blocknum == nblocks)  {
10635 		goto error_exit;
10636 	}
10637 
10638 	/*
10639 	 * Confirm that the first block of the request lies within the
10640 	 * partition limits. Also the requested number of bytes must be
10641 	 * a multiple of the system block size.
10642 	 */
10643 	if ((blocknum < 0) || (blocknum >= nblocks) ||
10644 	    ((bp->b_bcount & (un->un_sys_blocksize - 1)) != 0)) {
10645 		bp->b_flags |= B_ERROR;
10646 		goto error_exit;
10647 	}
10648 
10649 	/*
10650 	 * If the requsted # blocks exceeds the available # blocks, that
10651 	 * is an overrun of the partition.
10652 	 */
10653 	requested_nblocks = SD_BYTES2SYSBLOCKS(un, bp->b_bcount);
10654 	available_nblocks = (size_t)(nblocks - blocknum);
10655 	ASSERT(nblocks >= blocknum);
10656 
10657 	if (requested_nblocks > available_nblocks) {
10658 		/*
10659 		 * Allocate an "overrun" buf to allow the request to proceed
10660 		 * for the amount of space available in the partition. The
10661 		 * amount not transferred will be added into the b_resid
10662 		 * when the operation is complete. The overrun buf
10663 		 * replaces the original buf here, and the original buf
10664 		 * is saved inside the overrun buf, for later use.
10665 		 */
10666 		size_t resid = SD_SYSBLOCKS2BYTES(un,
10667 		    (offset_t)(requested_nblocks - available_nblocks));
10668 		size_t count = bp->b_bcount - resid;
10669 		/*
10670 		 * Note: count is an unsigned entity thus it'll NEVER
10671 		 * be less than 0 so ASSERT the original values are
10672 		 * correct.
10673 		 */
10674 		ASSERT(bp->b_bcount >= resid);
10675 
10676 		bp = sd_bioclone_alloc(bp, count, blocknum,
10677 		    (int (*)(struct buf *)) sd_mapblockaddr_iodone);
10678 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
10679 		ASSERT(xp != NULL);
10680 	}
10681 
10682 	/* At this point there should be no residual for this buf. */
10683 	ASSERT(bp->b_resid == 0);
10684 
10685 	/* Convert the block number to an absolute address. */
10686 	xp->xb_blkno += partition_offset;
10687 
10688 	SD_NEXT_IOSTART(index, un, bp);
10689 
10690 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10691 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
10692 
10693 	return;
10694 
10695 error_exit:
10696 	bp->b_resid = bp->b_bcount;
10697 	SD_BEGIN_IODONE(index, un, bp);
10698 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10699 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
10700 }
10701 
10702 
10703 /*
10704  *    Function: sd_mapblockaddr_iodone
10705  *
10706  * Description: Completion-side processing for partition management.
10707  *
10708  *     Context: May be called under interrupt context
10709  */
10710 
10711 static void
10712 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
10713 {
10714 	/* int	partition; */	/* Not used, see below. */
10715 	ASSERT(un != NULL);
10716 	ASSERT(bp != NULL);
10717 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10718 
10719 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10720 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
10721 
10722 	if (bp->b_iodone == (int (*)(struct buf *)) sd_mapblockaddr_iodone) {
10723 		/*
10724 		 * We have an "overrun" buf to deal with...
10725 		 */
10726 		struct sd_xbuf	*xp;
10727 		struct buf	*obp;	/* ptr to the original buf */
10728 
10729 		xp = SD_GET_XBUF(bp);
10730 		ASSERT(xp != NULL);
10731 
10732 		/* Retrieve the pointer to the original buf */
10733 		obp = (struct buf *)xp->xb_private;
10734 		ASSERT(obp != NULL);
10735 
10736 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
10737 		bioerror(obp, bp->b_error);
10738 
10739 		sd_bioclone_free(bp);
10740 
10741 		/*
10742 		 * Get back the original buf.
10743 		 * Note that since the restoration of xb_blkno below
10744 		 * was removed, the sd_xbuf is not needed.
10745 		 */
10746 		bp = obp;
10747 		/*
10748 		 * xp = SD_GET_XBUF(bp);
10749 		 * ASSERT(xp != NULL);
10750 		 */
10751 	}
10752 
10753 	/*
10754 	 * Convert sd->xb_blkno back to a minor-device relative value.
10755 	 * Note: this has been commented out, as it is not needed in the
10756 	 * current implementation of the driver (ie, since this function
10757 	 * is at the top of the layering chains, so the info will be
10758 	 * discarded) and it is in the "hot" IO path.
10759 	 *
10760 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
10761 	 * xp->xb_blkno -= un->un_offset[partition];
10762 	 */
10763 
10764 	SD_NEXT_IODONE(index, un, bp);
10765 
10766 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10767 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
10768 }
10769 
10770 
10771 /*
10772  *    Function: sd_mapblocksize_iostart
10773  *
10774  * Description: Convert between system block size (un->un_sys_blocksize)
10775  *		and target block size (un->un_tgt_blocksize).
10776  *
10777  *     Context: Can sleep to allocate resources.
10778  *
10779  * Assumptions: A higher layer has already performed any partition validation,
10780  *		and converted the xp->xb_blkno to an absolute value relative
10781  *		to the start of the device.
10782  *
10783  *		It is also assumed that the higher layer has implemented
10784  *		an "overrun" mechanism for the case where the request would
10785  *		read/write beyond the end of a partition.  In this case we
10786  *		assume (and ASSERT) that bp->b_resid == 0.
10787  *
10788  *		Note: The implementation for this routine assumes the target
10789  *		block size remains constant between allocation and transport.
10790  */
10791 
10792 static void
10793 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
10794 {
10795 	struct sd_mapblocksize_info	*bsp;
10796 	struct sd_xbuf			*xp;
10797 	offset_t first_byte;
10798 	daddr_t	start_block, end_block;
10799 	daddr_t	request_bytes;
10800 	ushort_t is_aligned = FALSE;
10801 
10802 	ASSERT(un != NULL);
10803 	ASSERT(bp != NULL);
10804 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10805 	ASSERT(bp->b_resid == 0);
10806 
10807 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
10808 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
10809 
10810 	/*
10811 	 * For a non-writable CD, a write request is an error
10812 	 */
10813 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
10814 	    (un->un_f_mmc_writable_media == FALSE)) {
10815 		bioerror(bp, EIO);
10816 		bp->b_resid = bp->b_bcount;
10817 		SD_BEGIN_IODONE(index, un, bp);
10818 		return;
10819 	}
10820 
10821 	/*
10822 	 * We do not need a shadow buf if the device is using
10823 	 * un->un_sys_blocksize as its block size or if bcount == 0.
10824 	 * In this case there is no layer-private data block allocated.
10825 	 */
10826 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
10827 	    (bp->b_bcount == 0)) {
10828 		goto done;
10829 	}
10830 
10831 #if defined(__i386) || defined(__amd64)
10832 	/* We do not support non-block-aligned transfers for ROD devices */
10833 	ASSERT(!ISROD(un));
10834 #endif
10835 
10836 	xp = SD_GET_XBUF(bp);
10837 	ASSERT(xp != NULL);
10838 
10839 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
10840 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
10841 	    un->un_tgt_blocksize, un->un_sys_blocksize);
10842 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
10843 	    "request start block:0x%x\n", xp->xb_blkno);
10844 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
10845 	    "request len:0x%x\n", bp->b_bcount);
10846 
10847 	/*
10848 	 * Allocate the layer-private data area for the mapblocksize layer.
10849 	 * Layers are allowed to use the xp_private member of the sd_xbuf
10850 	 * struct to store the pointer to their layer-private data block, but
10851 	 * each layer also has the responsibility of restoring the prior
10852 	 * contents of xb_private before returning the buf/xbuf to the
10853 	 * higher layer that sent it.
10854 	 *
10855 	 * Here we save the prior contents of xp->xb_private into the
10856 	 * bsp->mbs_oprivate field of our layer-private data area. This value
10857 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
10858 	 * the layer-private area and returning the buf/xbuf to the layer
10859 	 * that sent it.
10860 	 *
10861 	 * Note that here we use kmem_zalloc for the allocation as there are
10862 	 * parts of the mapblocksize code that expect certain fields to be
10863 	 * zero unless explicitly set to a required value.
10864 	 */
10865 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
10866 	bsp->mbs_oprivate = xp->xb_private;
10867 	xp->xb_private = bsp;
10868 
10869 	/*
10870 	 * This treats the data on the disk (target) as an array of bytes.
10871 	 * first_byte is the byte offset, from the beginning of the device,
10872 	 * to the location of the request. This is converted from a
10873 	 * un->un_sys_blocksize block address to a byte offset, and then back
10874 	 * to a block address based upon a un->un_tgt_blocksize block size.
10875 	 *
10876 	 * xp->xb_blkno should be absolute upon entry into this function,
10877 	 * but, but it is based upon partitions that use the "system"
10878 	 * block size. It must be adjusted to reflect the block size of
10879 	 * the target.
10880 	 *
10881 	 * Note that end_block is actually the block that follows the last
10882 	 * block of the request, but that's what is needed for the computation.
10883 	 */
10884 	first_byte  = SD_SYSBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
10885 	start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
10886 	end_block   = (first_byte + bp->b_bcount + un->un_tgt_blocksize - 1) /
10887 	    un->un_tgt_blocksize;
10888 
10889 	/* request_bytes is rounded up to a multiple of the target block size */
10890 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
10891 
10892 	/*
10893 	 * See if the starting address of the request and the request
10894 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
10895 	 * then we do not need to allocate a shadow buf to handle the request.
10896 	 */
10897 	if (((first_byte   % un->un_tgt_blocksize) == 0) &&
10898 	    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
10899 		is_aligned = TRUE;
10900 	}
10901 
10902 	if ((bp->b_flags & B_READ) == 0) {
10903 		/*
10904 		 * Lock the range for a write operation. An aligned request is
10905 		 * considered a simple write; otherwise the request must be a
10906 		 * read-modify-write.
10907 		 */
10908 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
10909 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
10910 	}
10911 
10912 	/*
10913 	 * Alloc a shadow buf if the request is not aligned. Also, this is
10914 	 * where the READ command is generated for a read-modify-write. (The
10915 	 * write phase is deferred until after the read completes.)
10916 	 */
10917 	if (is_aligned == FALSE) {
10918 
10919 		struct sd_mapblocksize_info	*shadow_bsp;
10920 		struct sd_xbuf	*shadow_xp;
10921 		struct buf	*shadow_bp;
10922 
10923 		/*
10924 		 * Allocate the shadow buf and it associated xbuf. Note that
10925 		 * after this call the xb_blkno value in both the original
10926 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
10927 		 * same: absolute relative to the start of the device, and
10928 		 * adjusted for the target block size. The b_blkno in the
10929 		 * shadow buf will also be set to this value. We should never
10930 		 * change b_blkno in the original bp however.
10931 		 *
10932 		 * Note also that the shadow buf will always need to be a
10933 		 * READ command, regardless of whether the incoming command
10934 		 * is a READ or a WRITE.
10935 		 */
10936 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
10937 		    xp->xb_blkno,
10938 		    (int (*)(struct buf *)) sd_mapblocksize_iodone);
10939 
10940 		shadow_xp = SD_GET_XBUF(shadow_bp);
10941 
10942 		/*
10943 		 * Allocate the layer-private data for the shadow buf.
10944 		 * (No need to preserve xb_private in the shadow xbuf.)
10945 		 */
10946 		shadow_xp->xb_private = shadow_bsp =
10947 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
10948 
10949 		/*
10950 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
10951 		 * to figure out where the start of the user data is (based upon
10952 		 * the system block size) in the data returned by the READ
10953 		 * command (which will be based upon the target blocksize). Note
10954 		 * that this is only really used if the request is unaligned.
10955 		 */
10956 		bsp->mbs_copy_offset = (ssize_t)(first_byte -
10957 		    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
10958 		ASSERT((bsp->mbs_copy_offset >= 0) &&
10959 		    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
10960 
10961 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
10962 
10963 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
10964 
10965 		/* Transfer the wmap (if any) to the shadow buf */
10966 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
10967 		bsp->mbs_wmp = NULL;
10968 
10969 		/*
10970 		 * The shadow buf goes on from here in place of the
10971 		 * original buf.
10972 		 */
10973 		shadow_bsp->mbs_orig_bp = bp;
10974 		bp = shadow_bp;
10975 	}
10976 
10977 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
10978 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
10979 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
10980 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
10981 	    request_bytes);
10982 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
10983 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
10984 
10985 done:
10986 	SD_NEXT_IOSTART(index, un, bp);
10987 
10988 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
10989 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
10990 }
10991 
10992 
10993 /*
10994  *    Function: sd_mapblocksize_iodone
10995  *
10996  * Description: Completion side processing for block-size mapping.
10997  *
10998  *     Context: May be called under interrupt context
10999  */
11000 
11001 static void
11002 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
11003 {
11004 	struct sd_mapblocksize_info	*bsp;
11005 	struct sd_xbuf	*xp;
11006 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
11007 	struct buf	*orig_bp;	/* ptr to the original buf */
11008 	offset_t	shadow_end;
11009 	offset_t	request_end;
11010 	offset_t	shadow_start;
11011 	ssize_t		copy_offset;
11012 	size_t		copy_length;
11013 	size_t		shortfall;
11014 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
11015 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
11016 
11017 	ASSERT(un != NULL);
11018 	ASSERT(bp != NULL);
11019 
11020 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11021 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
11022 
11023 	/*
11024 	 * There is no shadow buf or layer-private data if the target is
11025 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
11026 	 */
11027 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
11028 	    (bp->b_bcount == 0)) {
11029 		goto exit;
11030 	}
11031 
11032 	xp = SD_GET_XBUF(bp);
11033 	ASSERT(xp != NULL);
11034 
11035 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
11036 	bsp = xp->xb_private;
11037 
11038 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
11039 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
11040 
11041 	if (is_write) {
11042 		/*
11043 		 * For a WRITE request we must free up the block range that
11044 		 * we have locked up.  This holds regardless of whether this is
11045 		 * an aligned write request or a read-modify-write request.
11046 		 */
11047 		sd_range_unlock(un, bsp->mbs_wmp);
11048 		bsp->mbs_wmp = NULL;
11049 	}
11050 
11051 	if ((bp->b_iodone != (int(*)(struct buf *))sd_mapblocksize_iodone)) {
11052 		/*
11053 		 * An aligned read or write command will have no shadow buf;
11054 		 * there is not much else to do with it.
11055 		 */
11056 		goto done;
11057 	}
11058 
11059 	orig_bp = bsp->mbs_orig_bp;
11060 	ASSERT(orig_bp != NULL);
11061 	orig_xp = SD_GET_XBUF(orig_bp);
11062 	ASSERT(orig_xp != NULL);
11063 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11064 
11065 	if (!is_write && has_wmap) {
11066 		/*
11067 		 * A READ with a wmap means this is the READ phase of a
11068 		 * read-modify-write. If an error occurred on the READ then
11069 		 * we do not proceed with the WRITE phase or copy any data.
11070 		 * Just release the write maps and return with an error.
11071 		 */
11072 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
11073 			orig_bp->b_resid = orig_bp->b_bcount;
11074 			bioerror(orig_bp, bp->b_error);
11075 			sd_range_unlock(un, bsp->mbs_wmp);
11076 			goto freebuf_done;
11077 		}
11078 	}
11079 
11080 	/*
11081 	 * Here is where we set up to copy the data from the shadow buf
11082 	 * into the space associated with the original buf.
11083 	 *
11084 	 * To deal with the conversion between block sizes, these
11085 	 * computations treat the data as an array of bytes, with the
11086 	 * first byte (byte 0) corresponding to the first byte in the
11087 	 * first block on the disk.
11088 	 */
11089 
11090 	/*
11091 	 * shadow_start and shadow_len indicate the location and size of
11092 	 * the data returned with the shadow IO request.
11093 	 */
11094 	shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
11095 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
11096 
11097 	/*
11098 	 * copy_offset gives the offset (in bytes) from the start of the first
11099 	 * block of the READ request to the beginning of the data.  We retrieve
11100 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
11101 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
11102 	 * data to be copied (in bytes).
11103 	 */
11104 	copy_offset  = bsp->mbs_copy_offset;
11105 	ASSERT((copy_offset >= 0) && (copy_offset < un->un_tgt_blocksize));
11106 	copy_length  = orig_bp->b_bcount;
11107 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
11108 
11109 	/*
11110 	 * Set up the resid and error fields of orig_bp as appropriate.
11111 	 */
11112 	if (shadow_end >= request_end) {
11113 		/* We got all the requested data; set resid to zero */
11114 		orig_bp->b_resid = 0;
11115 	} else {
11116 		/*
11117 		 * We failed to get enough data to fully satisfy the original
11118 		 * request. Just copy back whatever data we got and set
11119 		 * up the residual and error code as required.
11120 		 *
11121 		 * 'shortfall' is the amount by which the data received with the
11122 		 * shadow buf has "fallen short" of the requested amount.
11123 		 */
11124 		shortfall = (size_t)(request_end - shadow_end);
11125 
11126 		if (shortfall > orig_bp->b_bcount) {
11127 			/*
11128 			 * We did not get enough data to even partially
11129 			 * fulfill the original request.  The residual is
11130 			 * equal to the amount requested.
11131 			 */
11132 			orig_bp->b_resid = orig_bp->b_bcount;
11133 		} else {
11134 			/*
11135 			 * We did not get all the data that we requested
11136 			 * from the device, but we will try to return what
11137 			 * portion we did get.
11138 			 */
11139 			orig_bp->b_resid = shortfall;
11140 		}
11141 		ASSERT(copy_length >= orig_bp->b_resid);
11142 		copy_length  -= orig_bp->b_resid;
11143 	}
11144 
11145 	/* Propagate the error code from the shadow buf to the original buf */
11146 	bioerror(orig_bp, bp->b_error);
11147 
11148 	if (is_write) {
11149 		goto freebuf_done;	/* No data copying for a WRITE */
11150 	}
11151 
11152 	if (has_wmap) {
11153 		/*
11154 		 * This is a READ command from the READ phase of a
11155 		 * read-modify-write request. We have to copy the data given
11156 		 * by the user OVER the data returned by the READ command,
11157 		 * then convert the command from a READ to a WRITE and send
11158 		 * it back to the target.
11159 		 */
11160 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
11161 		    copy_length);
11162 
11163 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
11164 
11165 		/*
11166 		 * Dispatch the WRITE command to the taskq thread, which
11167 		 * will in turn send the command to the target. When the
11168 		 * WRITE command completes, we (sd_mapblocksize_iodone())
11169 		 * will get called again as part of the iodone chain
11170 		 * processing for it. Note that we will still be dealing
11171 		 * with the shadow buf at that point.
11172 		 */
11173 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
11174 		    KM_NOSLEEP) != 0) {
11175 			/*
11176 			 * Dispatch was successful so we are done. Return
11177 			 * without going any higher up the iodone chain. Do
11178 			 * not free up any layer-private data until after the
11179 			 * WRITE completes.
11180 			 */
11181 			return;
11182 		}
11183 
11184 		/*
11185 		 * Dispatch of the WRITE command failed; set up the error
11186 		 * condition and send this IO back up the iodone chain.
11187 		 */
11188 		bioerror(orig_bp, EIO);
11189 		orig_bp->b_resid = orig_bp->b_bcount;
11190 
11191 	} else {
11192 		/*
11193 		 * This is a regular READ request (ie, not a RMW). Copy the
11194 		 * data from the shadow buf into the original buf. The
11195 		 * copy_offset compensates for any "misalignment" between the
11196 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
11197 		 * original buf (with its un->un_sys_blocksize blocks).
11198 		 */
11199 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
11200 		    copy_length);
11201 	}
11202 
11203 freebuf_done:
11204 
11205 	/*
11206 	 * At this point we still have both the shadow buf AND the original
11207 	 * buf to deal with, as well as the layer-private data area in each.
11208 	 * Local variables are as follows:
11209 	 *
11210 	 * bp -- points to shadow buf
11211 	 * xp -- points to xbuf of shadow buf
11212 	 * bsp -- points to layer-private data area of shadow buf
11213 	 * orig_bp -- points to original buf
11214 	 *
11215 	 * First free the shadow buf and its associated xbuf, then free the
11216 	 * layer-private data area from the shadow buf. There is no need to
11217 	 * restore xb_private in the shadow xbuf.
11218 	 */
11219 	sd_shadow_buf_free(bp);
11220 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11221 
11222 	/*
11223 	 * Now update the local variables to point to the original buf, xbuf,
11224 	 * and layer-private area.
11225 	 */
11226 	bp = orig_bp;
11227 	xp = SD_GET_XBUF(bp);
11228 	ASSERT(xp != NULL);
11229 	ASSERT(xp == orig_xp);
11230 	bsp = xp->xb_private;
11231 	ASSERT(bsp != NULL);
11232 
11233 done:
11234 	/*
11235 	 * Restore xb_private to whatever it was set to by the next higher
11236 	 * layer in the chain, then free the layer-private data area.
11237 	 */
11238 	xp->xb_private = bsp->mbs_oprivate;
11239 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11240 
11241 exit:
11242 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
11243 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
11244 
11245 	SD_NEXT_IODONE(index, un, bp);
11246 }
11247 
11248 
11249 /*
11250  *    Function: sd_checksum_iostart
11251  *
11252  * Description: A stub function for a layer that's currently not used.
11253  *		For now just a placeholder.
11254  *
11255  *     Context: Kernel thread context
11256  */
11257 
11258 static void
11259 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
11260 {
11261 	ASSERT(un != NULL);
11262 	ASSERT(bp != NULL);
11263 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11264 	SD_NEXT_IOSTART(index, un, bp);
11265 }
11266 
11267 
11268 /*
11269  *    Function: sd_checksum_iodone
11270  *
11271  * Description: A stub function for a layer that's currently not used.
11272  *		For now just a placeholder.
11273  *
11274  *     Context: May be called under interrupt context
11275  */
11276 
11277 static void
11278 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
11279 {
11280 	ASSERT(un != NULL);
11281 	ASSERT(bp != NULL);
11282 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11283 	SD_NEXT_IODONE(index, un, bp);
11284 }
11285 
11286 
11287 /*
11288  *    Function: sd_checksum_uscsi_iostart
11289  *
11290  * Description: A stub function for a layer that's currently not used.
11291  *		For now just a placeholder.
11292  *
11293  *     Context: Kernel thread context
11294  */
11295 
11296 static void
11297 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
11298 {
11299 	ASSERT(un != NULL);
11300 	ASSERT(bp != NULL);
11301 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11302 	SD_NEXT_IOSTART(index, un, bp);
11303 }
11304 
11305 
11306 /*
11307  *    Function: sd_checksum_uscsi_iodone
11308  *
11309  * Description: A stub function for a layer that's currently not used.
11310  *		For now just a placeholder.
11311  *
11312  *     Context: May be called under interrupt context
11313  */
11314 
11315 static void
11316 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
11317 {
11318 	ASSERT(un != NULL);
11319 	ASSERT(bp != NULL);
11320 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11321 	SD_NEXT_IODONE(index, un, bp);
11322 }
11323 
11324 
11325 /*
11326  *    Function: sd_pm_iostart
11327  *
11328  * Description: iostart-side routine for Power mangement.
11329  *
11330  *     Context: Kernel thread context
11331  */
11332 
11333 static void
11334 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
11335 {
11336 	ASSERT(un != NULL);
11337 	ASSERT(bp != NULL);
11338 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11339 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11340 
11341 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
11342 
11343 	if (sd_pm_entry(un) != DDI_SUCCESS) {
11344 		/*
11345 		 * Set up to return the failed buf back up the 'iodone'
11346 		 * side of the calling chain.
11347 		 */
11348 		bioerror(bp, EIO);
11349 		bp->b_resid = bp->b_bcount;
11350 
11351 		SD_BEGIN_IODONE(index, un, bp);
11352 
11353 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11354 		return;
11355 	}
11356 
11357 	SD_NEXT_IOSTART(index, un, bp);
11358 
11359 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11360 }
11361 
11362 
11363 /*
11364  *    Function: sd_pm_iodone
11365  *
11366  * Description: iodone-side routine for power mangement.
11367  *
11368  *     Context: may be called from interrupt context
11369  */
11370 
11371 static void
11372 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
11373 {
11374 	ASSERT(un != NULL);
11375 	ASSERT(bp != NULL);
11376 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11377 
11378 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
11379 
11380 	/*
11381 	 * After attach the following flag is only read, so don't
11382 	 * take the penalty of acquiring a mutex for it.
11383 	 */
11384 	if (un->un_f_pm_is_enabled == TRUE) {
11385 		sd_pm_exit(un);
11386 	}
11387 
11388 	SD_NEXT_IODONE(index, un, bp);
11389 
11390 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
11391 }
11392 
11393 
11394 /*
11395  *    Function: sd_core_iostart
11396  *
11397  * Description: Primary driver function for enqueuing buf(9S) structs from
11398  *		the system and initiating IO to the target device
11399  *
11400  *     Context: Kernel thread context. Can sleep.
11401  *
11402  * Assumptions:  - The given xp->xb_blkno is absolute
11403  *		   (ie, relative to the start of the device).
11404  *		 - The IO is to be done using the native blocksize of
11405  *		   the device, as specified in un->un_tgt_blocksize.
11406  */
11407 /* ARGSUSED */
11408 static void
11409 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
11410 {
11411 	struct sd_xbuf *xp;
11412 
11413 	ASSERT(un != NULL);
11414 	ASSERT(bp != NULL);
11415 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11416 	ASSERT(bp->b_resid == 0);
11417 
11418 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
11419 
11420 	xp = SD_GET_XBUF(bp);
11421 	ASSERT(xp != NULL);
11422 
11423 	mutex_enter(SD_MUTEX(un));
11424 
11425 	/*
11426 	 * If we are currently in the failfast state, fail any new IO
11427 	 * that has B_FAILFAST set, then return.
11428 	 */
11429 	if ((bp->b_flags & B_FAILFAST) &&
11430 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
11431 		mutex_exit(SD_MUTEX(un));
11432 		bioerror(bp, EIO);
11433 		bp->b_resid = bp->b_bcount;
11434 		SD_BEGIN_IODONE(index, un, bp);
11435 		return;
11436 	}
11437 
11438 	if (SD_IS_DIRECT_PRIORITY(xp)) {
11439 		/*
11440 		 * Priority command -- transport it immediately.
11441 		 *
11442 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
11443 		 * because all direct priority commands should be associated
11444 		 * with error recovery actions which we don't want to retry.
11445 		 */
11446 		sd_start_cmds(un, bp);
11447 	} else {
11448 		/*
11449 		 * Normal command -- add it to the wait queue, then start
11450 		 * transporting commands from the wait queue.
11451 		 */
11452 		sd_add_buf_to_waitq(un, bp);
11453 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
11454 		sd_start_cmds(un, NULL);
11455 	}
11456 
11457 	mutex_exit(SD_MUTEX(un));
11458 
11459 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
11460 }
11461 
11462 
11463 /*
11464  *    Function: sd_init_cdb_limits
11465  *
11466  * Description: This is to handle scsi_pkt initialization differences
11467  *		between the driver platforms.
11468  *
11469  *		Legacy behaviors:
11470  *
11471  *		If the block number or the sector count exceeds the
11472  *		capabilities of a Group 0 command, shift over to a
11473  *		Group 1 command. We don't blindly use Group 1
11474  *		commands because a) some drives (CDC Wren IVs) get a
11475  *		bit confused, and b) there is probably a fair amount
11476  *		of speed difference for a target to receive and decode
11477  *		a 10 byte command instead of a 6 byte command.
11478  *
11479  *		The xfer time difference of 6 vs 10 byte CDBs is
11480  *		still significant so this code is still worthwhile.
11481  *		10 byte CDBs are very inefficient with the fas HBA driver
11482  *		and older disks. Each CDB byte took 1 usec with some
11483  *		popular disks.
11484  *
11485  *     Context: Must be called at attach time
11486  */
11487 
11488 static void
11489 sd_init_cdb_limits(struct sd_lun *un)
11490 {
11491 	int hba_cdb_limit;
11492 
11493 	/*
11494 	 * Use CDB_GROUP1 commands for most devices except for
11495 	 * parallel SCSI fixed drives in which case we get better
11496 	 * performance using CDB_GROUP0 commands (where applicable).
11497 	 */
11498 	un->un_mincdb = SD_CDB_GROUP1;
11499 #if !defined(__fibre)
11500 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
11501 	    !un->un_f_has_removable_media) {
11502 		un->un_mincdb = SD_CDB_GROUP0;
11503 	}
11504 #endif
11505 
11506 	/*
11507 	 * Try to read the max-cdb-length supported by HBA.
11508 	 */
11509 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
11510 	if (0 >= un->un_max_hba_cdb) {
11511 		un->un_max_hba_cdb = CDB_GROUP4;
11512 		hba_cdb_limit = SD_CDB_GROUP4;
11513 	} else if (0 < un->un_max_hba_cdb &&
11514 	    un->un_max_hba_cdb < CDB_GROUP1) {
11515 		hba_cdb_limit = SD_CDB_GROUP0;
11516 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
11517 	    un->un_max_hba_cdb < CDB_GROUP5) {
11518 		hba_cdb_limit = SD_CDB_GROUP1;
11519 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
11520 	    un->un_max_hba_cdb < CDB_GROUP4) {
11521 		hba_cdb_limit = SD_CDB_GROUP5;
11522 	} else {
11523 		hba_cdb_limit = SD_CDB_GROUP4;
11524 	}
11525 
11526 	/*
11527 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
11528 	 * commands for fixed disks unless we are building for a 32 bit
11529 	 * kernel.
11530 	 */
11531 #ifdef _LP64
11532 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11533 	    min(hba_cdb_limit, SD_CDB_GROUP4);
11534 #else
11535 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11536 	    min(hba_cdb_limit, SD_CDB_GROUP1);
11537 #endif
11538 
11539 	/*
11540 	 * x86 systems require the PKT_DMA_PARTIAL flag
11541 	 */
11542 #if defined(__x86)
11543 	un->un_pkt_flags = PKT_DMA_PARTIAL;
11544 #else
11545 	un->un_pkt_flags = 0;
11546 #endif
11547 
11548 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
11549 	    ? sizeof (struct scsi_arq_status) : 1);
11550 	un->un_cmd_timeout = (ushort_t)sd_io_time;
11551 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
11552 }
11553 
11554 
11555 /*
11556  *    Function: sd_initpkt_for_buf
11557  *
11558  * Description: Allocate and initialize for transport a scsi_pkt struct,
11559  *		based upon the info specified in the given buf struct.
11560  *
11561  *		Assumes the xb_blkno in the request is absolute (ie,
11562  *		relative to the start of the device (NOT partition!).
11563  *		Also assumes that the request is using the native block
11564  *		size of the device (as returned by the READ CAPACITY
11565  *		command).
11566  *
11567  * Return Code: SD_PKT_ALLOC_SUCCESS
11568  *		SD_PKT_ALLOC_FAILURE
11569  *		SD_PKT_ALLOC_FAILURE_NO_DMA
11570  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11571  *
11572  *     Context: Kernel thread and may be called from software interrupt context
11573  *		as part of a sdrunout callback. This function may not block or
11574  *		call routines that block
11575  */
11576 
11577 static int
11578 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
11579 {
11580 	struct sd_xbuf	*xp;
11581 	struct scsi_pkt *pktp = NULL;
11582 	struct sd_lun	*un;
11583 	size_t		blockcount;
11584 	daddr_t		startblock;
11585 	int		rval;
11586 	int		cmd_flags;
11587 
11588 	ASSERT(bp != NULL);
11589 	ASSERT(pktpp != NULL);
11590 	xp = SD_GET_XBUF(bp);
11591 	ASSERT(xp != NULL);
11592 	un = SD_GET_UN(bp);
11593 	ASSERT(un != NULL);
11594 	ASSERT(mutex_owned(SD_MUTEX(un)));
11595 	ASSERT(bp->b_resid == 0);
11596 
11597 	SD_TRACE(SD_LOG_IO_CORE, un,
11598 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
11599 
11600 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11601 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
11602 		/*
11603 		 * Already have a scsi_pkt -- just need DMA resources.
11604 		 * We must recompute the CDB in case the mapping returns
11605 		 * a nonzero pkt_resid.
11606 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
11607 		 * that is being retried, the unmap/remap of the DMA resouces
11608 		 * will result in the entire transfer starting over again
11609 		 * from the very first block.
11610 		 */
11611 		ASSERT(xp->xb_pktp != NULL);
11612 		pktp = xp->xb_pktp;
11613 	} else {
11614 		pktp = NULL;
11615 	}
11616 #endif /* __i386 || __amd64 */
11617 
11618 	startblock = xp->xb_blkno;	/* Absolute block num. */
11619 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
11620 
11621 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11622 
11623 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
11624 
11625 #else
11626 
11627 	cmd_flags = un->un_pkt_flags | xp->xb_pkt_flags;
11628 
11629 #endif
11630 
11631 	/*
11632 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
11633 	 * call scsi_init_pkt, and build the CDB.
11634 	 */
11635 	rval = sd_setup_rw_pkt(un, &pktp, bp,
11636 	    cmd_flags, sdrunout, (caddr_t)un,
11637 	    startblock, blockcount);
11638 
11639 	if (rval == 0) {
11640 		/*
11641 		 * Success.
11642 		 *
11643 		 * If partial DMA is being used and required for this transfer.
11644 		 * set it up here.
11645 		 */
11646 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
11647 		    (pktp->pkt_resid != 0)) {
11648 
11649 			/*
11650 			 * Save the CDB length and pkt_resid for the
11651 			 * next xfer
11652 			 */
11653 			xp->xb_dma_resid = pktp->pkt_resid;
11654 
11655 			/* rezero resid */
11656 			pktp->pkt_resid = 0;
11657 
11658 		} else {
11659 			xp->xb_dma_resid = 0;
11660 		}
11661 
11662 		pktp->pkt_flags = un->un_tagflags;
11663 		pktp->pkt_time  = un->un_cmd_timeout;
11664 		pktp->pkt_comp  = sdintr;
11665 
11666 		pktp->pkt_private = bp;
11667 		*pktpp = pktp;
11668 
11669 		SD_TRACE(SD_LOG_IO_CORE, un,
11670 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
11671 
11672 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11673 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
11674 #endif
11675 
11676 		return (SD_PKT_ALLOC_SUCCESS);
11677 
11678 	}
11679 
11680 	/*
11681 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
11682 	 * from sd_setup_rw_pkt.
11683 	 */
11684 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
11685 
11686 	if (rval == SD_PKT_ALLOC_FAILURE) {
11687 		*pktpp = NULL;
11688 		/*
11689 		 * Set the driver state to RWAIT to indicate the driver
11690 		 * is waiting on resource allocations. The driver will not
11691 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
11692 		 */
11693 		New_state(un, SD_STATE_RWAIT);
11694 
11695 		SD_ERROR(SD_LOG_IO_CORE, un,
11696 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
11697 
11698 		if ((bp->b_flags & B_ERROR) != 0) {
11699 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
11700 		}
11701 		return (SD_PKT_ALLOC_FAILURE);
11702 	} else {
11703 		/*
11704 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11705 		 *
11706 		 * This should never happen.  Maybe someone messed with the
11707 		 * kernel's minphys?
11708 		 */
11709 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
11710 		    "Request rejected: too large for CDB: "
11711 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
11712 		SD_ERROR(SD_LOG_IO_CORE, un,
11713 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
11714 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
11715 
11716 	}
11717 }
11718 
11719 
11720 /*
11721  *    Function: sd_destroypkt_for_buf
11722  *
11723  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
11724  *
11725  *     Context: Kernel thread or interrupt context
11726  */
11727 
11728 static void
11729 sd_destroypkt_for_buf(struct buf *bp)
11730 {
11731 	ASSERT(bp != NULL);
11732 	ASSERT(SD_GET_UN(bp) != NULL);
11733 
11734 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11735 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
11736 
11737 	ASSERT(SD_GET_PKTP(bp) != NULL);
11738 	scsi_destroy_pkt(SD_GET_PKTP(bp));
11739 
11740 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11741 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
11742 }
11743 
11744 /*
11745  *    Function: sd_setup_rw_pkt
11746  *
11747  * Description: Determines appropriate CDB group for the requested LBA
11748  *		and transfer length, calls scsi_init_pkt, and builds
11749  *		the CDB.  Do not use for partial DMA transfers except
11750  *		for the initial transfer since the CDB size must
11751  *		remain constant.
11752  *
11753  *     Context: Kernel thread and may be called from software interrupt
11754  *		context as part of a sdrunout callback. This function may not
11755  *		block or call routines that block
11756  */
11757 
11758 
11759 int
11760 sd_setup_rw_pkt(struct sd_lun *un,
11761     struct scsi_pkt **pktpp, struct buf *bp, int flags,
11762     int (*callback)(caddr_t), caddr_t callback_arg,
11763     diskaddr_t lba, uint32_t blockcount)
11764 {
11765 	struct scsi_pkt *return_pktp;
11766 	union scsi_cdb *cdbp;
11767 	struct sd_cdbinfo *cp = NULL;
11768 	int i;
11769 
11770 	/*
11771 	 * See which size CDB to use, based upon the request.
11772 	 */
11773 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
11774 
11775 		/*
11776 		 * Check lba and block count against sd_cdbtab limits.
11777 		 * In the partial DMA case, we have to use the same size
11778 		 * CDB for all the transfers.  Check lba + blockcount
11779 		 * against the max LBA so we know that segment of the
11780 		 * transfer can use the CDB we select.
11781 		 */
11782 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
11783 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
11784 
11785 			/*
11786 			 * The command will fit into the CDB type
11787 			 * specified by sd_cdbtab[i].
11788 			 */
11789 			cp = sd_cdbtab + i;
11790 
11791 			/*
11792 			 * Call scsi_init_pkt so we can fill in the
11793 			 * CDB.
11794 			 */
11795 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
11796 			    bp, cp->sc_grpcode, un->un_status_len, 0,
11797 			    flags, callback, callback_arg);
11798 
11799 			if (return_pktp != NULL) {
11800 
11801 				/*
11802 				 * Return new value of pkt
11803 				 */
11804 				*pktpp = return_pktp;
11805 
11806 				/*
11807 				 * To be safe, zero the CDB insuring there is
11808 				 * no leftover data from a previous command.
11809 				 */
11810 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
11811 
11812 				/*
11813 				 * Handle partial DMA mapping
11814 				 */
11815 				if (return_pktp->pkt_resid != 0) {
11816 
11817 					/*
11818 					 * Not going to xfer as many blocks as
11819 					 * originally expected
11820 					 */
11821 					blockcount -=
11822 					    SD_BYTES2TGTBLOCKS(un,
11823 					    return_pktp->pkt_resid);
11824 				}
11825 
11826 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
11827 
11828 				/*
11829 				 * Set command byte based on the CDB
11830 				 * type we matched.
11831 				 */
11832 				cdbp->scc_cmd = cp->sc_grpmask |
11833 				    ((bp->b_flags & B_READ) ?
11834 				    SCMD_READ : SCMD_WRITE);
11835 
11836 				SD_FILL_SCSI1_LUN(un, return_pktp);
11837 
11838 				/*
11839 				 * Fill in LBA and length
11840 				 */
11841 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
11842 				    (cp->sc_grpcode == CDB_GROUP4) ||
11843 				    (cp->sc_grpcode == CDB_GROUP0) ||
11844 				    (cp->sc_grpcode == CDB_GROUP5));
11845 
11846 				if (cp->sc_grpcode == CDB_GROUP1) {
11847 					FORMG1ADDR(cdbp, lba);
11848 					FORMG1COUNT(cdbp, blockcount);
11849 					return (0);
11850 				} else if (cp->sc_grpcode == CDB_GROUP4) {
11851 					FORMG4LONGADDR(cdbp, lba);
11852 					FORMG4COUNT(cdbp, blockcount);
11853 					return (0);
11854 				} else if (cp->sc_grpcode == CDB_GROUP0) {
11855 					FORMG0ADDR(cdbp, lba);
11856 					FORMG0COUNT(cdbp, blockcount);
11857 					return (0);
11858 				} else if (cp->sc_grpcode == CDB_GROUP5) {
11859 					FORMG5ADDR(cdbp, lba);
11860 					FORMG5COUNT(cdbp, blockcount);
11861 					return (0);
11862 				}
11863 
11864 				/*
11865 				 * It should be impossible to not match one
11866 				 * of the CDB types above, so we should never
11867 				 * reach this point.  Set the CDB command byte
11868 				 * to test-unit-ready to avoid writing
11869 				 * to somewhere we don't intend.
11870 				 */
11871 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
11872 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
11873 			} else {
11874 				/*
11875 				 * Couldn't get scsi_pkt
11876 				 */
11877 				return (SD_PKT_ALLOC_FAILURE);
11878 			}
11879 		}
11880 	}
11881 
11882 	/*
11883 	 * None of the available CDB types were suitable.  This really
11884 	 * should never happen:  on a 64 bit system we support
11885 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
11886 	 * and on a 32 bit system we will refuse to bind to a device
11887 	 * larger than 2TB so addresses will never be larger than 32 bits.
11888 	 */
11889 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
11890 }
11891 
11892 #if defined(__i386) || defined(__amd64)
11893 /*
11894  *    Function: sd_setup_next_rw_pkt
11895  *
11896  * Description: Setup packet for partial DMA transfers, except for the
11897  * 		initial transfer.  sd_setup_rw_pkt should be used for
11898  *		the initial transfer.
11899  *
11900  *     Context: Kernel thread and may be called from interrupt context.
11901  */
11902 
11903 int
11904 sd_setup_next_rw_pkt(struct sd_lun *un,
11905     struct scsi_pkt *pktp, struct buf *bp,
11906     diskaddr_t lba, uint32_t blockcount)
11907 {
11908 	uchar_t com;
11909 	union scsi_cdb *cdbp;
11910 	uchar_t cdb_group_id;
11911 
11912 	ASSERT(pktp != NULL);
11913 	ASSERT(pktp->pkt_cdbp != NULL);
11914 
11915 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
11916 	com = cdbp->scc_cmd;
11917 	cdb_group_id = CDB_GROUPID(com);
11918 
11919 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
11920 	    (cdb_group_id == CDB_GROUPID_1) ||
11921 	    (cdb_group_id == CDB_GROUPID_4) ||
11922 	    (cdb_group_id == CDB_GROUPID_5));
11923 
11924 	/*
11925 	 * Move pkt to the next portion of the xfer.
11926 	 * func is NULL_FUNC so we do not have to release
11927 	 * the disk mutex here.
11928 	 */
11929 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
11930 	    NULL_FUNC, NULL) == pktp) {
11931 		/* Success.  Handle partial DMA */
11932 		if (pktp->pkt_resid != 0) {
11933 			blockcount -=
11934 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
11935 		}
11936 
11937 		cdbp->scc_cmd = com;
11938 		SD_FILL_SCSI1_LUN(un, pktp);
11939 		if (cdb_group_id == CDB_GROUPID_1) {
11940 			FORMG1ADDR(cdbp, lba);
11941 			FORMG1COUNT(cdbp, blockcount);
11942 			return (0);
11943 		} else if (cdb_group_id == CDB_GROUPID_4) {
11944 			FORMG4LONGADDR(cdbp, lba);
11945 			FORMG4COUNT(cdbp, blockcount);
11946 			return (0);
11947 		} else if (cdb_group_id == CDB_GROUPID_0) {
11948 			FORMG0ADDR(cdbp, lba);
11949 			FORMG0COUNT(cdbp, blockcount);
11950 			return (0);
11951 		} else if (cdb_group_id == CDB_GROUPID_5) {
11952 			FORMG5ADDR(cdbp, lba);
11953 			FORMG5COUNT(cdbp, blockcount);
11954 			return (0);
11955 		}
11956 
11957 		/* Unreachable */
11958 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
11959 	}
11960 
11961 	/*
11962 	 * Error setting up next portion of cmd transfer.
11963 	 * Something is definitely very wrong and this
11964 	 * should not happen.
11965 	 */
11966 	return (SD_PKT_ALLOC_FAILURE);
11967 }
11968 #endif /* defined(__i386) || defined(__amd64) */
11969 
11970 /*
11971  *    Function: sd_initpkt_for_uscsi
11972  *
11973  * Description: Allocate and initialize for transport a scsi_pkt struct,
11974  *		based upon the info specified in the given uscsi_cmd struct.
11975  *
11976  * Return Code: SD_PKT_ALLOC_SUCCESS
11977  *		SD_PKT_ALLOC_FAILURE
11978  *		SD_PKT_ALLOC_FAILURE_NO_DMA
11979  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11980  *
11981  *     Context: Kernel thread and may be called from software interrupt context
11982  *		as part of a sdrunout callback. This function may not block or
11983  *		call routines that block
11984  */
11985 
11986 static int
11987 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
11988 {
11989 	struct uscsi_cmd *uscmd;
11990 	struct sd_xbuf	*xp;
11991 	struct scsi_pkt	*pktp;
11992 	struct sd_lun	*un;
11993 	uint32_t	flags = 0;
11994 
11995 	ASSERT(bp != NULL);
11996 	ASSERT(pktpp != NULL);
11997 	xp = SD_GET_XBUF(bp);
11998 	ASSERT(xp != NULL);
11999 	un = SD_GET_UN(bp);
12000 	ASSERT(un != NULL);
12001 	ASSERT(mutex_owned(SD_MUTEX(un)));
12002 
12003 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12004 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12005 	ASSERT(uscmd != NULL);
12006 
12007 	SD_TRACE(SD_LOG_IO_CORE, un,
12008 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
12009 
12010 	/*
12011 	 * Allocate the scsi_pkt for the command.
12012 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
12013 	 *	 during scsi_init_pkt time and will continue to use the
12014 	 *	 same path as long as the same scsi_pkt is used without
12015 	 *	 intervening scsi_dma_free(). Since uscsi command does
12016 	 *	 not call scsi_dmafree() before retry failed command, it
12017 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
12018 	 *	 set such that scsi_vhci can use other available path for
12019 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
12020 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
12021 	 */
12022 	pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
12023 	    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
12024 	    sizeof (struct scsi_arq_status), 0,
12025 	    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
12026 	    sdrunout, (caddr_t)un);
12027 
12028 	if (pktp == NULL) {
12029 		*pktpp = NULL;
12030 		/*
12031 		 * Set the driver state to RWAIT to indicate the driver
12032 		 * is waiting on resource allocations. The driver will not
12033 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
12034 		 */
12035 		New_state(un, SD_STATE_RWAIT);
12036 
12037 		SD_ERROR(SD_LOG_IO_CORE, un,
12038 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
12039 
12040 		if ((bp->b_flags & B_ERROR) != 0) {
12041 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
12042 		}
12043 		return (SD_PKT_ALLOC_FAILURE);
12044 	}
12045 
12046 	/*
12047 	 * We do not do DMA breakup for USCSI commands, so return failure
12048 	 * here if all the needed DMA resources were not allocated.
12049 	 */
12050 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
12051 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
12052 		scsi_destroy_pkt(pktp);
12053 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
12054 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
12055 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
12056 	}
12057 
12058 	/* Init the cdb from the given uscsi struct */
12059 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
12060 	    uscmd->uscsi_cdb[0], 0, 0, 0);
12061 
12062 	SD_FILL_SCSI1_LUN(un, pktp);
12063 
12064 	/*
12065 	 * Set up the optional USCSI flags. See the uscsi (7I) man page
12066 	 * for listing of the supported flags.
12067 	 */
12068 
12069 	if (uscmd->uscsi_flags & USCSI_SILENT) {
12070 		flags |= FLAG_SILENT;
12071 	}
12072 
12073 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
12074 		flags |= FLAG_DIAGNOSE;
12075 	}
12076 
12077 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
12078 		flags |= FLAG_ISOLATE;
12079 	}
12080 
12081 	if (un->un_f_is_fibre == FALSE) {
12082 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
12083 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
12084 		}
12085 	}
12086 
12087 	/*
12088 	 * Set the pkt flags here so we save time later.
12089 	 * Note: These flags are NOT in the uscsi man page!!!
12090 	 */
12091 	if (uscmd->uscsi_flags & USCSI_HEAD) {
12092 		flags |= FLAG_HEAD;
12093 	}
12094 
12095 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
12096 		flags |= FLAG_NOINTR;
12097 	}
12098 
12099 	/*
12100 	 * For tagged queueing, things get a bit complicated.
12101 	 * Check first for head of queue and last for ordered queue.
12102 	 * If neither head nor order, use the default driver tag flags.
12103 	 */
12104 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
12105 		if (uscmd->uscsi_flags & USCSI_HTAG) {
12106 			flags |= FLAG_HTAG;
12107 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
12108 			flags |= FLAG_OTAG;
12109 		} else {
12110 			flags |= un->un_tagflags & FLAG_TAGMASK;
12111 		}
12112 	}
12113 
12114 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
12115 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
12116 	}
12117 
12118 	pktp->pkt_flags = flags;
12119 
12120 	/* Copy the caller's CDB into the pkt... */
12121 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
12122 
12123 	if (uscmd->uscsi_timeout == 0) {
12124 		pktp->pkt_time = un->un_uscsi_timeout;
12125 	} else {
12126 		pktp->pkt_time = uscmd->uscsi_timeout;
12127 	}
12128 
12129 	/* need it later to identify USCSI request in sdintr */
12130 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
12131 
12132 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
12133 
12134 	pktp->pkt_private = bp;
12135 	pktp->pkt_comp = sdintr;
12136 	*pktpp = pktp;
12137 
12138 	SD_TRACE(SD_LOG_IO_CORE, un,
12139 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
12140 
12141 	return (SD_PKT_ALLOC_SUCCESS);
12142 }
12143 
12144 
12145 /*
12146  *    Function: sd_destroypkt_for_uscsi
12147  *
12148  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
12149  *		IOs.. Also saves relevant info into the associated uscsi_cmd
12150  *		struct.
12151  *
12152  *     Context: May be called under interrupt context
12153  */
12154 
12155 static void
12156 sd_destroypkt_for_uscsi(struct buf *bp)
12157 {
12158 	struct uscsi_cmd *uscmd;
12159 	struct sd_xbuf	*xp;
12160 	struct scsi_pkt	*pktp;
12161 	struct sd_lun	*un;
12162 
12163 	ASSERT(bp != NULL);
12164 	xp = SD_GET_XBUF(bp);
12165 	ASSERT(xp != NULL);
12166 	un = SD_GET_UN(bp);
12167 	ASSERT(un != NULL);
12168 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12169 	pktp = SD_GET_PKTP(bp);
12170 	ASSERT(pktp != NULL);
12171 
12172 	SD_TRACE(SD_LOG_IO_CORE, un,
12173 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
12174 
12175 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12176 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12177 	ASSERT(uscmd != NULL);
12178 
12179 	/* Save the status and the residual into the uscsi_cmd struct */
12180 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
12181 	uscmd->uscsi_resid  = bp->b_resid;
12182 
12183 	/*
12184 	 * If enabled, copy any saved sense data into the area specified
12185 	 * by the uscsi command.
12186 	 */
12187 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
12188 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
12189 		/*
12190 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
12191 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
12192 		 */
12193 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
12194 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
12195 		bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf, SENSE_LENGTH);
12196 	}
12197 
12198 	/* We are done with the scsi_pkt; free it now */
12199 	ASSERT(SD_GET_PKTP(bp) != NULL);
12200 	scsi_destroy_pkt(SD_GET_PKTP(bp));
12201 
12202 	SD_TRACE(SD_LOG_IO_CORE, un,
12203 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
12204 }
12205 
12206 
12207 /*
12208  *    Function: sd_bioclone_alloc
12209  *
12210  * Description: Allocate a buf(9S) and init it as per the given buf
12211  *		and the various arguments.  The associated sd_xbuf
12212  *		struct is (nearly) duplicated.  The struct buf *bp
12213  *		argument is saved in new_xp->xb_private.
12214  *
12215  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12216  *		datalen - size of data area for the shadow bp
12217  *		blkno - starting LBA
12218  *		func - function pointer for b_iodone in the shadow buf. (May
12219  *			be NULL if none.)
12220  *
12221  * Return Code: Pointer to allocates buf(9S) struct
12222  *
12223  *     Context: Can sleep.
12224  */
12225 
12226 static struct buf *
12227 sd_bioclone_alloc(struct buf *bp, size_t datalen,
12228 	daddr_t blkno, int (*func)(struct buf *))
12229 {
12230 	struct	sd_lun	*un;
12231 	struct	sd_xbuf	*xp;
12232 	struct	sd_xbuf	*new_xp;
12233 	struct	buf	*new_bp;
12234 
12235 	ASSERT(bp != NULL);
12236 	xp = SD_GET_XBUF(bp);
12237 	ASSERT(xp != NULL);
12238 	un = SD_GET_UN(bp);
12239 	ASSERT(un != NULL);
12240 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12241 
12242 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
12243 	    NULL, KM_SLEEP);
12244 
12245 	new_bp->b_lblkno	= blkno;
12246 
12247 	/*
12248 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12249 	 * original xbuf into it.
12250 	 */
12251 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12252 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12253 
12254 	/*
12255 	 * The given bp is automatically saved in the xb_private member
12256 	 * of the new xbuf.  Callers are allowed to depend on this.
12257 	 */
12258 	new_xp->xb_private = bp;
12259 
12260 	new_bp->b_private  = new_xp;
12261 
12262 	return (new_bp);
12263 }
12264 
12265 /*
12266  *    Function: sd_shadow_buf_alloc
12267  *
12268  * Description: Allocate a buf(9S) and init it as per the given buf
12269  *		and the various arguments.  The associated sd_xbuf
12270  *		struct is (nearly) duplicated.  The struct buf *bp
12271  *		argument is saved in new_xp->xb_private.
12272  *
12273  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12274  *		datalen - size of data area for the shadow bp
12275  *		bflags - B_READ or B_WRITE (pseudo flag)
12276  *		blkno - starting LBA
12277  *		func - function pointer for b_iodone in the shadow buf. (May
12278  *			be NULL if none.)
12279  *
12280  * Return Code: Pointer to allocates buf(9S) struct
12281  *
12282  *     Context: Can sleep.
12283  */
12284 
12285 static struct buf *
12286 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
12287 	daddr_t blkno, int (*func)(struct buf *))
12288 {
12289 	struct	sd_lun	*un;
12290 	struct	sd_xbuf	*xp;
12291 	struct	sd_xbuf	*new_xp;
12292 	struct	buf	*new_bp;
12293 
12294 	ASSERT(bp != NULL);
12295 	xp = SD_GET_XBUF(bp);
12296 	ASSERT(xp != NULL);
12297 	un = SD_GET_UN(bp);
12298 	ASSERT(un != NULL);
12299 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12300 
12301 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
12302 		bp_mapin(bp);
12303 	}
12304 
12305 	bflags &= (B_READ | B_WRITE);
12306 #if defined(__i386) || defined(__amd64)
12307 	new_bp = getrbuf(KM_SLEEP);
12308 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
12309 	new_bp->b_bcount = datalen;
12310 	new_bp->b_flags = bflags |
12311 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
12312 #else
12313 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
12314 	    datalen, bflags, SLEEP_FUNC, NULL);
12315 #endif
12316 	new_bp->av_forw	= NULL;
12317 	new_bp->av_back	= NULL;
12318 	new_bp->b_dev	= bp->b_dev;
12319 	new_bp->b_blkno	= blkno;
12320 	new_bp->b_iodone = func;
12321 	new_bp->b_edev	= bp->b_edev;
12322 	new_bp->b_resid	= 0;
12323 
12324 	/* We need to preserve the B_FAILFAST flag */
12325 	if (bp->b_flags & B_FAILFAST) {
12326 		new_bp->b_flags |= B_FAILFAST;
12327 	}
12328 
12329 	/*
12330 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12331 	 * original xbuf into it.
12332 	 */
12333 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12334 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12335 
12336 	/* Need later to copy data between the shadow buf & original buf! */
12337 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
12338 
12339 	/*
12340 	 * The given bp is automatically saved in the xb_private member
12341 	 * of the new xbuf.  Callers are allowed to depend on this.
12342 	 */
12343 	new_xp->xb_private = bp;
12344 
12345 	new_bp->b_private  = new_xp;
12346 
12347 	return (new_bp);
12348 }
12349 
12350 /*
12351  *    Function: sd_bioclone_free
12352  *
12353  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
12354  *		in the larger than partition operation.
12355  *
12356  *     Context: May be called under interrupt context
12357  */
12358 
12359 static void
12360 sd_bioclone_free(struct buf *bp)
12361 {
12362 	struct sd_xbuf	*xp;
12363 
12364 	ASSERT(bp != NULL);
12365 	xp = SD_GET_XBUF(bp);
12366 	ASSERT(xp != NULL);
12367 
12368 	/*
12369 	 * Call bp_mapout() before freeing the buf,  in case a lower
12370 	 * layer or HBA  had done a bp_mapin().  we must do this here
12371 	 * as we are the "originator" of the shadow buf.
12372 	 */
12373 	bp_mapout(bp);
12374 
12375 	/*
12376 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12377 	 * never gets confused by a stale value in this field. (Just a little
12378 	 * extra defensiveness here.)
12379 	 */
12380 	bp->b_iodone = NULL;
12381 
12382 	freerbuf(bp);
12383 
12384 	kmem_free(xp, sizeof (struct sd_xbuf));
12385 }
12386 
12387 /*
12388  *    Function: sd_shadow_buf_free
12389  *
12390  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
12391  *
12392  *     Context: May be called under interrupt context
12393  */
12394 
12395 static void
12396 sd_shadow_buf_free(struct buf *bp)
12397 {
12398 	struct sd_xbuf	*xp;
12399 
12400 	ASSERT(bp != NULL);
12401 	xp = SD_GET_XBUF(bp);
12402 	ASSERT(xp != NULL);
12403 
12404 #if defined(__sparc)
12405 	/*
12406 	 * Call bp_mapout() before freeing the buf,  in case a lower
12407 	 * layer or HBA  had done a bp_mapin().  we must do this here
12408 	 * as we are the "originator" of the shadow buf.
12409 	 */
12410 	bp_mapout(bp);
12411 #endif
12412 
12413 	/*
12414 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12415 	 * never gets confused by a stale value in this field. (Just a little
12416 	 * extra defensiveness here.)
12417 	 */
12418 	bp->b_iodone = NULL;
12419 
12420 #if defined(__i386) || defined(__amd64)
12421 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
12422 	freerbuf(bp);
12423 #else
12424 	scsi_free_consistent_buf(bp);
12425 #endif
12426 
12427 	kmem_free(xp, sizeof (struct sd_xbuf));
12428 }
12429 
12430 
12431 /*
12432  *    Function: sd_print_transport_rejected_message
12433  *
12434  * Description: This implements the ludicrously complex rules for printing
12435  *		a "transport rejected" message.  This is to address the
12436  *		specific problem of having a flood of this error message
12437  *		produced when a failover occurs.
12438  *
12439  *     Context: Any.
12440  */
12441 
12442 static void
12443 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
12444 	int code)
12445 {
12446 	ASSERT(un != NULL);
12447 	ASSERT(mutex_owned(SD_MUTEX(un)));
12448 	ASSERT(xp != NULL);
12449 
12450 	/*
12451 	 * Print the "transport rejected" message under the following
12452 	 * conditions:
12453 	 *
12454 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
12455 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
12456 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
12457 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
12458 	 *   scsi_transport(9F) (which indicates that the target might have
12459 	 *   gone off-line).  This uses the un->un_tran_fatal_count
12460 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
12461 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
12462 	 *   from scsi_transport().
12463 	 *
12464 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
12465 	 * the preceeding cases in order for the message to be printed.
12466 	 */
12467 	if ((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) {
12468 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
12469 		    (code != TRAN_FATAL_ERROR) ||
12470 		    (un->un_tran_fatal_count == 1)) {
12471 			switch (code) {
12472 			case TRAN_BADPKT:
12473 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12474 				    "transport rejected bad packet\n");
12475 				break;
12476 			case TRAN_FATAL_ERROR:
12477 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12478 				    "transport rejected fatal error\n");
12479 				break;
12480 			default:
12481 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12482 				    "transport rejected (%d)\n", code);
12483 				break;
12484 			}
12485 		}
12486 	}
12487 }
12488 
12489 
12490 /*
12491  *    Function: sd_add_buf_to_waitq
12492  *
12493  * Description: Add the given buf(9S) struct to the wait queue for the
12494  *		instance.  If sorting is enabled, then the buf is added
12495  *		to the queue via an elevator sort algorithm (a la
12496  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
12497  *		If sorting is not enabled, then the buf is just added
12498  *		to the end of the wait queue.
12499  *
12500  * Return Code: void
12501  *
12502  *     Context: Does not sleep/block, therefore technically can be called
12503  *		from any context.  However if sorting is enabled then the
12504  *		execution time is indeterminate, and may take long if
12505  *		the wait queue grows large.
12506  */
12507 
12508 static void
12509 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
12510 {
12511 	struct buf *ap;
12512 
12513 	ASSERT(bp != NULL);
12514 	ASSERT(un != NULL);
12515 	ASSERT(mutex_owned(SD_MUTEX(un)));
12516 
12517 	/* If the queue is empty, add the buf as the only entry & return. */
12518 	if (un->un_waitq_headp == NULL) {
12519 		ASSERT(un->un_waitq_tailp == NULL);
12520 		un->un_waitq_headp = un->un_waitq_tailp = bp;
12521 		bp->av_forw = NULL;
12522 		return;
12523 	}
12524 
12525 	ASSERT(un->un_waitq_tailp != NULL);
12526 
12527 	/*
12528 	 * If sorting is disabled, just add the buf to the tail end of
12529 	 * the wait queue and return.
12530 	 */
12531 	if (un->un_f_disksort_disabled) {
12532 		un->un_waitq_tailp->av_forw = bp;
12533 		un->un_waitq_tailp = bp;
12534 		bp->av_forw = NULL;
12535 		return;
12536 	}
12537 
12538 	/*
12539 	 * Sort thru the list of requests currently on the wait queue
12540 	 * and add the new buf request at the appropriate position.
12541 	 *
12542 	 * The un->un_waitq_headp is an activity chain pointer on which
12543 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
12544 	 * first queue holds those requests which are positioned after
12545 	 * the current SD_GET_BLKNO() (in the first request); the second holds
12546 	 * requests which came in after their SD_GET_BLKNO() number was passed.
12547 	 * Thus we implement a one way scan, retracting after reaching
12548 	 * the end of the drive to the first request on the second
12549 	 * queue, at which time it becomes the first queue.
12550 	 * A one-way scan is natural because of the way UNIX read-ahead
12551 	 * blocks are allocated.
12552 	 *
12553 	 * If we lie after the first request, then we must locate the
12554 	 * second request list and add ourselves to it.
12555 	 */
12556 	ap = un->un_waitq_headp;
12557 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
12558 		while (ap->av_forw != NULL) {
12559 			/*
12560 			 * Look for an "inversion" in the (normally
12561 			 * ascending) block numbers. This indicates
12562 			 * the start of the second request list.
12563 			 */
12564 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
12565 				/*
12566 				 * Search the second request list for the
12567 				 * first request at a larger block number.
12568 				 * We go before that; however if there is
12569 				 * no such request, we go at the end.
12570 				 */
12571 				do {
12572 					if (SD_GET_BLKNO(bp) <
12573 					    SD_GET_BLKNO(ap->av_forw)) {
12574 						goto insert;
12575 					}
12576 					ap = ap->av_forw;
12577 				} while (ap->av_forw != NULL);
12578 				goto insert;		/* after last */
12579 			}
12580 			ap = ap->av_forw;
12581 		}
12582 
12583 		/*
12584 		 * No inversions... we will go after the last, and
12585 		 * be the first request in the second request list.
12586 		 */
12587 		goto insert;
12588 	}
12589 
12590 	/*
12591 	 * Request is at/after the current request...
12592 	 * sort in the first request list.
12593 	 */
12594 	while (ap->av_forw != NULL) {
12595 		/*
12596 		 * We want to go after the current request (1) if
12597 		 * there is an inversion after it (i.e. it is the end
12598 		 * of the first request list), or (2) if the next
12599 		 * request is a larger block no. than our request.
12600 		 */
12601 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
12602 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
12603 			goto insert;
12604 		}
12605 		ap = ap->av_forw;
12606 	}
12607 
12608 	/*
12609 	 * Neither a second list nor a larger request, therefore
12610 	 * we go at the end of the first list (which is the same
12611 	 * as the end of the whole schebang).
12612 	 */
12613 insert:
12614 	bp->av_forw = ap->av_forw;
12615 	ap->av_forw = bp;
12616 
12617 	/*
12618 	 * If we inserted onto the tail end of the waitq, make sure the
12619 	 * tail pointer is updated.
12620 	 */
12621 	if (ap == un->un_waitq_tailp) {
12622 		un->un_waitq_tailp = bp;
12623 	}
12624 }
12625 
12626 
12627 /*
12628  *    Function: sd_start_cmds
12629  *
12630  * Description: Remove and transport cmds from the driver queues.
12631  *
12632  *   Arguments: un - pointer to the unit (soft state) struct for the target.
12633  *
12634  *		immed_bp - ptr to a buf to be transported immediately. Only
12635  *		the immed_bp is transported; bufs on the waitq are not
12636  *		processed and the un_retry_bp is not checked.  If immed_bp is
12637  *		NULL, then normal queue processing is performed.
12638  *
12639  *     Context: May be called from kernel thread context, interrupt context,
12640  *		or runout callback context. This function may not block or
12641  *		call routines that block.
12642  */
12643 
12644 static void
12645 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
12646 {
12647 	struct	sd_xbuf	*xp;
12648 	struct	buf	*bp;
12649 	void	(*statp)(kstat_io_t *);
12650 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12651 	void	(*saved_statp)(kstat_io_t *);
12652 #endif
12653 	int	rval;
12654 
12655 	ASSERT(un != NULL);
12656 	ASSERT(mutex_owned(SD_MUTEX(un)));
12657 	ASSERT(un->un_ncmds_in_transport >= 0);
12658 	ASSERT(un->un_throttle >= 0);
12659 
12660 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
12661 
12662 	do {
12663 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12664 		saved_statp = NULL;
12665 #endif
12666 
12667 		/*
12668 		 * If we are syncing or dumping, fail the command to
12669 		 * avoid recursively calling back into scsi_transport().
12670 		 * The dump I/O itself uses a separate code path so this
12671 		 * only prevents non-dump I/O from being sent while dumping.
12672 		 * File system sync takes place before dumping begins.
12673 		 * During panic, filesystem I/O is allowed provided
12674 		 * un_in_callback is <= 1.  This is to prevent recursion
12675 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
12676 		 * sd_start_cmds and so on.  See panic.c for more information
12677 		 * about the states the system can be in during panic.
12678 		 */
12679 		if ((un->un_state == SD_STATE_DUMPING) ||
12680 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
12681 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12682 			    "sd_start_cmds: panicking\n");
12683 			goto exit;
12684 		}
12685 
12686 		if ((bp = immed_bp) != NULL) {
12687 			/*
12688 			 * We have a bp that must be transported immediately.
12689 			 * It's OK to transport the immed_bp here without doing
12690 			 * the throttle limit check because the immed_bp is
12691 			 * always used in a retry/recovery case. This means
12692 			 * that we know we are not at the throttle limit by
12693 			 * virtue of the fact that to get here we must have
12694 			 * already gotten a command back via sdintr(). This also
12695 			 * relies on (1) the command on un_retry_bp preventing
12696 			 * further commands from the waitq from being issued;
12697 			 * and (2) the code in sd_retry_command checking the
12698 			 * throttle limit before issuing a delayed or immediate
12699 			 * retry. This holds even if the throttle limit is
12700 			 * currently ratcheted down from its maximum value.
12701 			 */
12702 			statp = kstat_runq_enter;
12703 			if (bp == un->un_retry_bp) {
12704 				ASSERT((un->un_retry_statp == NULL) ||
12705 				    (un->un_retry_statp == kstat_waitq_enter) ||
12706 				    (un->un_retry_statp ==
12707 				    kstat_runq_back_to_waitq));
12708 				/*
12709 				 * If the waitq kstat was incremented when
12710 				 * sd_set_retry_bp() queued this bp for a retry,
12711 				 * then we must set up statp so that the waitq
12712 				 * count will get decremented correctly below.
12713 				 * Also we must clear un->un_retry_statp to
12714 				 * ensure that we do not act on a stale value
12715 				 * in this field.
12716 				 */
12717 				if ((un->un_retry_statp == kstat_waitq_enter) ||
12718 				    (un->un_retry_statp ==
12719 				    kstat_runq_back_to_waitq)) {
12720 					statp = kstat_waitq_to_runq;
12721 				}
12722 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12723 				saved_statp = un->un_retry_statp;
12724 #endif
12725 				un->un_retry_statp = NULL;
12726 
12727 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
12728 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
12729 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
12730 				    un, un->un_retry_bp, un->un_throttle,
12731 				    un->un_ncmds_in_transport);
12732 			} else {
12733 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
12734 				    "processing priority bp:0x%p\n", bp);
12735 			}
12736 
12737 		} else if ((bp = un->un_waitq_headp) != NULL) {
12738 			/*
12739 			 * A command on the waitq is ready to go, but do not
12740 			 * send it if:
12741 			 *
12742 			 * (1) the throttle limit has been reached, or
12743 			 * (2) a retry is pending, or
12744 			 * (3) a START_STOP_UNIT callback pending, or
12745 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
12746 			 *	command is pending.
12747 			 *
12748 			 * For all of these conditions, IO processing will
12749 			 * restart after the condition is cleared.
12750 			 */
12751 			if (un->un_ncmds_in_transport >= un->un_throttle) {
12752 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12753 				    "sd_start_cmds: exiting, "
12754 				    "throttle limit reached!\n");
12755 				goto exit;
12756 			}
12757 			if (un->un_retry_bp != NULL) {
12758 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12759 				    "sd_start_cmds: exiting, retry pending!\n");
12760 				goto exit;
12761 			}
12762 			if (un->un_startstop_timeid != NULL) {
12763 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12764 				    "sd_start_cmds: exiting, "
12765 				    "START_STOP pending!\n");
12766 				goto exit;
12767 			}
12768 			if (un->un_direct_priority_timeid != NULL) {
12769 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12770 				    "sd_start_cmds: exiting, "
12771 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
12772 				goto exit;
12773 			}
12774 
12775 			/* Dequeue the command */
12776 			un->un_waitq_headp = bp->av_forw;
12777 			if (un->un_waitq_headp == NULL) {
12778 				un->un_waitq_tailp = NULL;
12779 			}
12780 			bp->av_forw = NULL;
12781 			statp = kstat_waitq_to_runq;
12782 			SD_TRACE(SD_LOG_IO_CORE, un,
12783 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
12784 
12785 		} else {
12786 			/* No work to do so bail out now */
12787 			SD_TRACE(SD_LOG_IO_CORE, un,
12788 			    "sd_start_cmds: no more work, exiting!\n");
12789 			goto exit;
12790 		}
12791 
12792 		/*
12793 		 * Reset the state to normal. This is the mechanism by which
12794 		 * the state transitions from either SD_STATE_RWAIT or
12795 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
12796 		 * If state is SD_STATE_PM_CHANGING then this command is
12797 		 * part of the device power control and the state must
12798 		 * not be put back to normal. Doing so would would
12799 		 * allow new commands to proceed when they shouldn't,
12800 		 * the device may be going off.
12801 		 */
12802 		if ((un->un_state != SD_STATE_SUSPENDED) &&
12803 		    (un->un_state != SD_STATE_PM_CHANGING)) {
12804 			New_state(un, SD_STATE_NORMAL);
12805 		}
12806 
12807 		xp = SD_GET_XBUF(bp);
12808 		ASSERT(xp != NULL);
12809 
12810 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12811 		/*
12812 		 * Allocate the scsi_pkt if we need one, or attach DMA
12813 		 * resources if we have a scsi_pkt that needs them. The
12814 		 * latter should only occur for commands that are being
12815 		 * retried.
12816 		 */
12817 		if ((xp->xb_pktp == NULL) ||
12818 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
12819 #else
12820 		if (xp->xb_pktp == NULL) {
12821 #endif
12822 			/*
12823 			 * There is no scsi_pkt allocated for this buf. Call
12824 			 * the initpkt function to allocate & init one.
12825 			 *
12826 			 * The scsi_init_pkt runout callback functionality is
12827 			 * implemented as follows:
12828 			 *
12829 			 * 1) The initpkt function always calls
12830 			 *    scsi_init_pkt(9F) with sdrunout specified as the
12831 			 *    callback routine.
12832 			 * 2) A successful packet allocation is initialized and
12833 			 *    the I/O is transported.
12834 			 * 3) The I/O associated with an allocation resource
12835 			 *    failure is left on its queue to be retried via
12836 			 *    runout or the next I/O.
12837 			 * 4) The I/O associated with a DMA error is removed
12838 			 *    from the queue and failed with EIO. Processing of
12839 			 *    the transport queues is also halted to be
12840 			 *    restarted via runout or the next I/O.
12841 			 * 5) The I/O associated with a CDB size or packet
12842 			 *    size error is removed from the queue and failed
12843 			 *    with EIO. Processing of the transport queues is
12844 			 *    continued.
12845 			 *
12846 			 * Note: there is no interface for canceling a runout
12847 			 * callback. To prevent the driver from detaching or
12848 			 * suspending while a runout is pending the driver
12849 			 * state is set to SD_STATE_RWAIT
12850 			 *
12851 			 * Note: using the scsi_init_pkt callback facility can
12852 			 * result in an I/O request persisting at the head of
12853 			 * the list which cannot be satisfied even after
12854 			 * multiple retries. In the future the driver may
12855 			 * implement some kind of maximum runout count before
12856 			 * failing an I/O.
12857 			 *
12858 			 * Note: the use of funcp below may seem superfluous,
12859 			 * but it helps warlock figure out the correct
12860 			 * initpkt function calls (see [s]sd.wlcmd).
12861 			 */
12862 			struct scsi_pkt	*pktp;
12863 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
12864 
12865 			ASSERT(bp != un->un_rqs_bp);
12866 
12867 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
12868 			switch ((*funcp)(bp, &pktp)) {
12869 			case  SD_PKT_ALLOC_SUCCESS:
12870 				xp->xb_pktp = pktp;
12871 				SD_TRACE(SD_LOG_IO_CORE, un,
12872 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
12873 				    pktp);
12874 				goto got_pkt;
12875 
12876 			case SD_PKT_ALLOC_FAILURE:
12877 				/*
12878 				 * Temporary (hopefully) resource depletion.
12879 				 * Since retries and RQS commands always have a
12880 				 * scsi_pkt allocated, these cases should never
12881 				 * get here. So the only cases this needs to
12882 				 * handle is a bp from the waitq (which we put
12883 				 * back onto the waitq for sdrunout), or a bp
12884 				 * sent as an immed_bp (which we just fail).
12885 				 */
12886 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12887 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
12888 
12889 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12890 
12891 				if (bp == immed_bp) {
12892 					/*
12893 					 * If SD_XB_DMA_FREED is clear, then
12894 					 * this is a failure to allocate a
12895 					 * scsi_pkt, and we must fail the
12896 					 * command.
12897 					 */
12898 					if ((xp->xb_pkt_flags &
12899 					    SD_XB_DMA_FREED) == 0) {
12900 						break;
12901 					}
12902 
12903 					/*
12904 					 * If this immediate command is NOT our
12905 					 * un_retry_bp, then we must fail it.
12906 					 */
12907 					if (bp != un->un_retry_bp) {
12908 						break;
12909 					}
12910 
12911 					/*
12912 					 * We get here if this cmd is our
12913 					 * un_retry_bp that was DMAFREED, but
12914 					 * scsi_init_pkt() failed to reallocate
12915 					 * DMA resources when we attempted to
12916 					 * retry it. This can happen when an
12917 					 * mpxio failover is in progress, but
12918 					 * we don't want to just fail the
12919 					 * command in this case.
12920 					 *
12921 					 * Use timeout(9F) to restart it after
12922 					 * a 100ms delay.  We don't want to
12923 					 * let sdrunout() restart it, because
12924 					 * sdrunout() is just supposed to start
12925 					 * commands that are sitting on the
12926 					 * wait queue.  The un_retry_bp stays
12927 					 * set until the command completes, but
12928 					 * sdrunout can be called many times
12929 					 * before that happens.  Since sdrunout
12930 					 * cannot tell if the un_retry_bp is
12931 					 * already in the transport, it could
12932 					 * end up calling scsi_transport() for
12933 					 * the un_retry_bp multiple times.
12934 					 *
12935 					 * Also: don't schedule the callback
12936 					 * if some other callback is already
12937 					 * pending.
12938 					 */
12939 					if (un->un_retry_statp == NULL) {
12940 						/*
12941 						 * restore the kstat pointer to
12942 						 * keep kstat counts coherent
12943 						 * when we do retry the command.
12944 						 */
12945 						un->un_retry_statp =
12946 						    saved_statp;
12947 					}
12948 
12949 					if ((un->un_startstop_timeid == NULL) &&
12950 					    (un->un_retry_timeid == NULL) &&
12951 					    (un->un_direct_priority_timeid ==
12952 					    NULL)) {
12953 
12954 						un->un_retry_timeid =
12955 						    timeout(
12956 						    sd_start_retry_command,
12957 						    un, SD_RESTART_TIMEOUT);
12958 					}
12959 					goto exit;
12960 				}
12961 
12962 #else
12963 				if (bp == immed_bp) {
12964 					break;	/* Just fail the command */
12965 				}
12966 #endif
12967 
12968 				/* Add the buf back to the head of the waitq */
12969 				bp->av_forw = un->un_waitq_headp;
12970 				un->un_waitq_headp = bp;
12971 				if (un->un_waitq_tailp == NULL) {
12972 					un->un_waitq_tailp = bp;
12973 				}
12974 				goto exit;
12975 
12976 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
12977 				/*
12978 				 * HBA DMA resource failure. Fail the command
12979 				 * and continue processing of the queues.
12980 				 */
12981 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12982 				    "sd_start_cmds: "
12983 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
12984 				break;
12985 
12986 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
12987 				/*
12988 				 * Note:x86: Partial DMA mapping not supported
12989 				 * for USCSI commands, and all the needed DMA
12990 				 * resources were not allocated.
12991 				 */
12992 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12993 				    "sd_start_cmds: "
12994 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
12995 				break;
12996 
12997 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
12998 				/*
12999 				 * Note:x86: Request cannot fit into CDB based
13000 				 * on lba and len.
13001 				 */
13002 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13003 				    "sd_start_cmds: "
13004 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
13005 				break;
13006 
13007 			default:
13008 				/* Should NEVER get here! */
13009 				panic("scsi_initpkt error");
13010 				/*NOTREACHED*/
13011 			}
13012 
13013 			/*
13014 			 * Fatal error in allocating a scsi_pkt for this buf.
13015 			 * Update kstats & return the buf with an error code.
13016 			 * We must use sd_return_failed_command_no_restart() to
13017 			 * avoid a recursive call back into sd_start_cmds().
13018 			 * However this also means that we must keep processing
13019 			 * the waitq here in order to avoid stalling.
13020 			 */
13021 			if (statp == kstat_waitq_to_runq) {
13022 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
13023 			}
13024 			sd_return_failed_command_no_restart(un, bp, EIO);
13025 			if (bp == immed_bp) {
13026 				/* immed_bp is gone by now, so clear this */
13027 				immed_bp = NULL;
13028 			}
13029 			continue;
13030 		}
13031 got_pkt:
13032 		if (bp == immed_bp) {
13033 			/* goto the head of the class.... */
13034 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13035 		}
13036 
13037 		un->un_ncmds_in_transport++;
13038 		SD_UPDATE_KSTATS(un, statp, bp);
13039 
13040 		/*
13041 		 * Call scsi_transport() to send the command to the target.
13042 		 * According to SCSA architecture, we must drop the mutex here
13043 		 * before calling scsi_transport() in order to avoid deadlock.
13044 		 * Note that the scsi_pkt's completion routine can be executed
13045 		 * (from interrupt context) even before the call to
13046 		 * scsi_transport() returns.
13047 		 */
13048 		SD_TRACE(SD_LOG_IO_CORE, un,
13049 		    "sd_start_cmds: calling scsi_transport()\n");
13050 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
13051 
13052 		mutex_exit(SD_MUTEX(un));
13053 		rval = scsi_transport(xp->xb_pktp);
13054 		mutex_enter(SD_MUTEX(un));
13055 
13056 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13057 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
13058 
13059 		switch (rval) {
13060 		case TRAN_ACCEPT:
13061 			/* Clear this with every pkt accepted by the HBA */
13062 			un->un_tran_fatal_count = 0;
13063 			break;	/* Success; try the next cmd (if any) */
13064 
13065 		case TRAN_BUSY:
13066 			un->un_ncmds_in_transport--;
13067 			ASSERT(un->un_ncmds_in_transport >= 0);
13068 
13069 			/*
13070 			 * Don't retry request sense, the sense data
13071 			 * is lost when another request is sent.
13072 			 * Free up the rqs buf and retry
13073 			 * the original failed cmd.  Update kstat.
13074 			 */
13075 			if (bp == un->un_rqs_bp) {
13076 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13077 				bp = sd_mark_rqs_idle(un, xp);
13078 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
13079 				    NULL, NULL, EIO, SD_BSY_TIMEOUT / 500,
13080 				    kstat_waitq_enter);
13081 				goto exit;
13082 			}
13083 
13084 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13085 			/*
13086 			 * Free the DMA resources for the  scsi_pkt. This will
13087 			 * allow mpxio to select another path the next time
13088 			 * we call scsi_transport() with this scsi_pkt.
13089 			 * See sdintr() for the rationalization behind this.
13090 			 */
13091 			if ((un->un_f_is_fibre == TRUE) &&
13092 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
13093 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
13094 				scsi_dmafree(xp->xb_pktp);
13095 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
13096 			}
13097 #endif
13098 
13099 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
13100 				/*
13101 				 * Commands that are SD_PATH_DIRECT_PRIORITY
13102 				 * are for error recovery situations. These do
13103 				 * not use the normal command waitq, so if they
13104 				 * get a TRAN_BUSY we cannot put them back onto
13105 				 * the waitq for later retry. One possible
13106 				 * problem is that there could already be some
13107 				 * other command on un_retry_bp that is waiting
13108 				 * for this one to complete, so we would be
13109 				 * deadlocked if we put this command back onto
13110 				 * the waitq for later retry (since un_retry_bp
13111 				 * must complete before the driver gets back to
13112 				 * commands on the waitq).
13113 				 *
13114 				 * To avoid deadlock we must schedule a callback
13115 				 * that will restart this command after a set
13116 				 * interval.  This should keep retrying for as
13117 				 * long as the underlying transport keeps
13118 				 * returning TRAN_BUSY (just like for other
13119 				 * commands).  Use the same timeout interval as
13120 				 * for the ordinary TRAN_BUSY retry.
13121 				 */
13122 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13123 				    "sd_start_cmds: scsi_transport() returned "
13124 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
13125 
13126 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13127 				un->un_direct_priority_timeid =
13128 				    timeout(sd_start_direct_priority_command,
13129 				    bp, SD_BSY_TIMEOUT / 500);
13130 
13131 				goto exit;
13132 			}
13133 
13134 			/*
13135 			 * For TRAN_BUSY, we want to reduce the throttle value,
13136 			 * unless we are retrying a command.
13137 			 */
13138 			if (bp != un->un_retry_bp) {
13139 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
13140 			}
13141 
13142 			/*
13143 			 * Set up the bp to be tried again 10 ms later.
13144 			 * Note:x86: Is there a timeout value in the sd_lun
13145 			 * for this condition?
13146 			 */
13147 			sd_set_retry_bp(un, bp, SD_BSY_TIMEOUT / 500,
13148 			    kstat_runq_back_to_waitq);
13149 			goto exit;
13150 
13151 		case TRAN_FATAL_ERROR:
13152 			un->un_tran_fatal_count++;
13153 			/* FALLTHRU */
13154 
13155 		case TRAN_BADPKT:
13156 		default:
13157 			un->un_ncmds_in_transport--;
13158 			ASSERT(un->un_ncmds_in_transport >= 0);
13159 
13160 			/*
13161 			 * If this is our REQUEST SENSE command with a
13162 			 * transport error, we must get back the pointers
13163 			 * to the original buf, and mark the REQUEST
13164 			 * SENSE command as "available".
13165 			 */
13166 			if (bp == un->un_rqs_bp) {
13167 				bp = sd_mark_rqs_idle(un, xp);
13168 				xp = SD_GET_XBUF(bp);
13169 			} else {
13170 				/*
13171 				 * Legacy behavior: do not update transport
13172 				 * error count for request sense commands.
13173 				 */
13174 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
13175 			}
13176 
13177 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13178 			sd_print_transport_rejected_message(un, xp, rval);
13179 
13180 			/*
13181 			 * We must use sd_return_failed_command_no_restart() to
13182 			 * avoid a recursive call back into sd_start_cmds().
13183 			 * However this also means that we must keep processing
13184 			 * the waitq here in order to avoid stalling.
13185 			 */
13186 			sd_return_failed_command_no_restart(un, bp, EIO);
13187 
13188 			/*
13189 			 * Notify any threads waiting in sd_ddi_suspend() that
13190 			 * a command completion has occurred.
13191 			 */
13192 			if (un->un_state == SD_STATE_SUSPENDED) {
13193 				cv_broadcast(&un->un_disk_busy_cv);
13194 			}
13195 
13196 			if (bp == immed_bp) {
13197 				/* immed_bp is gone by now, so clear this */
13198 				immed_bp = NULL;
13199 			}
13200 			break;
13201 		}
13202 
13203 	} while (immed_bp == NULL);
13204 
13205 exit:
13206 	ASSERT(mutex_owned(SD_MUTEX(un)));
13207 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
13208 }
13209 
13210 
13211 /*
13212  *    Function: sd_return_command
13213  *
13214  * Description: Returns a command to its originator (with or without an
13215  *		error).  Also starts commands waiting to be transported
13216  *		to the target.
13217  *
13218  *     Context: May be called from interrupt, kernel, or timeout context
13219  */
13220 
13221 static void
13222 sd_return_command(struct sd_lun *un, struct buf *bp)
13223 {
13224 	struct sd_xbuf *xp;
13225 #if defined(__i386) || defined(__amd64)
13226 	struct scsi_pkt *pktp;
13227 #endif
13228 
13229 	ASSERT(bp != NULL);
13230 	ASSERT(un != NULL);
13231 	ASSERT(mutex_owned(SD_MUTEX(un)));
13232 	ASSERT(bp != un->un_rqs_bp);
13233 	xp = SD_GET_XBUF(bp);
13234 	ASSERT(xp != NULL);
13235 
13236 #if defined(__i386) || defined(__amd64)
13237 	pktp = SD_GET_PKTP(bp);
13238 #endif
13239 
13240 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
13241 
13242 #if defined(__i386) || defined(__amd64)
13243 	/*
13244 	 * Note:x86: check for the "sdrestart failed" case.
13245 	 */
13246 	if (((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
13247 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
13248 	    (xp->xb_pktp->pkt_resid == 0)) {
13249 
13250 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
13251 			/*
13252 			 * Successfully set up next portion of cmd
13253 			 * transfer, try sending it
13254 			 */
13255 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
13256 			    NULL, NULL, 0, (clock_t)0, NULL);
13257 			sd_start_cmds(un, NULL);
13258 			return;	/* Note:x86: need a return here? */
13259 		}
13260 	}
13261 #endif
13262 
13263 	/*
13264 	 * If this is the failfast bp, clear it from un_failfast_bp. This
13265 	 * can happen if upon being re-tried the failfast bp either
13266 	 * succeeded or encountered another error (possibly even a different
13267 	 * error than the one that precipitated the failfast state, but in
13268 	 * that case it would have had to exhaust retries as well). Regardless,
13269 	 * this should not occur whenever the instance is in the active
13270 	 * failfast state.
13271 	 */
13272 	if (bp == un->un_failfast_bp) {
13273 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13274 		un->un_failfast_bp = NULL;
13275 	}
13276 
13277 	/*
13278 	 * Clear the failfast state upon successful completion of ANY cmd.
13279 	 */
13280 	if (bp->b_error == 0) {
13281 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13282 	}
13283 
13284 	/*
13285 	 * This is used if the command was retried one or more times. Show that
13286 	 * we are done with it, and allow processing of the waitq to resume.
13287 	 */
13288 	if (bp == un->un_retry_bp) {
13289 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13290 		    "sd_return_command: un:0x%p: "
13291 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13292 		un->un_retry_bp = NULL;
13293 		un->un_retry_statp = NULL;
13294 	}
13295 
13296 	SD_UPDATE_RDWR_STATS(un, bp);
13297 	SD_UPDATE_PARTITION_STATS(un, bp);
13298 
13299 	switch (un->un_state) {
13300 	case SD_STATE_SUSPENDED:
13301 		/*
13302 		 * Notify any threads waiting in sd_ddi_suspend() that
13303 		 * a command completion has occurred.
13304 		 */
13305 		cv_broadcast(&un->un_disk_busy_cv);
13306 		break;
13307 	default:
13308 		sd_start_cmds(un, NULL);
13309 		break;
13310 	}
13311 
13312 	/* Return this command up the iodone chain to its originator. */
13313 	mutex_exit(SD_MUTEX(un));
13314 
13315 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13316 	xp->xb_pktp = NULL;
13317 
13318 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13319 
13320 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13321 	mutex_enter(SD_MUTEX(un));
13322 
13323 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
13324 }
13325 
13326 
13327 /*
13328  *    Function: sd_return_failed_command
13329  *
13330  * Description: Command completion when an error occurred.
13331  *
13332  *     Context: May be called from interrupt context
13333  */
13334 
13335 static void
13336 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
13337 {
13338 	ASSERT(bp != NULL);
13339 	ASSERT(un != NULL);
13340 	ASSERT(mutex_owned(SD_MUTEX(un)));
13341 
13342 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13343 	    "sd_return_failed_command: entry\n");
13344 
13345 	/*
13346 	 * b_resid could already be nonzero due to a partial data
13347 	 * transfer, so do not change it here.
13348 	 */
13349 	SD_BIOERROR(bp, errcode);
13350 
13351 	sd_return_command(un, bp);
13352 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13353 	    "sd_return_failed_command: exit\n");
13354 }
13355 
13356 
13357 /*
13358  *    Function: sd_return_failed_command_no_restart
13359  *
13360  * Description: Same as sd_return_failed_command, but ensures that no
13361  *		call back into sd_start_cmds will be issued.
13362  *
13363  *     Context: May be called from interrupt context
13364  */
13365 
13366 static void
13367 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
13368 	int errcode)
13369 {
13370 	struct sd_xbuf *xp;
13371 
13372 	ASSERT(bp != NULL);
13373 	ASSERT(un != NULL);
13374 	ASSERT(mutex_owned(SD_MUTEX(un)));
13375 	xp = SD_GET_XBUF(bp);
13376 	ASSERT(xp != NULL);
13377 	ASSERT(errcode != 0);
13378 
13379 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13380 	    "sd_return_failed_command_no_restart: entry\n");
13381 
13382 	/*
13383 	 * b_resid could already be nonzero due to a partial data
13384 	 * transfer, so do not change it here.
13385 	 */
13386 	SD_BIOERROR(bp, errcode);
13387 
13388 	/*
13389 	 * If this is the failfast bp, clear it. This can happen if the
13390 	 * failfast bp encounterd a fatal error when we attempted to
13391 	 * re-try it (such as a scsi_transport(9F) failure).  However
13392 	 * we should NOT be in an active failfast state if the failfast
13393 	 * bp is not NULL.
13394 	 */
13395 	if (bp == un->un_failfast_bp) {
13396 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13397 		un->un_failfast_bp = NULL;
13398 	}
13399 
13400 	if (bp == un->un_retry_bp) {
13401 		/*
13402 		 * This command was retried one or more times. Show that we are
13403 		 * done with it, and allow processing of the waitq to resume.
13404 		 */
13405 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13406 		    "sd_return_failed_command_no_restart: "
13407 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13408 		un->un_retry_bp = NULL;
13409 		un->un_retry_statp = NULL;
13410 	}
13411 
13412 	SD_UPDATE_RDWR_STATS(un, bp);
13413 	SD_UPDATE_PARTITION_STATS(un, bp);
13414 
13415 	mutex_exit(SD_MUTEX(un));
13416 
13417 	if (xp->xb_pktp != NULL) {
13418 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13419 		xp->xb_pktp = NULL;
13420 	}
13421 
13422 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13423 
13424 	mutex_enter(SD_MUTEX(un));
13425 
13426 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13427 	    "sd_return_failed_command_no_restart: exit\n");
13428 }
13429 
13430 
13431 /*
13432  *    Function: sd_retry_command
13433  *
13434  * Description: queue up a command for retry, or (optionally) fail it
13435  *		if retry counts are exhausted.
13436  *
13437  *   Arguments: un - Pointer to the sd_lun struct for the target.
13438  *
13439  *		bp - Pointer to the buf for the command to be retried.
13440  *
13441  *		retry_check_flag - Flag to see which (if any) of the retry
13442  *		   counts should be decremented/checked. If the indicated
13443  *		   retry count is exhausted, then the command will not be
13444  *		   retried; it will be failed instead. This should use a
13445  *		   value equal to one of the following:
13446  *
13447  *			SD_RETRIES_NOCHECK
13448  *			SD_RESD_RETRIES_STANDARD
13449  *			SD_RETRIES_VICTIM
13450  *
13451  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
13452  *		   if the check should be made to see of FLAG_ISOLATE is set
13453  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
13454  *		   not retried, it is simply failed.
13455  *
13456  *		user_funcp - Ptr to function to call before dispatching the
13457  *		   command. May be NULL if no action needs to be performed.
13458  *		   (Primarily intended for printing messages.)
13459  *
13460  *		user_arg - Optional argument to be passed along to
13461  *		   the user_funcp call.
13462  *
13463  *		failure_code - errno return code to set in the bp if the
13464  *		   command is going to be failed.
13465  *
13466  *		retry_delay - Retry delay interval in (clock_t) units. May
13467  *		   be zero which indicates that the retry should be retried
13468  *		   immediately (ie, without an intervening delay).
13469  *
13470  *		statp - Ptr to kstat function to be updated if the command
13471  *		   is queued for a delayed retry. May be NULL if no kstat
13472  *		   update is desired.
13473  *
13474  *     Context: May be called from interrupt context.
13475  */
13476 
13477 static void
13478 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
13479 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int
13480 	code), void *user_arg, int failure_code,  clock_t retry_delay,
13481 	void (*statp)(kstat_io_t *))
13482 {
13483 	struct sd_xbuf	*xp;
13484 	struct scsi_pkt	*pktp;
13485 
13486 	ASSERT(un != NULL);
13487 	ASSERT(mutex_owned(SD_MUTEX(un)));
13488 	ASSERT(bp != NULL);
13489 	xp = SD_GET_XBUF(bp);
13490 	ASSERT(xp != NULL);
13491 	pktp = SD_GET_PKTP(bp);
13492 	ASSERT(pktp != NULL);
13493 
13494 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
13495 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
13496 
13497 	/*
13498 	 * If we are syncing or dumping, fail the command to avoid
13499 	 * recursively calling back into scsi_transport().
13500 	 */
13501 	if (ddi_in_panic()) {
13502 		goto fail_command_no_log;
13503 	}
13504 
13505 	/*
13506 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
13507 	 * log an error and fail the command.
13508 	 */
13509 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
13510 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
13511 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
13512 		sd_dump_memory(un, SD_LOG_IO, "CDB",
13513 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
13514 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
13515 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
13516 		goto fail_command;
13517 	}
13518 
13519 	/*
13520 	 * If we are suspended, then put the command onto head of the
13521 	 * wait queue since we don't want to start more commands, and
13522 	 * clear the un_retry_bp. Next time when we are resumed, will
13523 	 * handle the command in the wait queue.
13524 	 */
13525 	switch (un->un_state) {
13526 	case SD_STATE_SUSPENDED:
13527 	case SD_STATE_DUMPING:
13528 		bp->av_forw = un->un_waitq_headp;
13529 		un->un_waitq_headp = bp;
13530 		if (un->un_waitq_tailp == NULL) {
13531 			un->un_waitq_tailp = bp;
13532 		}
13533 		if (bp == un->un_retry_bp) {
13534 			un->un_retry_bp = NULL;
13535 			un->un_retry_statp = NULL;
13536 		}
13537 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13538 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
13539 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
13540 		return;
13541 	default:
13542 		break;
13543 	}
13544 
13545 	/*
13546 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
13547 	 * is set; if it is then we do not want to retry the command.
13548 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
13549 	 */
13550 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
13551 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
13552 			goto fail_command;
13553 		}
13554 	}
13555 
13556 
13557 	/*
13558 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
13559 	 * command timeout or a selection timeout has occurred. This means
13560 	 * that we were unable to establish an kind of communication with
13561 	 * the target, and subsequent retries and/or commands are likely
13562 	 * to encounter similar results and take a long time to complete.
13563 	 *
13564 	 * If this is a failfast error condition, we need to update the
13565 	 * failfast state, even if this bp does not have B_FAILFAST set.
13566 	 */
13567 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
13568 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
13569 			ASSERT(un->un_failfast_bp == NULL);
13570 			/*
13571 			 * If we are already in the active failfast state, and
13572 			 * another failfast error condition has been detected,
13573 			 * then fail this command if it has B_FAILFAST set.
13574 			 * If B_FAILFAST is clear, then maintain the legacy
13575 			 * behavior of retrying heroically, even tho this will
13576 			 * take a lot more time to fail the command.
13577 			 */
13578 			if (bp->b_flags & B_FAILFAST) {
13579 				goto fail_command;
13580 			}
13581 		} else {
13582 			/*
13583 			 * We're not in the active failfast state, but we
13584 			 * have a failfast error condition, so we must begin
13585 			 * transition to the next state. We do this regardless
13586 			 * of whether or not this bp has B_FAILFAST set.
13587 			 */
13588 			if (un->un_failfast_bp == NULL) {
13589 				/*
13590 				 * This is the first bp to meet a failfast
13591 				 * condition so save it on un_failfast_bp &
13592 				 * do normal retry processing. Do not enter
13593 				 * active failfast state yet. This marks
13594 				 * entry into the "failfast pending" state.
13595 				 */
13596 				un->un_failfast_bp = bp;
13597 
13598 			} else if (un->un_failfast_bp == bp) {
13599 				/*
13600 				 * This is the second time *this* bp has
13601 				 * encountered a failfast error condition,
13602 				 * so enter active failfast state & flush
13603 				 * queues as appropriate.
13604 				 */
13605 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
13606 				un->un_failfast_bp = NULL;
13607 				sd_failfast_flushq(un);
13608 
13609 				/*
13610 				 * Fail this bp now if B_FAILFAST set;
13611 				 * otherwise continue with retries. (It would
13612 				 * be pretty ironic if this bp succeeded on a
13613 				 * subsequent retry after we just flushed all
13614 				 * the queues).
13615 				 */
13616 				if (bp->b_flags & B_FAILFAST) {
13617 					goto fail_command;
13618 				}
13619 
13620 #if !defined(lint) && !defined(__lint)
13621 			} else {
13622 				/*
13623 				 * If neither of the preceeding conditionals
13624 				 * was true, it means that there is some
13625 				 * *other* bp that has met an inital failfast
13626 				 * condition and is currently either being
13627 				 * retried or is waiting to be retried. In
13628 				 * that case we should perform normal retry
13629 				 * processing on *this* bp, since there is a
13630 				 * chance that the current failfast condition
13631 				 * is transient and recoverable. If that does
13632 				 * not turn out to be the case, then retries
13633 				 * will be cleared when the wait queue is
13634 				 * flushed anyway.
13635 				 */
13636 #endif
13637 			}
13638 		}
13639 	} else {
13640 		/*
13641 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
13642 		 * likely were able to at least establish some level of
13643 		 * communication with the target and subsequent commands
13644 		 * and/or retries are likely to get through to the target,
13645 		 * In this case we want to be aggressive about clearing
13646 		 * the failfast state. Note that this does not affect
13647 		 * the "failfast pending" condition.
13648 		 */
13649 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13650 	}
13651 
13652 
13653 	/*
13654 	 * Check the specified retry count to see if we can still do
13655 	 * any retries with this pkt before we should fail it.
13656 	 */
13657 	switch (retry_check_flag & SD_RETRIES_MASK) {
13658 	case SD_RETRIES_VICTIM:
13659 		/*
13660 		 * Check the victim retry count. If exhausted, then fall
13661 		 * thru & check against the standard retry count.
13662 		 */
13663 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
13664 			/* Increment count & proceed with the retry */
13665 			xp->xb_victim_retry_count++;
13666 			break;
13667 		}
13668 		/* Victim retries exhausted, fall back to std. retries... */
13669 		/* FALLTHRU */
13670 
13671 	case SD_RETRIES_STANDARD:
13672 		if (xp->xb_retry_count >= un->un_retry_count) {
13673 			/* Retries exhausted, fail the command */
13674 			SD_TRACE(SD_LOG_IO_CORE, un,
13675 			    "sd_retry_command: retries exhausted!\n");
13676 			/*
13677 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
13678 			 * commands with nonzero pkt_resid.
13679 			 */
13680 			if ((pktp->pkt_reason == CMD_CMPLT) &&
13681 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
13682 			    (pktp->pkt_resid != 0)) {
13683 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
13684 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
13685 					SD_UPDATE_B_RESID(bp, pktp);
13686 				}
13687 			}
13688 			goto fail_command;
13689 		}
13690 		xp->xb_retry_count++;
13691 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13692 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13693 		break;
13694 
13695 	case SD_RETRIES_UA:
13696 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
13697 			/* Retries exhausted, fail the command */
13698 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13699 			    "Unit Attention retries exhausted. "
13700 			    "Check the target.\n");
13701 			goto fail_command;
13702 		}
13703 		xp->xb_ua_retry_count++;
13704 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13705 		    "sd_retry_command: retry count:%d\n",
13706 		    xp->xb_ua_retry_count);
13707 		break;
13708 
13709 	case SD_RETRIES_BUSY:
13710 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
13711 			/* Retries exhausted, fail the command */
13712 			SD_TRACE(SD_LOG_IO_CORE, un,
13713 			    "sd_retry_command: retries exhausted!\n");
13714 			goto fail_command;
13715 		}
13716 		xp->xb_retry_count++;
13717 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13718 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13719 		break;
13720 
13721 	case SD_RETRIES_NOCHECK:
13722 	default:
13723 		/* No retry count to check. Just proceed with the retry */
13724 		break;
13725 	}
13726 
13727 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13728 
13729 	/*
13730 	 * If we were given a zero timeout, we must attempt to retry the
13731 	 * command immediately (ie, without a delay).
13732 	 */
13733 	if (retry_delay == 0) {
13734 		/*
13735 		 * Check some limiting conditions to see if we can actually
13736 		 * do the immediate retry.  If we cannot, then we must
13737 		 * fall back to queueing up a delayed retry.
13738 		 */
13739 		if (un->un_ncmds_in_transport >= un->un_throttle) {
13740 			/*
13741 			 * We are at the throttle limit for the target,
13742 			 * fall back to delayed retry.
13743 			 */
13744 			retry_delay = SD_BSY_TIMEOUT;
13745 			statp = kstat_waitq_enter;
13746 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13747 			    "sd_retry_command: immed. retry hit "
13748 			    "throttle!\n");
13749 		} else {
13750 			/*
13751 			 * We're clear to proceed with the immediate retry.
13752 			 * First call the user-provided function (if any)
13753 			 */
13754 			if (user_funcp != NULL) {
13755 				(*user_funcp)(un, bp, user_arg,
13756 				    SD_IMMEDIATE_RETRY_ISSUED);
13757 #ifdef __lock_lint
13758 				sd_print_incomplete_msg(un, bp, user_arg,
13759 				    SD_IMMEDIATE_RETRY_ISSUED);
13760 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
13761 				    SD_IMMEDIATE_RETRY_ISSUED);
13762 				sd_print_sense_failed_msg(un, bp, user_arg,
13763 				    SD_IMMEDIATE_RETRY_ISSUED);
13764 #endif
13765 			}
13766 
13767 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13768 			    "sd_retry_command: issuing immediate retry\n");
13769 
13770 			/*
13771 			 * Call sd_start_cmds() to transport the command to
13772 			 * the target.
13773 			 */
13774 			sd_start_cmds(un, bp);
13775 
13776 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13777 			    "sd_retry_command exit\n");
13778 			return;
13779 		}
13780 	}
13781 
13782 	/*
13783 	 * Set up to retry the command after a delay.
13784 	 * First call the user-provided function (if any)
13785 	 */
13786 	if (user_funcp != NULL) {
13787 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
13788 	}
13789 
13790 	sd_set_retry_bp(un, bp, retry_delay, statp);
13791 
13792 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
13793 	return;
13794 
13795 fail_command:
13796 
13797 	if (user_funcp != NULL) {
13798 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
13799 	}
13800 
13801 fail_command_no_log:
13802 
13803 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13804 	    "sd_retry_command: returning failed command\n");
13805 
13806 	sd_return_failed_command(un, bp, failure_code);
13807 
13808 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
13809 }
13810 
13811 
13812 /*
13813  *    Function: sd_set_retry_bp
13814  *
13815  * Description: Set up the given bp for retry.
13816  *
13817  *   Arguments: un - ptr to associated softstate
13818  *		bp - ptr to buf(9S) for the command
13819  *		retry_delay - time interval before issuing retry (may be 0)
13820  *		statp - optional pointer to kstat function
13821  *
13822  *     Context: May be called under interrupt context
13823  */
13824 
13825 static void
13826 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
13827 	void (*statp)(kstat_io_t *))
13828 {
13829 	ASSERT(un != NULL);
13830 	ASSERT(mutex_owned(SD_MUTEX(un)));
13831 	ASSERT(bp != NULL);
13832 
13833 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
13834 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
13835 
13836 	/*
13837 	 * Indicate that the command is being retried. This will not allow any
13838 	 * other commands on the wait queue to be transported to the target
13839 	 * until this command has been completed (success or failure). The
13840 	 * "retry command" is not transported to the target until the given
13841 	 * time delay expires, unless the user specified a 0 retry_delay.
13842 	 *
13843 	 * Note: the timeout(9F) callback routine is what actually calls
13844 	 * sd_start_cmds() to transport the command, with the exception of a
13845 	 * zero retry_delay. The only current implementor of a zero retry delay
13846 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
13847 	 */
13848 	if (un->un_retry_bp == NULL) {
13849 		ASSERT(un->un_retry_statp == NULL);
13850 		un->un_retry_bp = bp;
13851 
13852 		/*
13853 		 * If the user has not specified a delay the command should
13854 		 * be queued and no timeout should be scheduled.
13855 		 */
13856 		if (retry_delay == 0) {
13857 			/*
13858 			 * Save the kstat pointer that will be used in the
13859 			 * call to SD_UPDATE_KSTATS() below, so that
13860 			 * sd_start_cmds() can correctly decrement the waitq
13861 			 * count when it is time to transport this command.
13862 			 */
13863 			un->un_retry_statp = statp;
13864 			goto done;
13865 		}
13866 	}
13867 
13868 	if (un->un_retry_bp == bp) {
13869 		/*
13870 		 * Save the kstat pointer that will be used in the call to
13871 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
13872 		 * correctly decrement the waitq count when it is time to
13873 		 * transport this command.
13874 		 */
13875 		un->un_retry_statp = statp;
13876 
13877 		/*
13878 		 * Schedule a timeout if:
13879 		 *   1) The user has specified a delay.
13880 		 *   2) There is not a START_STOP_UNIT callback pending.
13881 		 *
13882 		 * If no delay has been specified, then it is up to the caller
13883 		 * to ensure that IO processing continues without stalling.
13884 		 * Effectively, this means that the caller will issue the
13885 		 * required call to sd_start_cmds(). The START_STOP_UNIT
13886 		 * callback does this after the START STOP UNIT command has
13887 		 * completed. In either of these cases we should not schedule
13888 		 * a timeout callback here.  Also don't schedule the timeout if
13889 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
13890 		 */
13891 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
13892 		    (un->un_direct_priority_timeid == NULL)) {
13893 			un->un_retry_timeid =
13894 			    timeout(sd_start_retry_command, un, retry_delay);
13895 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13896 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
13897 			    " bp:0x%p un_retry_timeid:0x%p\n",
13898 			    un, bp, un->un_retry_timeid);
13899 		}
13900 	} else {
13901 		/*
13902 		 * We only get in here if there is already another command
13903 		 * waiting to be retried.  In this case, we just put the
13904 		 * given command onto the wait queue, so it can be transported
13905 		 * after the current retry command has completed.
13906 		 *
13907 		 * Also we have to make sure that if the command at the head
13908 		 * of the wait queue is the un_failfast_bp, that we do not
13909 		 * put ahead of it any other commands that are to be retried.
13910 		 */
13911 		if ((un->un_failfast_bp != NULL) &&
13912 		    (un->un_failfast_bp == un->un_waitq_headp)) {
13913 			/*
13914 			 * Enqueue this command AFTER the first command on
13915 			 * the wait queue (which is also un_failfast_bp).
13916 			 */
13917 			bp->av_forw = un->un_waitq_headp->av_forw;
13918 			un->un_waitq_headp->av_forw = bp;
13919 			if (un->un_waitq_headp == un->un_waitq_tailp) {
13920 				un->un_waitq_tailp = bp;
13921 			}
13922 		} else {
13923 			/* Enqueue this command at the head of the waitq. */
13924 			bp->av_forw = un->un_waitq_headp;
13925 			un->un_waitq_headp = bp;
13926 			if (un->un_waitq_tailp == NULL) {
13927 				un->un_waitq_tailp = bp;
13928 			}
13929 		}
13930 
13931 		if (statp == NULL) {
13932 			statp = kstat_waitq_enter;
13933 		}
13934 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13935 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
13936 	}
13937 
13938 done:
13939 	if (statp != NULL) {
13940 		SD_UPDATE_KSTATS(un, statp, bp);
13941 	}
13942 
13943 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13944 	    "sd_set_retry_bp: exit un:0x%p\n", un);
13945 }
13946 
13947 
13948 /*
13949  *    Function: sd_start_retry_command
13950  *
13951  * Description: Start the command that has been waiting on the target's
13952  *		retry queue.  Called from timeout(9F) context after the
13953  *		retry delay interval has expired.
13954  *
13955  *   Arguments: arg - pointer to associated softstate for the device.
13956  *
13957  *     Context: timeout(9F) thread context.  May not sleep.
13958  */
13959 
13960 static void
13961 sd_start_retry_command(void *arg)
13962 {
13963 	struct sd_lun *un = arg;
13964 
13965 	ASSERT(un != NULL);
13966 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13967 
13968 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13969 	    "sd_start_retry_command: entry\n");
13970 
13971 	mutex_enter(SD_MUTEX(un));
13972 
13973 	un->un_retry_timeid = NULL;
13974 
13975 	if (un->un_retry_bp != NULL) {
13976 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13977 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
13978 		    un, un->un_retry_bp);
13979 		sd_start_cmds(un, un->un_retry_bp);
13980 	}
13981 
13982 	mutex_exit(SD_MUTEX(un));
13983 
13984 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13985 	    "sd_start_retry_command: exit\n");
13986 }
13987 
13988 
13989 /*
13990  *    Function: sd_start_direct_priority_command
13991  *
13992  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
13993  *		received TRAN_BUSY when we called scsi_transport() to send it
13994  *		to the underlying HBA. This function is called from timeout(9F)
13995  *		context after the delay interval has expired.
13996  *
13997  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
13998  *
13999  *     Context: timeout(9F) thread context.  May not sleep.
14000  */
14001 
14002 static void
14003 sd_start_direct_priority_command(void *arg)
14004 {
14005 	struct buf	*priority_bp = arg;
14006 	struct sd_lun	*un;
14007 
14008 	ASSERT(priority_bp != NULL);
14009 	un = SD_GET_UN(priority_bp);
14010 	ASSERT(un != NULL);
14011 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14012 
14013 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14014 	    "sd_start_direct_priority_command: entry\n");
14015 
14016 	mutex_enter(SD_MUTEX(un));
14017 	un->un_direct_priority_timeid = NULL;
14018 	sd_start_cmds(un, priority_bp);
14019 	mutex_exit(SD_MUTEX(un));
14020 
14021 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14022 	    "sd_start_direct_priority_command: exit\n");
14023 }
14024 
14025 
14026 /*
14027  *    Function: sd_send_request_sense_command
14028  *
14029  * Description: Sends a REQUEST SENSE command to the target
14030  *
14031  *     Context: May be called from interrupt context.
14032  */
14033 
14034 static void
14035 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
14036 	struct scsi_pkt *pktp)
14037 {
14038 	ASSERT(bp != NULL);
14039 	ASSERT(un != NULL);
14040 	ASSERT(mutex_owned(SD_MUTEX(un)));
14041 
14042 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
14043 	    "entry: buf:0x%p\n", bp);
14044 
14045 	/*
14046 	 * If we are syncing or dumping, then fail the command to avoid a
14047 	 * recursive callback into scsi_transport(). Also fail the command
14048 	 * if we are suspended (legacy behavior).
14049 	 */
14050 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
14051 	    (un->un_state == SD_STATE_DUMPING)) {
14052 		sd_return_failed_command(un, bp, EIO);
14053 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14054 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
14055 		return;
14056 	}
14057 
14058 	/*
14059 	 * Retry the failed command and don't issue the request sense if:
14060 	 *    1) the sense buf is busy
14061 	 *    2) we have 1 or more outstanding commands on the target
14062 	 *    (the sense data will be cleared or invalidated any way)
14063 	 *
14064 	 * Note: There could be an issue with not checking a retry limit here,
14065 	 * the problem is determining which retry limit to check.
14066 	 */
14067 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
14068 		/* Don't retry if the command is flagged as non-retryable */
14069 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
14070 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
14071 			    NULL, NULL, 0, SD_BSY_TIMEOUT, kstat_waitq_enter);
14072 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14073 			    "sd_send_request_sense_command: "
14074 			    "at full throttle, retrying exit\n");
14075 		} else {
14076 			sd_return_failed_command(un, bp, EIO);
14077 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14078 			    "sd_send_request_sense_command: "
14079 			    "at full throttle, non-retryable exit\n");
14080 		}
14081 		return;
14082 	}
14083 
14084 	sd_mark_rqs_busy(un, bp);
14085 	sd_start_cmds(un, un->un_rqs_bp);
14086 
14087 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14088 	    "sd_send_request_sense_command: exit\n");
14089 }
14090 
14091 
14092 /*
14093  *    Function: sd_mark_rqs_busy
14094  *
14095  * Description: Indicate that the request sense bp for this instance is
14096  *		in use.
14097  *
14098  *     Context: May be called under interrupt context
14099  */
14100 
14101 static void
14102 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
14103 {
14104 	struct sd_xbuf	*sense_xp;
14105 
14106 	ASSERT(un != NULL);
14107 	ASSERT(bp != NULL);
14108 	ASSERT(mutex_owned(SD_MUTEX(un)));
14109 	ASSERT(un->un_sense_isbusy == 0);
14110 
14111 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
14112 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
14113 
14114 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
14115 	ASSERT(sense_xp != NULL);
14116 
14117 	SD_INFO(SD_LOG_IO, un,
14118 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
14119 
14120 	ASSERT(sense_xp->xb_pktp != NULL);
14121 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
14122 	    == (FLAG_SENSING | FLAG_HEAD));
14123 
14124 	un->un_sense_isbusy = 1;
14125 	un->un_rqs_bp->b_resid = 0;
14126 	sense_xp->xb_pktp->pkt_resid  = 0;
14127 	sense_xp->xb_pktp->pkt_reason = 0;
14128 
14129 	/* So we can get back the bp at interrupt time! */
14130 	sense_xp->xb_sense_bp = bp;
14131 
14132 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
14133 
14134 	/*
14135 	 * Mark this buf as awaiting sense data. (This is already set in
14136 	 * the pkt_flags for the RQS packet.)
14137 	 */
14138 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
14139 
14140 	sense_xp->xb_retry_count	= 0;
14141 	sense_xp->xb_victim_retry_count = 0;
14142 	sense_xp->xb_ua_retry_count	= 0;
14143 	sense_xp->xb_nr_retry_count 	= 0;
14144 	sense_xp->xb_dma_resid  = 0;
14145 
14146 	/* Clean up the fields for auto-request sense */
14147 	sense_xp->xb_sense_status = 0;
14148 	sense_xp->xb_sense_state  = 0;
14149 	sense_xp->xb_sense_resid  = 0;
14150 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
14151 
14152 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
14153 }
14154 
14155 
14156 /*
14157  *    Function: sd_mark_rqs_idle
14158  *
14159  * Description: SD_MUTEX must be held continuously through this routine
14160  *		to prevent reuse of the rqs struct before the caller can
14161  *		complete it's processing.
14162  *
14163  * Return Code: Pointer to the RQS buf
14164  *
14165  *     Context: May be called under interrupt context
14166  */
14167 
14168 static struct buf *
14169 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
14170 {
14171 	struct buf *bp;
14172 	ASSERT(un != NULL);
14173 	ASSERT(sense_xp != NULL);
14174 	ASSERT(mutex_owned(SD_MUTEX(un)));
14175 	ASSERT(un->un_sense_isbusy != 0);
14176 
14177 	un->un_sense_isbusy = 0;
14178 	bp = sense_xp->xb_sense_bp;
14179 	sense_xp->xb_sense_bp = NULL;
14180 
14181 	/* This pkt is no longer interested in getting sense data */
14182 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
14183 
14184 	return (bp);
14185 }
14186 
14187 
14188 
14189 /*
14190  *    Function: sd_alloc_rqs
14191  *
14192  * Description: Set up the unit to receive auto request sense data
14193  *
14194  * Return Code: DDI_SUCCESS or DDI_FAILURE
14195  *
14196  *     Context: Called under attach(9E) context
14197  */
14198 
14199 static int
14200 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
14201 {
14202 	struct sd_xbuf *xp;
14203 
14204 	ASSERT(un != NULL);
14205 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14206 	ASSERT(un->un_rqs_bp == NULL);
14207 	ASSERT(un->un_rqs_pktp == NULL);
14208 
14209 	/*
14210 	 * First allocate the required buf and scsi_pkt structs, then set up
14211 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
14212 	 */
14213 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
14214 	    SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
14215 	if (un->un_rqs_bp == NULL) {
14216 		return (DDI_FAILURE);
14217 	}
14218 
14219 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
14220 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
14221 
14222 	if (un->un_rqs_pktp == NULL) {
14223 		sd_free_rqs(un);
14224 		return (DDI_FAILURE);
14225 	}
14226 
14227 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
14228 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
14229 	    SCMD_REQUEST_SENSE, 0, SENSE_LENGTH, 0);
14230 
14231 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
14232 
14233 	/* Set up the other needed members in the ARQ scsi_pkt. */
14234 	un->un_rqs_pktp->pkt_comp   = sdintr;
14235 	un->un_rqs_pktp->pkt_time   = sd_io_time;
14236 	un->un_rqs_pktp->pkt_flags |=
14237 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
14238 
14239 	/*
14240 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
14241 	 * provide any intpkt, destroypkt routines as we take care of
14242 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
14243 	 */
14244 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14245 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
14246 	xp->xb_pktp = un->un_rqs_pktp;
14247 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
14248 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
14249 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
14250 
14251 	/*
14252 	 * Save the pointer to the request sense private bp so it can
14253 	 * be retrieved in sdintr.
14254 	 */
14255 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
14256 	ASSERT(un->un_rqs_bp->b_private == xp);
14257 
14258 	/*
14259 	 * See if the HBA supports auto-request sense for the specified
14260 	 * target/lun. If it does, then try to enable it (if not already
14261 	 * enabled).
14262 	 *
14263 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
14264 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
14265 	 * return success.  However, in both of these cases ARQ is always
14266 	 * enabled and scsi_ifgetcap will always return true. The best approach
14267 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
14268 	 *
14269 	 * The 3rd case is the HBA (adp) always return enabled on
14270 	 * scsi_ifgetgetcap even when it's not enable, the best approach
14271 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
14272 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
14273 	 */
14274 
14275 	if (un->un_f_is_fibre == TRUE) {
14276 		un->un_f_arq_enabled = TRUE;
14277 	} else {
14278 #if defined(__i386) || defined(__amd64)
14279 		/*
14280 		 * Circumvent the Adaptec bug, remove this code when
14281 		 * the bug is fixed
14282 		 */
14283 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
14284 #endif
14285 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
14286 		case 0:
14287 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14288 			    "sd_alloc_rqs: HBA supports ARQ\n");
14289 			/*
14290 			 * ARQ is supported by this HBA but currently is not
14291 			 * enabled. Attempt to enable it and if successful then
14292 			 * mark this instance as ARQ enabled.
14293 			 */
14294 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
14295 			    == 1) {
14296 				/* Successfully enabled ARQ in the HBA */
14297 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14298 				    "sd_alloc_rqs: ARQ enabled\n");
14299 				un->un_f_arq_enabled = TRUE;
14300 			} else {
14301 				/* Could not enable ARQ in the HBA */
14302 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14303 				    "sd_alloc_rqs: failed ARQ enable\n");
14304 				un->un_f_arq_enabled = FALSE;
14305 			}
14306 			break;
14307 		case 1:
14308 			/*
14309 			 * ARQ is supported by this HBA and is already enabled.
14310 			 * Just mark ARQ as enabled for this instance.
14311 			 */
14312 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14313 			    "sd_alloc_rqs: ARQ already enabled\n");
14314 			un->un_f_arq_enabled = TRUE;
14315 			break;
14316 		default:
14317 			/*
14318 			 * ARQ is not supported by this HBA; disable it for this
14319 			 * instance.
14320 			 */
14321 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14322 			    "sd_alloc_rqs: HBA does not support ARQ\n");
14323 			un->un_f_arq_enabled = FALSE;
14324 			break;
14325 		}
14326 	}
14327 
14328 	return (DDI_SUCCESS);
14329 }
14330 
14331 
14332 /*
14333  *    Function: sd_free_rqs
14334  *
14335  * Description: Cleanup for the pre-instance RQS command.
14336  *
14337  *     Context: Kernel thread context
14338  */
14339 
14340 static void
14341 sd_free_rqs(struct sd_lun *un)
14342 {
14343 	ASSERT(un != NULL);
14344 
14345 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
14346 
14347 	/*
14348 	 * If consistent memory is bound to a scsi_pkt, the pkt
14349 	 * has to be destroyed *before* freeing the consistent memory.
14350 	 * Don't change the sequence of this operations.
14351 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
14352 	 * after it was freed in scsi_free_consistent_buf().
14353 	 */
14354 	if (un->un_rqs_pktp != NULL) {
14355 		scsi_destroy_pkt(un->un_rqs_pktp);
14356 		un->un_rqs_pktp = NULL;
14357 	}
14358 
14359 	if (un->un_rqs_bp != NULL) {
14360 		kmem_free(SD_GET_XBUF(un->un_rqs_bp), sizeof (struct sd_xbuf));
14361 		scsi_free_consistent_buf(un->un_rqs_bp);
14362 		un->un_rqs_bp = NULL;
14363 	}
14364 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
14365 }
14366 
14367 
14368 
14369 /*
14370  *    Function: sd_reduce_throttle
14371  *
14372  * Description: Reduces the maximum # of outstanding commands on a
14373  *		target to the current number of outstanding commands.
14374  *		Queues a tiemout(9F) callback to restore the limit
14375  *		after a specified interval has elapsed.
14376  *		Typically used when we get a TRAN_BUSY return code
14377  *		back from scsi_transport().
14378  *
14379  *   Arguments: un - ptr to the sd_lun softstate struct
14380  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
14381  *
14382  *     Context: May be called from interrupt context
14383  */
14384 
14385 static void
14386 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
14387 {
14388 	ASSERT(un != NULL);
14389 	ASSERT(mutex_owned(SD_MUTEX(un)));
14390 	ASSERT(un->un_ncmds_in_transport >= 0);
14391 
14392 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14393 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
14394 	    un, un->un_throttle, un->un_ncmds_in_transport);
14395 
14396 	if (un->un_throttle > 1) {
14397 		if (un->un_f_use_adaptive_throttle == TRUE) {
14398 			switch (throttle_type) {
14399 			case SD_THROTTLE_TRAN_BUSY:
14400 				if (un->un_busy_throttle == 0) {
14401 					un->un_busy_throttle = un->un_throttle;
14402 				}
14403 				break;
14404 			case SD_THROTTLE_QFULL:
14405 				un->un_busy_throttle = 0;
14406 				break;
14407 			default:
14408 				ASSERT(FALSE);
14409 			}
14410 
14411 			if (un->un_ncmds_in_transport > 0) {
14412 				un->un_throttle = un->un_ncmds_in_transport;
14413 			}
14414 
14415 		} else {
14416 			if (un->un_ncmds_in_transport == 0) {
14417 				un->un_throttle = 1;
14418 			} else {
14419 				un->un_throttle = un->un_ncmds_in_transport;
14420 			}
14421 		}
14422 	}
14423 
14424 	/* Reschedule the timeout if none is currently active */
14425 	if (un->un_reset_throttle_timeid == NULL) {
14426 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
14427 		    un, SD_THROTTLE_RESET_INTERVAL);
14428 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14429 		    "sd_reduce_throttle: timeout scheduled!\n");
14430 	}
14431 
14432 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14433 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14434 }
14435 
14436 
14437 
14438 /*
14439  *    Function: sd_restore_throttle
14440  *
14441  * Description: Callback function for timeout(9F).  Resets the current
14442  *		value of un->un_throttle to its default.
14443  *
14444  *   Arguments: arg - pointer to associated softstate for the device.
14445  *
14446  *     Context: May be called from interrupt context
14447  */
14448 
14449 static void
14450 sd_restore_throttle(void *arg)
14451 {
14452 	struct sd_lun	*un = arg;
14453 
14454 	ASSERT(un != NULL);
14455 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14456 
14457 	mutex_enter(SD_MUTEX(un));
14458 
14459 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14460 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14461 
14462 	un->un_reset_throttle_timeid = NULL;
14463 
14464 	if (un->un_f_use_adaptive_throttle == TRUE) {
14465 		/*
14466 		 * If un_busy_throttle is nonzero, then it contains the
14467 		 * value that un_throttle was when we got a TRAN_BUSY back
14468 		 * from scsi_transport(). We want to revert back to this
14469 		 * value.
14470 		 *
14471 		 * In the QFULL case, the throttle limit will incrementally
14472 		 * increase until it reaches max throttle.
14473 		 */
14474 		if (un->un_busy_throttle > 0) {
14475 			un->un_throttle = un->un_busy_throttle;
14476 			un->un_busy_throttle = 0;
14477 		} else {
14478 			/*
14479 			 * increase throttle by 10% open gate slowly, schedule
14480 			 * another restore if saved throttle has not been
14481 			 * reached
14482 			 */
14483 			short throttle;
14484 			if (sd_qfull_throttle_enable) {
14485 				throttle = un->un_throttle +
14486 				    max((un->un_throttle / 10), 1);
14487 				un->un_throttle =
14488 				    (throttle < un->un_saved_throttle) ?
14489 				    throttle : un->un_saved_throttle;
14490 				if (un->un_throttle < un->un_saved_throttle) {
14491 					un->un_reset_throttle_timeid =
14492 					    timeout(sd_restore_throttle,
14493 					    un,
14494 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
14495 				}
14496 			}
14497 		}
14498 
14499 		/*
14500 		 * If un_throttle has fallen below the low-water mark, we
14501 		 * restore the maximum value here (and allow it to ratchet
14502 		 * down again if necessary).
14503 		 */
14504 		if (un->un_throttle < un->un_min_throttle) {
14505 			un->un_throttle = un->un_saved_throttle;
14506 		}
14507 	} else {
14508 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14509 		    "restoring limit from 0x%x to 0x%x\n",
14510 		    un->un_throttle, un->un_saved_throttle);
14511 		un->un_throttle = un->un_saved_throttle;
14512 	}
14513 
14514 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14515 	    "sd_restore_throttle: calling sd_start_cmds!\n");
14516 
14517 	sd_start_cmds(un, NULL);
14518 
14519 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14520 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
14521 	    un, un->un_throttle);
14522 
14523 	mutex_exit(SD_MUTEX(un));
14524 
14525 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
14526 }
14527 
14528 /*
14529  *    Function: sdrunout
14530  *
14531  * Description: Callback routine for scsi_init_pkt when a resource allocation
14532  *		fails.
14533  *
14534  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
14535  *		soft state instance.
14536  *
14537  * Return Code: The scsi_init_pkt routine allows for the callback function to
14538  *		return a 0 indicating the callback should be rescheduled or a 1
14539  *		indicating not to reschedule. This routine always returns 1
14540  *		because the driver always provides a callback function to
14541  *		scsi_init_pkt. This results in a callback always being scheduled
14542  *		(via the scsi_init_pkt callback implementation) if a resource
14543  *		failure occurs.
14544  *
14545  *     Context: This callback function may not block or call routines that block
14546  *
14547  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
14548  *		request persisting at the head of the list which cannot be
14549  *		satisfied even after multiple retries. In the future the driver
14550  *		may implement some time of maximum runout count before failing
14551  *		an I/O.
14552  */
14553 
14554 static int
14555 sdrunout(caddr_t arg)
14556 {
14557 	struct sd_lun	*un = (struct sd_lun *)arg;
14558 
14559 	ASSERT(un != NULL);
14560 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14561 
14562 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
14563 
14564 	mutex_enter(SD_MUTEX(un));
14565 	sd_start_cmds(un, NULL);
14566 	mutex_exit(SD_MUTEX(un));
14567 	/*
14568 	 * This callback routine always returns 1 (i.e. do not reschedule)
14569 	 * because we always specify sdrunout as the callback handler for
14570 	 * scsi_init_pkt inside the call to sd_start_cmds.
14571 	 */
14572 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
14573 	return (1);
14574 }
14575 
14576 
14577 /*
14578  *    Function: sdintr
14579  *
14580  * Description: Completion callback routine for scsi_pkt(9S) structs
14581  *		sent to the HBA driver via scsi_transport(9F).
14582  *
14583  *     Context: Interrupt context
14584  */
14585 
14586 static void
14587 sdintr(struct scsi_pkt *pktp)
14588 {
14589 	struct buf	*bp;
14590 	struct sd_xbuf	*xp;
14591 	struct sd_lun	*un;
14592 
14593 	ASSERT(pktp != NULL);
14594 	bp = (struct buf *)pktp->pkt_private;
14595 	ASSERT(bp != NULL);
14596 	xp = SD_GET_XBUF(bp);
14597 	ASSERT(xp != NULL);
14598 	ASSERT(xp->xb_pktp != NULL);
14599 	un = SD_GET_UN(bp);
14600 	ASSERT(un != NULL);
14601 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14602 
14603 #ifdef SD_FAULT_INJECTION
14604 
14605 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
14606 	/* SD FaultInjection */
14607 	sd_faultinjection(pktp);
14608 
14609 #endif /* SD_FAULT_INJECTION */
14610 
14611 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
14612 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
14613 
14614 	mutex_enter(SD_MUTEX(un));
14615 
14616 	/* Reduce the count of the #commands currently in transport */
14617 	un->un_ncmds_in_transport--;
14618 	ASSERT(un->un_ncmds_in_transport >= 0);
14619 
14620 	/* Increment counter to indicate that the callback routine is active */
14621 	un->un_in_callback++;
14622 
14623 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14624 
14625 #ifdef	SDDEBUG
14626 	if (bp == un->un_retry_bp) {
14627 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
14628 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
14629 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
14630 	}
14631 #endif
14632 
14633 	/*
14634 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
14635 	 * state if needed.
14636 	 */
14637 	if (pktp->pkt_reason == CMD_DEV_GONE) {
14638 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
14639 		    "Device is gone\n");
14640 		if (un->un_mediastate != DKIO_DEV_GONE) {
14641 			un->un_mediastate = DKIO_DEV_GONE;
14642 			cv_broadcast(&un->un_state_cv);
14643 		}
14644 		sd_return_failed_command(un, bp, EIO);
14645 		goto exit;
14646 	}
14647 
14648 	/*
14649 	 * First see if the pkt has auto-request sense data with it....
14650 	 * Look at the packet state first so we don't take a performance
14651 	 * hit looking at the arq enabled flag unless absolutely necessary.
14652 	 */
14653 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
14654 	    (un->un_f_arq_enabled == TRUE)) {
14655 		/*
14656 		 * The HBA did an auto request sense for this command so check
14657 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
14658 		 * driver command that should not be retried.
14659 		 */
14660 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
14661 			/*
14662 			 * Save the relevant sense info into the xp for the
14663 			 * original cmd.
14664 			 */
14665 			struct scsi_arq_status *asp;
14666 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
14667 			xp->xb_sense_status =
14668 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
14669 			xp->xb_sense_state  = asp->sts_rqpkt_state;
14670 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
14671 			bcopy(&asp->sts_sensedata, xp->xb_sense_data,
14672 			    min(sizeof (struct scsi_extended_sense),
14673 			    SENSE_LENGTH));
14674 
14675 			/* fail the command */
14676 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14677 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
14678 			sd_return_failed_command(un, bp, EIO);
14679 			goto exit;
14680 		}
14681 
14682 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
14683 		/*
14684 		 * We want to either retry or fail this command, so free
14685 		 * the DMA resources here.  If we retry the command then
14686 		 * the DMA resources will be reallocated in sd_start_cmds().
14687 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
14688 		 * causes the *entire* transfer to start over again from the
14689 		 * beginning of the request, even for PARTIAL chunks that
14690 		 * have already transferred successfully.
14691 		 */
14692 		if ((un->un_f_is_fibre == TRUE) &&
14693 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14694 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
14695 			scsi_dmafree(pktp);
14696 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
14697 		}
14698 #endif
14699 
14700 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14701 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
14702 
14703 		sd_handle_auto_request_sense(un, bp, xp, pktp);
14704 		goto exit;
14705 	}
14706 
14707 	/* Next see if this is the REQUEST SENSE pkt for the instance */
14708 	if (pktp->pkt_flags & FLAG_SENSING)  {
14709 		/* This pktp is from the unit's REQUEST_SENSE command */
14710 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14711 		    "sdintr: sd_handle_request_sense\n");
14712 		sd_handle_request_sense(un, bp, xp, pktp);
14713 		goto exit;
14714 	}
14715 
14716 	/*
14717 	 * Check to see if the command successfully completed as requested;
14718 	 * this is the most common case (and also the hot performance path).
14719 	 *
14720 	 * Requirements for successful completion are:
14721 	 * pkt_reason is CMD_CMPLT and packet status is status good.
14722 	 * In addition:
14723 	 * - A residual of zero indicates successful completion no matter what
14724 	 *   the command is.
14725 	 * - If the residual is not zero and the command is not a read or
14726 	 *   write, then it's still defined as successful completion. In other
14727 	 *   words, if the command is a read or write the residual must be
14728 	 *   zero for successful completion.
14729 	 * - If the residual is not zero and the command is a read or
14730 	 *   write, and it's a USCSICMD, then it's still defined as
14731 	 *   successful completion.
14732 	 */
14733 	if ((pktp->pkt_reason == CMD_CMPLT) &&
14734 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
14735 
14736 		/*
14737 		 * Since this command is returned with a good status, we
14738 		 * can reset the count for Sonoma failover.
14739 		 */
14740 		un->un_sonoma_failure_count = 0;
14741 
14742 		/*
14743 		 * Return all USCSI commands on good status
14744 		 */
14745 		if (pktp->pkt_resid == 0) {
14746 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14747 			    "sdintr: returning command for resid == 0\n");
14748 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
14749 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
14750 			SD_UPDATE_B_RESID(bp, pktp);
14751 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14752 			    "sdintr: returning command for resid != 0\n");
14753 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
14754 			SD_UPDATE_B_RESID(bp, pktp);
14755 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14756 			    "sdintr: returning uscsi command\n");
14757 		} else {
14758 			goto not_successful;
14759 		}
14760 		sd_return_command(un, bp);
14761 
14762 		/*
14763 		 * Decrement counter to indicate that the callback routine
14764 		 * is done.
14765 		 */
14766 		un->un_in_callback--;
14767 		ASSERT(un->un_in_callback >= 0);
14768 		mutex_exit(SD_MUTEX(un));
14769 
14770 		return;
14771 	}
14772 
14773 not_successful:
14774 
14775 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
14776 	/*
14777 	 * The following is based upon knowledge of the underlying transport
14778 	 * and its use of DMA resources.  This code should be removed when
14779 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
14780 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
14781 	 * and sd_start_cmds().
14782 	 *
14783 	 * Free any DMA resources associated with this command if there
14784 	 * is a chance it could be retried or enqueued for later retry.
14785 	 * If we keep the DMA binding then mpxio cannot reissue the
14786 	 * command on another path whenever a path failure occurs.
14787 	 *
14788 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
14789 	 * causes the *entire* transfer to start over again from the
14790 	 * beginning of the request, even for PARTIAL chunks that
14791 	 * have already transferred successfully.
14792 	 *
14793 	 * This is only done for non-uscsi commands (and also skipped for the
14794 	 * driver's internal RQS command). Also just do this for Fibre Channel
14795 	 * devices as these are the only ones that support mpxio.
14796 	 */
14797 	if ((un->un_f_is_fibre == TRUE) &&
14798 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14799 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
14800 		scsi_dmafree(pktp);
14801 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
14802 	}
14803 #endif
14804 
14805 	/*
14806 	 * The command did not successfully complete as requested so check
14807 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
14808 	 * driver command that should not be retried so just return. If
14809 	 * FLAG_DIAGNOSE is not set the error will be processed below.
14810 	 */
14811 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
14812 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14813 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
14814 		/*
14815 		 * Issue a request sense if a check condition caused the error
14816 		 * (we handle the auto request sense case above), otherwise
14817 		 * just fail the command.
14818 		 */
14819 		if ((pktp->pkt_reason == CMD_CMPLT) &&
14820 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
14821 			sd_send_request_sense_command(un, bp, pktp);
14822 		} else {
14823 			sd_return_failed_command(un, bp, EIO);
14824 		}
14825 		goto exit;
14826 	}
14827 
14828 	/*
14829 	 * The command did not successfully complete as requested so process
14830 	 * the error, retry, and/or attempt recovery.
14831 	 */
14832 	switch (pktp->pkt_reason) {
14833 	case CMD_CMPLT:
14834 		switch (SD_GET_PKT_STATUS(pktp)) {
14835 		case STATUS_GOOD:
14836 			/*
14837 			 * The command completed successfully with a non-zero
14838 			 * residual
14839 			 */
14840 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14841 			    "sdintr: STATUS_GOOD \n");
14842 			sd_pkt_status_good(un, bp, xp, pktp);
14843 			break;
14844 
14845 		case STATUS_CHECK:
14846 		case STATUS_TERMINATED:
14847 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14848 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
14849 			sd_pkt_status_check_condition(un, bp, xp, pktp);
14850 			break;
14851 
14852 		case STATUS_BUSY:
14853 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14854 			    "sdintr: STATUS_BUSY\n");
14855 			sd_pkt_status_busy(un, bp, xp, pktp);
14856 			break;
14857 
14858 		case STATUS_RESERVATION_CONFLICT:
14859 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14860 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
14861 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
14862 			break;
14863 
14864 		case STATUS_QFULL:
14865 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14866 			    "sdintr: STATUS_QFULL\n");
14867 			sd_pkt_status_qfull(un, bp, xp, pktp);
14868 			break;
14869 
14870 		case STATUS_MET:
14871 		case STATUS_INTERMEDIATE:
14872 		case STATUS_SCSI2:
14873 		case STATUS_INTERMEDIATE_MET:
14874 		case STATUS_ACA_ACTIVE:
14875 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
14876 			    "Unexpected SCSI status received: 0x%x\n",
14877 			    SD_GET_PKT_STATUS(pktp));
14878 			sd_return_failed_command(un, bp, EIO);
14879 			break;
14880 
14881 		default:
14882 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
14883 			    "Invalid SCSI status received: 0x%x\n",
14884 			    SD_GET_PKT_STATUS(pktp));
14885 			sd_return_failed_command(un, bp, EIO);
14886 			break;
14887 
14888 		}
14889 		break;
14890 
14891 	case CMD_INCOMPLETE:
14892 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14893 		    "sdintr:  CMD_INCOMPLETE\n");
14894 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
14895 		break;
14896 	case CMD_TRAN_ERR:
14897 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14898 		    "sdintr: CMD_TRAN_ERR\n");
14899 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
14900 		break;
14901 	case CMD_RESET:
14902 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14903 		    "sdintr: CMD_RESET \n");
14904 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
14905 		break;
14906 	case CMD_ABORTED:
14907 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14908 		    "sdintr: CMD_ABORTED \n");
14909 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
14910 		break;
14911 	case CMD_TIMEOUT:
14912 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14913 		    "sdintr: CMD_TIMEOUT\n");
14914 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
14915 		break;
14916 	case CMD_UNX_BUS_FREE:
14917 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14918 		    "sdintr: CMD_UNX_BUS_FREE \n");
14919 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
14920 		break;
14921 	case CMD_TAG_REJECT:
14922 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14923 		    "sdintr: CMD_TAG_REJECT\n");
14924 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
14925 		break;
14926 	default:
14927 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14928 		    "sdintr: default\n");
14929 		sd_pkt_reason_default(un, bp, xp, pktp);
14930 		break;
14931 	}
14932 
14933 exit:
14934 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
14935 
14936 	/* Decrement counter to indicate that the callback routine is done. */
14937 	un->un_in_callback--;
14938 	ASSERT(un->un_in_callback >= 0);
14939 
14940 	/*
14941 	 * At this point, the pkt has been dispatched, ie, it is either
14942 	 * being re-tried or has been returned to its caller and should
14943 	 * not be referenced.
14944 	 */
14945 
14946 	mutex_exit(SD_MUTEX(un));
14947 }
14948 
14949 
14950 /*
14951  *    Function: sd_print_incomplete_msg
14952  *
14953  * Description: Prints the error message for a CMD_INCOMPLETE error.
14954  *
14955  *   Arguments: un - ptr to associated softstate for the device.
14956  *		bp - ptr to the buf(9S) for the command.
14957  *		arg - message string ptr
14958  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
14959  *			or SD_NO_RETRY_ISSUED.
14960  *
14961  *     Context: May be called under interrupt context
14962  */
14963 
14964 static void
14965 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
14966 {
14967 	struct scsi_pkt	*pktp;
14968 	char	*msgp;
14969 	char	*cmdp = arg;
14970 
14971 	ASSERT(un != NULL);
14972 	ASSERT(mutex_owned(SD_MUTEX(un)));
14973 	ASSERT(bp != NULL);
14974 	ASSERT(arg != NULL);
14975 	pktp = SD_GET_PKTP(bp);
14976 	ASSERT(pktp != NULL);
14977 
14978 	switch (code) {
14979 	case SD_DELAYED_RETRY_ISSUED:
14980 	case SD_IMMEDIATE_RETRY_ISSUED:
14981 		msgp = "retrying";
14982 		break;
14983 	case SD_NO_RETRY_ISSUED:
14984 	default:
14985 		msgp = "giving up";
14986 		break;
14987 	}
14988 
14989 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
14990 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14991 		    "incomplete %s- %s\n", cmdp, msgp);
14992 	}
14993 }
14994 
14995 
14996 
14997 /*
14998  *    Function: sd_pkt_status_good
14999  *
15000  * Description: Processing for a STATUS_GOOD code in pkt_status.
15001  *
15002  *     Context: May be called under interrupt context
15003  */
15004 
15005 static void
15006 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
15007 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15008 {
15009 	char	*cmdp;
15010 
15011 	ASSERT(un != NULL);
15012 	ASSERT(mutex_owned(SD_MUTEX(un)));
15013 	ASSERT(bp != NULL);
15014 	ASSERT(xp != NULL);
15015 	ASSERT(pktp != NULL);
15016 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
15017 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
15018 	ASSERT(pktp->pkt_resid != 0);
15019 
15020 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
15021 
15022 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
15023 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
15024 	case SCMD_READ:
15025 		cmdp = "read";
15026 		break;
15027 	case SCMD_WRITE:
15028 		cmdp = "write";
15029 		break;
15030 	default:
15031 		SD_UPDATE_B_RESID(bp, pktp);
15032 		sd_return_command(un, bp);
15033 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15034 		return;
15035 	}
15036 
15037 	/*
15038 	 * See if we can retry the read/write, preferrably immediately.
15039 	 * If retries are exhaused, then sd_retry_command() will update
15040 	 * the b_resid count.
15041 	 */
15042 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
15043 	    cmdp, EIO, (clock_t)0, NULL);
15044 
15045 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15046 }
15047 
15048 
15049 
15050 
15051 
15052 /*
15053  *    Function: sd_handle_request_sense
15054  *
15055  * Description: Processing for non-auto Request Sense command.
15056  *
15057  *   Arguments: un - ptr to associated softstate
15058  *		sense_bp - ptr to buf(9S) for the RQS command
15059  *		sense_xp - ptr to the sd_xbuf for the RQS command
15060  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
15061  *
15062  *     Context: May be called under interrupt context
15063  */
15064 
15065 static void
15066 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
15067 	struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
15068 {
15069 	struct buf	*cmd_bp;	/* buf for the original command */
15070 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
15071 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
15072 
15073 	ASSERT(un != NULL);
15074 	ASSERT(mutex_owned(SD_MUTEX(un)));
15075 	ASSERT(sense_bp != NULL);
15076 	ASSERT(sense_xp != NULL);
15077 	ASSERT(sense_pktp != NULL);
15078 
15079 	/*
15080 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
15081 	 * RQS command and not the original command.
15082 	 */
15083 	ASSERT(sense_pktp == un->un_rqs_pktp);
15084 	ASSERT(sense_bp   == un->un_rqs_bp);
15085 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
15086 	    (FLAG_SENSING | FLAG_HEAD));
15087 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
15088 	    FLAG_SENSING) == FLAG_SENSING);
15089 
15090 	/* These are the bp, xp, and pktp for the original command */
15091 	cmd_bp = sense_xp->xb_sense_bp;
15092 	cmd_xp = SD_GET_XBUF(cmd_bp);
15093 	cmd_pktp = SD_GET_PKTP(cmd_bp);
15094 
15095 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
15096 		/*
15097 		 * The REQUEST SENSE command failed.  Release the REQUEST
15098 		 * SENSE command for re-use, get back the bp for the original
15099 		 * command, and attempt to re-try the original command if
15100 		 * FLAG_DIAGNOSE is not set in the original packet.
15101 		 */
15102 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
15103 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15104 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
15105 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
15106 			    NULL, NULL, EIO, (clock_t)0, NULL);
15107 			return;
15108 		}
15109 	}
15110 
15111 	/*
15112 	 * Save the relevant sense info into the xp for the original cmd.
15113 	 *
15114 	 * Note: if the request sense failed the state info will be zero
15115 	 * as set in sd_mark_rqs_busy()
15116 	 */
15117 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
15118 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
15119 	cmd_xp->xb_sense_resid  = sense_pktp->pkt_resid;
15120 	bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data, SENSE_LENGTH);
15121 
15122 	/*
15123 	 *  Free up the RQS command....
15124 	 *  NOTE:
15125 	 *	Must do this BEFORE calling sd_validate_sense_data!
15126 	 *	sd_validate_sense_data may return the original command in
15127 	 *	which case the pkt will be freed and the flags can no
15128 	 *	longer be touched.
15129 	 *	SD_MUTEX is held through this process until the command
15130 	 *	is dispatched based upon the sense data, so there are
15131 	 *	no race conditions.
15132 	 */
15133 	(void) sd_mark_rqs_idle(un, sense_xp);
15134 
15135 	/*
15136 	 * For a retryable command see if we have valid sense data, if so then
15137 	 * turn it over to sd_decode_sense() to figure out the right course of
15138 	 * action. Just fail a non-retryable command.
15139 	 */
15140 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15141 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp) ==
15142 		    SD_SENSE_DATA_IS_VALID) {
15143 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
15144 		}
15145 	} else {
15146 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
15147 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15148 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
15149 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15150 		sd_return_failed_command(un, cmd_bp, EIO);
15151 	}
15152 }
15153 
15154 
15155 
15156 
15157 /*
15158  *    Function: sd_handle_auto_request_sense
15159  *
15160  * Description: Processing for auto-request sense information.
15161  *
15162  *   Arguments: un - ptr to associated softstate
15163  *		bp - ptr to buf(9S) for the command
15164  *		xp - ptr to the sd_xbuf for the command
15165  *		pktp - ptr to the scsi_pkt(9S) for the command
15166  *
15167  *     Context: May be called under interrupt context
15168  */
15169 
15170 static void
15171 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
15172 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15173 {
15174 	struct scsi_arq_status *asp;
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 != un->un_rqs_pktp);
15182 	ASSERT(bp   != un->un_rqs_bp);
15183 
15184 	/*
15185 	 * For auto-request sense, we get a scsi_arq_status back from
15186 	 * the HBA, with the sense data in the sts_sensedata member.
15187 	 * The pkt_scbp of the packet points to this scsi_arq_status.
15188 	 */
15189 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
15190 
15191 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
15192 		/*
15193 		 * The auto REQUEST SENSE failed; see if we can re-try
15194 		 * the original command.
15195 		 */
15196 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15197 		    "auto request sense failed (reason=%s)\n",
15198 		    scsi_rname(asp->sts_rqpkt_reason));
15199 
15200 		sd_reset_target(un, pktp);
15201 
15202 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15203 		    NULL, NULL, EIO, (clock_t)0, NULL);
15204 		return;
15205 	}
15206 
15207 	/* Save the relevant sense info into the xp for the original cmd. */
15208 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
15209 	xp->xb_sense_state  = asp->sts_rqpkt_state;
15210 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
15211 	bcopy(&asp->sts_sensedata, xp->xb_sense_data,
15212 	    min(sizeof (struct scsi_extended_sense), SENSE_LENGTH));
15213 
15214 	/*
15215 	 * See if we have valid sense data, if so then turn it over to
15216 	 * sd_decode_sense() to figure out the right course of action.
15217 	 */
15218 	if (sd_validate_sense_data(un, bp, xp) == SD_SENSE_DATA_IS_VALID) {
15219 		sd_decode_sense(un, bp, xp, pktp);
15220 	}
15221 }
15222 
15223 
15224 /*
15225  *    Function: sd_print_sense_failed_msg
15226  *
15227  * Description: Print log message when RQS has failed.
15228  *
15229  *   Arguments: un - ptr to associated softstate
15230  *		bp - ptr to buf(9S) for the command
15231  *		arg - generic message string ptr
15232  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15233  *			or SD_NO_RETRY_ISSUED
15234  *
15235  *     Context: May be called from interrupt context
15236  */
15237 
15238 static void
15239 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
15240 	int code)
15241 {
15242 	char	*msgp = arg;
15243 
15244 	ASSERT(un != NULL);
15245 	ASSERT(mutex_owned(SD_MUTEX(un)));
15246 	ASSERT(bp != NULL);
15247 
15248 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
15249 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
15250 	}
15251 }
15252 
15253 
15254 /*
15255  *    Function: sd_validate_sense_data
15256  *
15257  * Description: Check the given sense data for validity.
15258  *		If the sense data is not valid, the command will
15259  *		be either failed or retried!
15260  *
15261  * Return Code: SD_SENSE_DATA_IS_INVALID
15262  *		SD_SENSE_DATA_IS_VALID
15263  *
15264  *     Context: May be called from interrupt context
15265  */
15266 
15267 static int
15268 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp)
15269 {
15270 	struct scsi_extended_sense *esp;
15271 	struct	scsi_pkt *pktp;
15272 	size_t	actual_len;
15273 	char	*msgp = NULL;
15274 
15275 	ASSERT(un != NULL);
15276 	ASSERT(mutex_owned(SD_MUTEX(un)));
15277 	ASSERT(bp != NULL);
15278 	ASSERT(bp != un->un_rqs_bp);
15279 	ASSERT(xp != NULL);
15280 
15281 	pktp = SD_GET_PKTP(bp);
15282 	ASSERT(pktp != NULL);
15283 
15284 	/*
15285 	 * Check the status of the RQS command (auto or manual).
15286 	 */
15287 	switch (xp->xb_sense_status & STATUS_MASK) {
15288 	case STATUS_GOOD:
15289 		break;
15290 
15291 	case STATUS_RESERVATION_CONFLICT:
15292 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
15293 		return (SD_SENSE_DATA_IS_INVALID);
15294 
15295 	case STATUS_BUSY:
15296 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15297 		    "Busy Status on REQUEST SENSE\n");
15298 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
15299 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15300 		return (SD_SENSE_DATA_IS_INVALID);
15301 
15302 	case STATUS_QFULL:
15303 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15304 		    "QFULL Status on REQUEST SENSE\n");
15305 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
15306 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15307 		return (SD_SENSE_DATA_IS_INVALID);
15308 
15309 	case STATUS_CHECK:
15310 	case STATUS_TERMINATED:
15311 		msgp = "Check Condition on REQUEST SENSE\n";
15312 		goto sense_failed;
15313 
15314 	default:
15315 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
15316 		goto sense_failed;
15317 	}
15318 
15319 	/*
15320 	 * See if we got the minimum required amount of sense data.
15321 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
15322 	 * or less.
15323 	 */
15324 	actual_len = (int)(SENSE_LENGTH - xp->xb_sense_resid);
15325 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
15326 	    (actual_len == 0)) {
15327 		msgp = "Request Sense couldn't get sense data\n";
15328 		goto sense_failed;
15329 	}
15330 
15331 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
15332 		msgp = "Not enough sense information\n";
15333 		goto sense_failed;
15334 	}
15335 
15336 	/*
15337 	 * We require the extended sense data
15338 	 */
15339 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
15340 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
15341 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
15342 			static char tmp[8];
15343 			static char buf[148];
15344 			char *p = (char *)(xp->xb_sense_data);
15345 			int i;
15346 
15347 			mutex_enter(&sd_sense_mutex);
15348 			(void) strcpy(buf, "undecodable sense information:");
15349 			for (i = 0; i < actual_len; i++) {
15350 				(void) sprintf(tmp, " 0x%x", *(p++)&0xff);
15351 				(void) strcpy(&buf[strlen(buf)], tmp);
15352 			}
15353 			i = strlen(buf);
15354 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
15355 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, buf);
15356 			mutex_exit(&sd_sense_mutex);
15357 		}
15358 		/* Note: Legacy behavior, fail the command with no retry */
15359 		sd_return_failed_command(un, bp, EIO);
15360 		return (SD_SENSE_DATA_IS_INVALID);
15361 	}
15362 
15363 	/*
15364 	 * Check that es_code is valid (es_class concatenated with es_code
15365 	 * make up the "response code" field.  es_class will always be 7, so
15366 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
15367 	 * format.
15368 	 */
15369 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
15370 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
15371 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
15372 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
15373 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
15374 		goto sense_failed;
15375 	}
15376 
15377 	return (SD_SENSE_DATA_IS_VALID);
15378 
15379 sense_failed:
15380 	/*
15381 	 * If the request sense failed (for whatever reason), attempt
15382 	 * to retry the original command.
15383 	 */
15384 #if defined(__i386) || defined(__amd64)
15385 	/*
15386 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
15387 	 * sddef.h for Sparc platform, and x86 uses 1 binary
15388 	 * for both SCSI/FC.
15389 	 * The SD_RETRY_DELAY value need to be adjusted here
15390 	 * when SD_RETRY_DELAY change in sddef.h
15391 	 */
15392 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15393 	    sd_print_sense_failed_msg, msgp, EIO,
15394 	    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0, NULL);
15395 #else
15396 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15397 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
15398 #endif
15399 
15400 	return (SD_SENSE_DATA_IS_INVALID);
15401 }
15402 
15403 
15404 
15405 /*
15406  *    Function: sd_decode_sense
15407  *
15408  * Description: Take recovery action(s) when SCSI Sense Data is received.
15409  *
15410  *     Context: Interrupt context.
15411  */
15412 
15413 static void
15414 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
15415 	struct scsi_pkt *pktp)
15416 {
15417 	uint8_t sense_key;
15418 
15419 	ASSERT(un != NULL);
15420 	ASSERT(mutex_owned(SD_MUTEX(un)));
15421 	ASSERT(bp != NULL);
15422 	ASSERT(bp != un->un_rqs_bp);
15423 	ASSERT(xp != NULL);
15424 	ASSERT(pktp != NULL);
15425 
15426 	sense_key = scsi_sense_key(xp->xb_sense_data);
15427 
15428 	switch (sense_key) {
15429 	case KEY_NO_SENSE:
15430 		sd_sense_key_no_sense(un, bp, xp, pktp);
15431 		break;
15432 	case KEY_RECOVERABLE_ERROR:
15433 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
15434 		    bp, xp, pktp);
15435 		break;
15436 	case KEY_NOT_READY:
15437 		sd_sense_key_not_ready(un, xp->xb_sense_data,
15438 		    bp, xp, pktp);
15439 		break;
15440 	case KEY_MEDIUM_ERROR:
15441 	case KEY_HARDWARE_ERROR:
15442 		sd_sense_key_medium_or_hardware_error(un,
15443 		    xp->xb_sense_data, bp, xp, pktp);
15444 		break;
15445 	case KEY_ILLEGAL_REQUEST:
15446 		sd_sense_key_illegal_request(un, bp, xp, pktp);
15447 		break;
15448 	case KEY_UNIT_ATTENTION:
15449 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
15450 		    bp, xp, pktp);
15451 		break;
15452 	case KEY_WRITE_PROTECT:
15453 	case KEY_VOLUME_OVERFLOW:
15454 	case KEY_MISCOMPARE:
15455 		sd_sense_key_fail_command(un, bp, xp, pktp);
15456 		break;
15457 	case KEY_BLANK_CHECK:
15458 		sd_sense_key_blank_check(un, bp, xp, pktp);
15459 		break;
15460 	case KEY_ABORTED_COMMAND:
15461 		sd_sense_key_aborted_command(un, bp, xp, pktp);
15462 		break;
15463 	case KEY_VENDOR_UNIQUE:
15464 	case KEY_COPY_ABORTED:
15465 	case KEY_EQUAL:
15466 	case KEY_RESERVED:
15467 	default:
15468 		sd_sense_key_default(un, xp->xb_sense_data,
15469 		    bp, xp, pktp);
15470 		break;
15471 	}
15472 }
15473 
15474 
15475 /*
15476  *    Function: sd_dump_memory
15477  *
15478  * Description: Debug logging routine to print the contents of a user provided
15479  *		buffer. The output of the buffer is broken up into 256 byte
15480  *		segments due to a size constraint of the scsi_log.
15481  *		implementation.
15482  *
15483  *   Arguments: un - ptr to softstate
15484  *		comp - component mask
15485  *		title - "title" string to preceed data when printed
15486  *		data - ptr to data block to be printed
15487  *		len - size of data block to be printed
15488  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
15489  *
15490  *     Context: May be called from interrupt context
15491  */
15492 
15493 #define	SD_DUMP_MEMORY_BUF_SIZE	256
15494 
15495 static char *sd_dump_format_string[] = {
15496 		" 0x%02x",
15497 		" %c"
15498 };
15499 
15500 static void
15501 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
15502     int len, int fmt)
15503 {
15504 	int	i, j;
15505 	int	avail_count;
15506 	int	start_offset;
15507 	int	end_offset;
15508 	size_t	entry_len;
15509 	char	*bufp;
15510 	char	*local_buf;
15511 	char	*format_string;
15512 
15513 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
15514 
15515 	/*
15516 	 * In the debug version of the driver, this function is called from a
15517 	 * number of places which are NOPs in the release driver.
15518 	 * The debug driver therefore has additional methods of filtering
15519 	 * debug output.
15520 	 */
15521 #ifdef SDDEBUG
15522 	/*
15523 	 * In the debug version of the driver we can reduce the amount of debug
15524 	 * messages by setting sd_error_level to something other than
15525 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
15526 	 * sd_component_mask.
15527 	 */
15528 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
15529 	    (sd_error_level != SCSI_ERR_ALL)) {
15530 		return;
15531 	}
15532 	if (((sd_component_mask & comp) == 0) ||
15533 	    (sd_error_level != SCSI_ERR_ALL)) {
15534 		return;
15535 	}
15536 #else
15537 	if (sd_error_level != SCSI_ERR_ALL) {
15538 		return;
15539 	}
15540 #endif
15541 
15542 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
15543 	bufp = local_buf;
15544 	/*
15545 	 * Available length is the length of local_buf[], minus the
15546 	 * length of the title string, minus one for the ":", minus
15547 	 * one for the newline, minus one for the NULL terminator.
15548 	 * This gives the #bytes available for holding the printed
15549 	 * values from the given data buffer.
15550 	 */
15551 	if (fmt == SD_LOG_HEX) {
15552 		format_string = sd_dump_format_string[0];
15553 	} else /* SD_LOG_CHAR */ {
15554 		format_string = sd_dump_format_string[1];
15555 	}
15556 	/*
15557 	 * Available count is the number of elements from the given
15558 	 * data buffer that we can fit into the available length.
15559 	 * This is based upon the size of the format string used.
15560 	 * Make one entry and find it's size.
15561 	 */
15562 	(void) sprintf(bufp, format_string, data[0]);
15563 	entry_len = strlen(bufp);
15564 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
15565 
15566 	j = 0;
15567 	while (j < len) {
15568 		bufp = local_buf;
15569 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
15570 		start_offset = j;
15571 
15572 		end_offset = start_offset + avail_count;
15573 
15574 		(void) sprintf(bufp, "%s:", title);
15575 		bufp += strlen(bufp);
15576 		for (i = start_offset; ((i < end_offset) && (j < len));
15577 		    i++, j++) {
15578 			(void) sprintf(bufp, format_string, data[i]);
15579 			bufp += entry_len;
15580 		}
15581 		(void) sprintf(bufp, "\n");
15582 
15583 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
15584 	}
15585 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
15586 }
15587 
15588 /*
15589  *    Function: sd_print_sense_msg
15590  *
15591  * Description: Log a message based upon the given sense data.
15592  *
15593  *   Arguments: un - ptr to associated softstate
15594  *		bp - ptr to buf(9S) for the command
15595  *		arg - ptr to associate sd_sense_info struct
15596  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15597  *			or SD_NO_RETRY_ISSUED
15598  *
15599  *     Context: May be called from interrupt context
15600  */
15601 
15602 static void
15603 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
15604 {
15605 	struct sd_xbuf	*xp;
15606 	struct scsi_pkt	*pktp;
15607 	uint8_t *sensep;
15608 	daddr_t request_blkno;
15609 	diskaddr_t err_blkno;
15610 	int severity;
15611 	int pfa_flag;
15612 	extern struct scsi_key_strings scsi_cmds[];
15613 
15614 	ASSERT(un != NULL);
15615 	ASSERT(mutex_owned(SD_MUTEX(un)));
15616 	ASSERT(bp != NULL);
15617 	xp = SD_GET_XBUF(bp);
15618 	ASSERT(xp != NULL);
15619 	pktp = SD_GET_PKTP(bp);
15620 	ASSERT(pktp != NULL);
15621 	ASSERT(arg != NULL);
15622 
15623 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
15624 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
15625 
15626 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
15627 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
15628 		severity = SCSI_ERR_RETRYABLE;
15629 	}
15630 
15631 	/* Use absolute block number for the request block number */
15632 	request_blkno = xp->xb_blkno;
15633 
15634 	/*
15635 	 * Now try to get the error block number from the sense data
15636 	 */
15637 	sensep = xp->xb_sense_data;
15638 
15639 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
15640 	    (uint64_t *)&err_blkno)) {
15641 		/*
15642 		 * We retrieved the error block number from the information
15643 		 * portion of the sense data.
15644 		 *
15645 		 * For USCSI commands we are better off using the error
15646 		 * block no. as the requested block no. (This is the best
15647 		 * we can estimate.)
15648 		 */
15649 		if ((SD_IS_BUFIO(xp) == FALSE) &&
15650 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
15651 			request_blkno = err_blkno;
15652 		}
15653 	} else {
15654 		/*
15655 		 * Without the es_valid bit set (for fixed format) or an
15656 		 * information descriptor (for descriptor format) we cannot
15657 		 * be certain of the error blkno, so just use the
15658 		 * request_blkno.
15659 		 */
15660 		err_blkno = (diskaddr_t)request_blkno;
15661 	}
15662 
15663 	/*
15664 	 * The following will log the buffer contents for the release driver
15665 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
15666 	 * level is set to verbose.
15667 	 */
15668 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
15669 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15670 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15671 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
15672 
15673 	if (pfa_flag == FALSE) {
15674 		/* This is normally only set for USCSI */
15675 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
15676 			return;
15677 		}
15678 
15679 		if ((SD_IS_BUFIO(xp) == TRUE) &&
15680 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
15681 		    (severity < sd_error_level))) {
15682 			return;
15683 		}
15684 	}
15685 
15686 	/*
15687 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
15688 	 */
15689 	if ((SD_IS_LSI(un)) &&
15690 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
15691 	    (scsi_sense_asc(sensep) == 0x94) &&
15692 	    (scsi_sense_ascq(sensep) == 0x01)) {
15693 		un->un_sonoma_failure_count++;
15694 		if (un->un_sonoma_failure_count > 1) {
15695 			return;
15696 		}
15697 	}
15698 
15699 	scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
15700 	    request_blkno, err_blkno, scsi_cmds,
15701 	    (struct scsi_extended_sense *)sensep,
15702 	    un->un_additional_codes, NULL);
15703 }
15704 
15705 /*
15706  *    Function: sd_sense_key_no_sense
15707  *
15708  * Description: Recovery action when sense data was not received.
15709  *
15710  *     Context: May be called from interrupt context
15711  */
15712 
15713 static void
15714 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
15715 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15716 {
15717 	struct sd_sense_info	si;
15718 
15719 	ASSERT(un != NULL);
15720 	ASSERT(mutex_owned(SD_MUTEX(un)));
15721 	ASSERT(bp != NULL);
15722 	ASSERT(xp != NULL);
15723 	ASSERT(pktp != NULL);
15724 
15725 	si.ssi_severity = SCSI_ERR_FATAL;
15726 	si.ssi_pfa_flag = FALSE;
15727 
15728 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
15729 
15730 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
15731 	    &si, EIO, (clock_t)0, NULL);
15732 }
15733 
15734 
15735 /*
15736  *    Function: sd_sense_key_recoverable_error
15737  *
15738  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
15739  *
15740  *     Context: May be called from interrupt context
15741  */
15742 
15743 static void
15744 sd_sense_key_recoverable_error(struct sd_lun *un,
15745 	uint8_t *sense_datap,
15746 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
15747 {
15748 	struct sd_sense_info	si;
15749 	uint8_t asc = scsi_sense_asc(sense_datap);
15750 
15751 	ASSERT(un != NULL);
15752 	ASSERT(mutex_owned(SD_MUTEX(un)));
15753 	ASSERT(bp != NULL);
15754 	ASSERT(xp != NULL);
15755 	ASSERT(pktp != NULL);
15756 
15757 	/*
15758 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
15759 	 */
15760 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
15761 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
15762 		si.ssi_severity = SCSI_ERR_INFO;
15763 		si.ssi_pfa_flag = TRUE;
15764 	} else {
15765 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
15766 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
15767 		si.ssi_severity = SCSI_ERR_RECOVERED;
15768 		si.ssi_pfa_flag = FALSE;
15769 	}
15770 
15771 	if (pktp->pkt_resid == 0) {
15772 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
15773 		sd_return_command(un, bp);
15774 		return;
15775 	}
15776 
15777 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
15778 	    &si, EIO, (clock_t)0, NULL);
15779 }
15780 
15781 
15782 
15783 
15784 /*
15785  *    Function: sd_sense_key_not_ready
15786  *
15787  * Description: Recovery actions for a SCSI "Not Ready" sense key.
15788  *
15789  *     Context: May be called from interrupt context
15790  */
15791 
15792 static void
15793 sd_sense_key_not_ready(struct sd_lun *un,
15794 	uint8_t *sense_datap,
15795 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
15796 {
15797 	struct sd_sense_info	si;
15798 	uint8_t asc = scsi_sense_asc(sense_datap);
15799 	uint8_t ascq = scsi_sense_ascq(sense_datap);
15800 
15801 	ASSERT(un != NULL);
15802 	ASSERT(mutex_owned(SD_MUTEX(un)));
15803 	ASSERT(bp != NULL);
15804 	ASSERT(xp != NULL);
15805 	ASSERT(pktp != NULL);
15806 
15807 	si.ssi_severity = SCSI_ERR_FATAL;
15808 	si.ssi_pfa_flag = FALSE;
15809 
15810 	/*
15811 	 * Update error stats after first NOT READY error. Disks may have
15812 	 * been powered down and may need to be restarted.  For CDROMs,
15813 	 * report NOT READY errors only if media is present.
15814 	 */
15815 	if ((ISCD(un) && (asc == 0x3A)) ||
15816 	    (xp->xb_nr_retry_count > 0)) {
15817 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
15818 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
15819 	}
15820 
15821 	/*
15822 	 * Just fail if the "not ready" retry limit has been reached.
15823 	 */
15824 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
15825 		/* Special check for error message printing for removables. */
15826 		if (un->un_f_has_removable_media && (asc == 0x04) &&
15827 		    (ascq >= 0x04)) {
15828 			si.ssi_severity = SCSI_ERR_ALL;
15829 		}
15830 		goto fail_command;
15831 	}
15832 
15833 	/*
15834 	 * Check the ASC and ASCQ in the sense data as needed, to determine
15835 	 * what to do.
15836 	 */
15837 	switch (asc) {
15838 	case 0x04:	/* LOGICAL UNIT NOT READY */
15839 		/*
15840 		 * disk drives that don't spin up result in a very long delay
15841 		 * in format without warning messages. We will log a message
15842 		 * if the error level is set to verbose.
15843 		 */
15844 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
15845 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15846 			    "logical unit not ready, resetting disk\n");
15847 		}
15848 
15849 		/*
15850 		 * There are different requirements for CDROMs and disks for
15851 		 * the number of retries.  If a CD-ROM is giving this, it is
15852 		 * probably reading TOC and is in the process of getting
15853 		 * ready, so we should keep on trying for a long time to make
15854 		 * sure that all types of media are taken in account (for
15855 		 * some media the drive takes a long time to read TOC).  For
15856 		 * disks we do not want to retry this too many times as this
15857 		 * can cause a long hang in format when the drive refuses to
15858 		 * spin up (a very common failure).
15859 		 */
15860 		switch (ascq) {
15861 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
15862 			/*
15863 			 * Disk drives frequently refuse to spin up which
15864 			 * results in a very long hang in format without
15865 			 * warning messages.
15866 			 *
15867 			 * Note: This code preserves the legacy behavior of
15868 			 * comparing xb_nr_retry_count against zero for fibre
15869 			 * channel targets instead of comparing against the
15870 			 * un_reset_retry_count value.  The reason for this
15871 			 * discrepancy has been so utterly lost beneath the
15872 			 * Sands of Time that even Indiana Jones could not
15873 			 * find it.
15874 			 */
15875 			if (un->un_f_is_fibre == TRUE) {
15876 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
15877 				    (xp->xb_nr_retry_count > 0)) &&
15878 				    (un->un_startstop_timeid == NULL)) {
15879 					scsi_log(SD_DEVINFO(un), sd_label,
15880 					    CE_WARN, "logical unit not ready, "
15881 					    "resetting disk\n");
15882 					sd_reset_target(un, pktp);
15883 				}
15884 			} else {
15885 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
15886 				    (xp->xb_nr_retry_count >
15887 				    un->un_reset_retry_count)) &&
15888 				    (un->un_startstop_timeid == NULL)) {
15889 					scsi_log(SD_DEVINFO(un), sd_label,
15890 					    CE_WARN, "logical unit not ready, "
15891 					    "resetting disk\n");
15892 					sd_reset_target(un, pktp);
15893 				}
15894 			}
15895 			break;
15896 
15897 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
15898 			/*
15899 			 * If the target is in the process of becoming
15900 			 * ready, just proceed with the retry. This can
15901 			 * happen with CD-ROMs that take a long time to
15902 			 * read TOC after a power cycle or reset.
15903 			 */
15904 			goto do_retry;
15905 
15906 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
15907 			break;
15908 
15909 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
15910 			/*
15911 			 * Retries cannot help here so just fail right away.
15912 			 */
15913 			goto fail_command;
15914 
15915 		case 0x88:
15916 			/*
15917 			 * Vendor-unique code for T3/T4: it indicates a
15918 			 * path problem in a mutipathed config, but as far as
15919 			 * the target driver is concerned it equates to a fatal
15920 			 * error, so we should just fail the command right away
15921 			 * (without printing anything to the console). If this
15922 			 * is not a T3/T4, fall thru to the default recovery
15923 			 * action.
15924 			 * T3/T4 is FC only, don't need to check is_fibre
15925 			 */
15926 			if (SD_IS_T3(un) || SD_IS_T4(un)) {
15927 				sd_return_failed_command(un, bp, EIO);
15928 				return;
15929 			}
15930 			/* FALLTHRU */
15931 
15932 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
15933 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
15934 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
15935 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
15936 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
15937 		default:    /* Possible future codes in SCSI spec? */
15938 			/*
15939 			 * For removable-media devices, do not retry if
15940 			 * ASCQ > 2 as these result mostly from USCSI commands
15941 			 * on MMC devices issued to check status of an
15942 			 * operation initiated in immediate mode.  Also for
15943 			 * ASCQ >= 4 do not print console messages as these
15944 			 * mainly represent a user-initiated operation
15945 			 * instead of a system failure.
15946 			 */
15947 			if (un->un_f_has_removable_media) {
15948 				si.ssi_severity = SCSI_ERR_ALL;
15949 				goto fail_command;
15950 			}
15951 			break;
15952 		}
15953 
15954 		/*
15955 		 * As part of our recovery attempt for the NOT READY
15956 		 * condition, we issue a START STOP UNIT command. However
15957 		 * we want to wait for a short delay before attempting this
15958 		 * as there may still be more commands coming back from the
15959 		 * target with the check condition. To do this we use
15960 		 * timeout(9F) to call sd_start_stop_unit_callback() after
15961 		 * the delay interval expires. (sd_start_stop_unit_callback()
15962 		 * dispatches sd_start_stop_unit_task(), which will issue
15963 		 * the actual START STOP UNIT command. The delay interval
15964 		 * is one-half of the delay that we will use to retry the
15965 		 * command that generated the NOT READY condition.
15966 		 *
15967 		 * Note that we could just dispatch sd_start_stop_unit_task()
15968 		 * from here and allow it to sleep for the delay interval,
15969 		 * but then we would be tying up the taskq thread
15970 		 * uncesessarily for the duration of the delay.
15971 		 *
15972 		 * Do not issue the START STOP UNIT if the current command
15973 		 * is already a START STOP UNIT.
15974 		 */
15975 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
15976 			break;
15977 		}
15978 
15979 		/*
15980 		 * Do not schedule the timeout if one is already pending.
15981 		 */
15982 		if (un->un_startstop_timeid != NULL) {
15983 			SD_INFO(SD_LOG_ERROR, un,
15984 			    "sd_sense_key_not_ready: restart already issued to"
15985 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
15986 			    ddi_get_instance(SD_DEVINFO(un)));
15987 			break;
15988 		}
15989 
15990 		/*
15991 		 * Schedule the START STOP UNIT command, then queue the command
15992 		 * for a retry.
15993 		 *
15994 		 * Note: A timeout is not scheduled for this retry because we
15995 		 * want the retry to be serial with the START_STOP_UNIT. The
15996 		 * retry will be started when the START_STOP_UNIT is completed
15997 		 * in sd_start_stop_unit_task.
15998 		 */
15999 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
16000 		    un, SD_BSY_TIMEOUT / 2);
16001 		xp->xb_nr_retry_count++;
16002 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
16003 		return;
16004 
16005 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
16006 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16007 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16008 			    "unit does not respond to selection\n");
16009 		}
16010 		break;
16011 
16012 	case 0x3A:	/* MEDIUM NOT PRESENT */
16013 		if (sd_error_level >= SCSI_ERR_FATAL) {
16014 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16015 			    "Caddy not inserted in drive\n");
16016 		}
16017 
16018 		sr_ejected(un);
16019 		un->un_mediastate = DKIO_EJECTED;
16020 		/* The state has changed, inform the media watch routines */
16021 		cv_broadcast(&un->un_state_cv);
16022 		/* Just fail if no media is present in the drive. */
16023 		goto fail_command;
16024 
16025 	default:
16026 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16027 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
16028 			    "Unit not Ready. Additional sense code 0x%x\n",
16029 			    asc);
16030 		}
16031 		break;
16032 	}
16033 
16034 do_retry:
16035 
16036 	/*
16037 	 * Retry the command, as some targets may report NOT READY for
16038 	 * several seconds after being reset.
16039 	 */
16040 	xp->xb_nr_retry_count++;
16041 	si.ssi_severity = SCSI_ERR_RETRYABLE;
16042 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
16043 	    &si, EIO, SD_BSY_TIMEOUT, NULL);
16044 
16045 	return;
16046 
16047 fail_command:
16048 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16049 	sd_return_failed_command(un, bp, EIO);
16050 }
16051 
16052 
16053 
16054 /*
16055  *    Function: sd_sense_key_medium_or_hardware_error
16056  *
16057  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
16058  *		sense key.
16059  *
16060  *     Context: May be called from interrupt context
16061  */
16062 
16063 static void
16064 sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
16065 	uint8_t *sense_datap,
16066 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16067 {
16068 	struct sd_sense_info	si;
16069 	uint8_t sense_key = scsi_sense_key(sense_datap);
16070 	uint8_t asc = scsi_sense_asc(sense_datap);
16071 
16072 	ASSERT(un != NULL);
16073 	ASSERT(mutex_owned(SD_MUTEX(un)));
16074 	ASSERT(bp != NULL);
16075 	ASSERT(xp != NULL);
16076 	ASSERT(pktp != NULL);
16077 
16078 	si.ssi_severity = SCSI_ERR_FATAL;
16079 	si.ssi_pfa_flag = FALSE;
16080 
16081 	if (sense_key == KEY_MEDIUM_ERROR) {
16082 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
16083 	}
16084 
16085 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16086 
16087 	if ((un->un_reset_retry_count != 0) &&
16088 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
16089 		mutex_exit(SD_MUTEX(un));
16090 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
16091 		if (un->un_f_allow_bus_device_reset == TRUE) {
16092 
16093 			boolean_t try_resetting_target = B_TRUE;
16094 
16095 			/*
16096 			 * We need to be able to handle specific ASC when we are
16097 			 * handling a KEY_HARDWARE_ERROR. In particular
16098 			 * taking the default action of resetting the target may
16099 			 * not be the appropriate way to attempt recovery.
16100 			 * Resetting a target because of a single LUN failure
16101 			 * victimizes all LUNs on that target.
16102 			 *
16103 			 * This is true for the LSI arrays, if an LSI
16104 			 * array controller returns an ASC of 0x84 (LUN Dead) we
16105 			 * should trust it.
16106 			 */
16107 
16108 			if (sense_key == KEY_HARDWARE_ERROR) {
16109 				switch (asc) {
16110 				case 0x84:
16111 					if (SD_IS_LSI(un)) {
16112 						try_resetting_target = B_FALSE;
16113 					}
16114 					break;
16115 				default:
16116 					break;
16117 				}
16118 			}
16119 
16120 			if (try_resetting_target == B_TRUE) {
16121 				int reset_retval = 0;
16122 				if (un->un_f_lun_reset_enabled == TRUE) {
16123 					SD_TRACE(SD_LOG_IO_CORE, un,
16124 					    "sd_sense_key_medium_or_hardware_"
16125 					    "error: issuing RESET_LUN\n");
16126 					reset_retval =
16127 					    scsi_reset(SD_ADDRESS(un),
16128 					    RESET_LUN);
16129 				}
16130 				if (reset_retval == 0) {
16131 					SD_TRACE(SD_LOG_IO_CORE, un,
16132 					    "sd_sense_key_medium_or_hardware_"
16133 					    "error: issuing RESET_TARGET\n");
16134 					(void) scsi_reset(SD_ADDRESS(un),
16135 					    RESET_TARGET);
16136 				}
16137 			}
16138 		}
16139 		mutex_enter(SD_MUTEX(un));
16140 	}
16141 
16142 	/*
16143 	 * This really ought to be a fatal error, but we will retry anyway
16144 	 * as some drives report this as a spurious error.
16145 	 */
16146 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16147 	    &si, EIO, (clock_t)0, NULL);
16148 }
16149 
16150 
16151 
16152 /*
16153  *    Function: sd_sense_key_illegal_request
16154  *
16155  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
16156  *
16157  *     Context: May be called from interrupt context
16158  */
16159 
16160 static void
16161 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
16162 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16163 {
16164 	struct sd_sense_info	si;
16165 
16166 	ASSERT(un != NULL);
16167 	ASSERT(mutex_owned(SD_MUTEX(un)));
16168 	ASSERT(bp != NULL);
16169 	ASSERT(xp != NULL);
16170 	ASSERT(pktp != NULL);
16171 
16172 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
16173 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
16174 
16175 	si.ssi_severity = SCSI_ERR_INFO;
16176 	si.ssi_pfa_flag = FALSE;
16177 
16178 	/* Pointless to retry if the target thinks it's an illegal request */
16179 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16180 	sd_return_failed_command(un, bp, EIO);
16181 }
16182 
16183 
16184 
16185 
16186 /*
16187  *    Function: sd_sense_key_unit_attention
16188  *
16189  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
16190  *
16191  *     Context: May be called from interrupt context
16192  */
16193 
16194 static void
16195 sd_sense_key_unit_attention(struct sd_lun *un,
16196 	uint8_t *sense_datap,
16197 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16198 {
16199 	/*
16200 	 * For UNIT ATTENTION we allow retries for one minute. Devices
16201 	 * like Sonoma can return UNIT ATTENTION close to a minute
16202 	 * under certain conditions.
16203 	 */
16204 	int	retry_check_flag = SD_RETRIES_UA;
16205 	boolean_t	kstat_updated = B_FALSE;
16206 	struct	sd_sense_info		si;
16207 	uint8_t asc = scsi_sense_asc(sense_datap);
16208 
16209 	ASSERT(un != NULL);
16210 	ASSERT(mutex_owned(SD_MUTEX(un)));
16211 	ASSERT(bp != NULL);
16212 	ASSERT(xp != NULL);
16213 	ASSERT(pktp != NULL);
16214 
16215 	si.ssi_severity = SCSI_ERR_INFO;
16216 	si.ssi_pfa_flag = FALSE;
16217 
16218 
16219 	switch (asc) {
16220 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
16221 		if (sd_report_pfa != 0) {
16222 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
16223 			si.ssi_pfa_flag = TRUE;
16224 			retry_check_flag = SD_RETRIES_STANDARD;
16225 			goto do_retry;
16226 		}
16227 
16228 		break;
16229 
16230 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
16231 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
16232 			un->un_resvd_status |=
16233 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
16234 		}
16235 #ifdef _LP64
16236 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
16237 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
16238 			    un, KM_NOSLEEP) == 0) {
16239 				/*
16240 				 * If we can't dispatch the task we'll just
16241 				 * live without descriptor sense.  We can
16242 				 * try again on the next "unit attention"
16243 				 */
16244 				SD_ERROR(SD_LOG_ERROR, un,
16245 				    "sd_sense_key_unit_attention: "
16246 				    "Could not dispatch "
16247 				    "sd_reenable_dsense_task\n");
16248 			}
16249 		}
16250 #endif /* _LP64 */
16251 		/* FALLTHRU */
16252 
16253 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
16254 		if (!un->un_f_has_removable_media) {
16255 			break;
16256 		}
16257 
16258 		/*
16259 		 * When we get a unit attention from a removable-media device,
16260 		 * it may be in a state that will take a long time to recover
16261 		 * (e.g., from a reset).  Since we are executing in interrupt
16262 		 * context here, we cannot wait around for the device to come
16263 		 * back. So hand this command off to sd_media_change_task()
16264 		 * for deferred processing under taskq thread context. (Note
16265 		 * that the command still may be failed if a problem is
16266 		 * encountered at a later time.)
16267 		 */
16268 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
16269 		    KM_NOSLEEP) == 0) {
16270 			/*
16271 			 * Cannot dispatch the request so fail the command.
16272 			 */
16273 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
16274 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16275 			si.ssi_severity = SCSI_ERR_FATAL;
16276 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16277 			sd_return_failed_command(un, bp, EIO);
16278 		}
16279 
16280 		/*
16281 		 * If failed to dispatch sd_media_change_task(), we already
16282 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
16283 		 * we should update kstat later if it encounters an error. So,
16284 		 * we update kstat_updated flag here.
16285 		 */
16286 		kstat_updated = B_TRUE;
16287 
16288 		/*
16289 		 * Either the command has been successfully dispatched to a
16290 		 * task Q for retrying, or the dispatch failed. In either case
16291 		 * do NOT retry again by calling sd_retry_command. This sets up
16292 		 * two retries of the same command and when one completes and
16293 		 * frees the resources the other will access freed memory,
16294 		 * a bad thing.
16295 		 */
16296 		return;
16297 
16298 	default:
16299 		break;
16300 	}
16301 
16302 	/*
16303 	 * Update kstat if we haven't done that.
16304 	 */
16305 	if (!kstat_updated) {
16306 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16307 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16308 	}
16309 
16310 do_retry:
16311 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
16312 	    EIO, SD_UA_RETRY_DELAY, NULL);
16313 }
16314 
16315 
16316 
16317 /*
16318  *    Function: sd_sense_key_fail_command
16319  *
16320  * Description: Use to fail a command when we don't like the sense key that
16321  *		was returned.
16322  *
16323  *     Context: May be called from interrupt context
16324  */
16325 
16326 static void
16327 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
16328 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16329 {
16330 	struct sd_sense_info	si;
16331 
16332 	ASSERT(un != NULL);
16333 	ASSERT(mutex_owned(SD_MUTEX(un)));
16334 	ASSERT(bp != NULL);
16335 	ASSERT(xp != NULL);
16336 	ASSERT(pktp != NULL);
16337 
16338 	si.ssi_severity = SCSI_ERR_FATAL;
16339 	si.ssi_pfa_flag = FALSE;
16340 
16341 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16342 	sd_return_failed_command(un, bp, EIO);
16343 }
16344 
16345 
16346 
16347 /*
16348  *    Function: sd_sense_key_blank_check
16349  *
16350  * Description: Recovery actions for a SCSI "Blank Check" sense key.
16351  *		Has no monetary connotation.
16352  *
16353  *     Context: May be called from interrupt context
16354  */
16355 
16356 static void
16357 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
16358 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16359 {
16360 	struct sd_sense_info	si;
16361 
16362 	ASSERT(un != NULL);
16363 	ASSERT(mutex_owned(SD_MUTEX(un)));
16364 	ASSERT(bp != NULL);
16365 	ASSERT(xp != NULL);
16366 	ASSERT(pktp != NULL);
16367 
16368 	/*
16369 	 * Blank check is not fatal for removable devices, therefore
16370 	 * it does not require a console message.
16371 	 */
16372 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
16373 	    SCSI_ERR_FATAL;
16374 	si.ssi_pfa_flag = FALSE;
16375 
16376 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16377 	sd_return_failed_command(un, bp, EIO);
16378 }
16379 
16380 
16381 
16382 
16383 /*
16384  *    Function: sd_sense_key_aborted_command
16385  *
16386  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
16387  *
16388  *     Context: May be called from interrupt context
16389  */
16390 
16391 static void
16392 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
16393 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16394 {
16395 	struct sd_sense_info	si;
16396 
16397 	ASSERT(un != NULL);
16398 	ASSERT(mutex_owned(SD_MUTEX(un)));
16399 	ASSERT(bp != NULL);
16400 	ASSERT(xp != NULL);
16401 	ASSERT(pktp != NULL);
16402 
16403 	si.ssi_severity = SCSI_ERR_FATAL;
16404 	si.ssi_pfa_flag = FALSE;
16405 
16406 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16407 
16408 	/*
16409 	 * This really ought to be a fatal error, but we will retry anyway
16410 	 * as some drives report this as a spurious error.
16411 	 */
16412 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16413 	    &si, EIO, drv_usectohz(100000), NULL);
16414 }
16415 
16416 
16417 
16418 /*
16419  *    Function: sd_sense_key_default
16420  *
16421  * Description: Default recovery action for several SCSI sense keys (basically
16422  *		attempts a retry).
16423  *
16424  *     Context: May be called from interrupt context
16425  */
16426 
16427 static void
16428 sd_sense_key_default(struct sd_lun *un,
16429 	uint8_t *sense_datap,
16430 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16431 {
16432 	struct sd_sense_info	si;
16433 	uint8_t sense_key = scsi_sense_key(sense_datap);
16434 
16435 	ASSERT(un != NULL);
16436 	ASSERT(mutex_owned(SD_MUTEX(un)));
16437 	ASSERT(bp != NULL);
16438 	ASSERT(xp != NULL);
16439 	ASSERT(pktp != NULL);
16440 
16441 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16442 
16443 	/*
16444 	 * Undecoded sense key.	Attempt retries and hope that will fix
16445 	 * the problem.  Otherwise, we're dead.
16446 	 */
16447 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
16448 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16449 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
16450 	}
16451 
16452 	si.ssi_severity = SCSI_ERR_FATAL;
16453 	si.ssi_pfa_flag = FALSE;
16454 
16455 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16456 	    &si, EIO, (clock_t)0, NULL);
16457 }
16458 
16459 
16460 
16461 /*
16462  *    Function: sd_print_retry_msg
16463  *
16464  * Description: Print a message indicating the retry action being taken.
16465  *
16466  *   Arguments: un - ptr to associated softstate
16467  *		bp - ptr to buf(9S) for the command
16468  *		arg - not used.
16469  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16470  *			or SD_NO_RETRY_ISSUED
16471  *
16472  *     Context: May be called from interrupt context
16473  */
16474 /* ARGSUSED */
16475 static void
16476 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
16477 {
16478 	struct sd_xbuf	*xp;
16479 	struct scsi_pkt *pktp;
16480 	char *reasonp;
16481 	char *msgp;
16482 
16483 	ASSERT(un != NULL);
16484 	ASSERT(mutex_owned(SD_MUTEX(un)));
16485 	ASSERT(bp != NULL);
16486 	pktp = SD_GET_PKTP(bp);
16487 	ASSERT(pktp != NULL);
16488 	xp = SD_GET_XBUF(bp);
16489 	ASSERT(xp != NULL);
16490 
16491 	ASSERT(!mutex_owned(&un->un_pm_mutex));
16492 	mutex_enter(&un->un_pm_mutex);
16493 	if ((un->un_state == SD_STATE_SUSPENDED) ||
16494 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
16495 	    (pktp->pkt_flags & FLAG_SILENT)) {
16496 		mutex_exit(&un->un_pm_mutex);
16497 		goto update_pkt_reason;
16498 	}
16499 	mutex_exit(&un->un_pm_mutex);
16500 
16501 	/*
16502 	 * Suppress messages if they are all the same pkt_reason; with
16503 	 * TQ, many (up to 256) are returned with the same pkt_reason.
16504 	 * If we are in panic, then suppress the retry messages.
16505 	 */
16506 	switch (flag) {
16507 	case SD_NO_RETRY_ISSUED:
16508 		msgp = "giving up";
16509 		break;
16510 	case SD_IMMEDIATE_RETRY_ISSUED:
16511 	case SD_DELAYED_RETRY_ISSUED:
16512 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
16513 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
16514 		    (sd_error_level != SCSI_ERR_ALL))) {
16515 			return;
16516 		}
16517 		msgp = "retrying command";
16518 		break;
16519 	default:
16520 		goto update_pkt_reason;
16521 	}
16522 
16523 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
16524 	    scsi_rname(pktp->pkt_reason));
16525 
16526 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16527 	    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
16528 
16529 update_pkt_reason:
16530 	/*
16531 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
16532 	 * This is to prevent multiple console messages for the same failure
16533 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
16534 	 * when the command is retried successfully because there still may be
16535 	 * more commands coming back with the same value of pktp->pkt_reason.
16536 	 */
16537 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
16538 		un->un_last_pkt_reason = pktp->pkt_reason;
16539 	}
16540 }
16541 
16542 
16543 /*
16544  *    Function: sd_print_cmd_incomplete_msg
16545  *
16546  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
16547  *
16548  *   Arguments: un - ptr to associated softstate
16549  *		bp - ptr to buf(9S) for the command
16550  *		arg - passed to sd_print_retry_msg()
16551  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16552  *			or SD_NO_RETRY_ISSUED
16553  *
16554  *     Context: May be called from interrupt context
16555  */
16556 
16557 static void
16558 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
16559 	int code)
16560 {
16561 	dev_info_t	*dip;
16562 
16563 	ASSERT(un != NULL);
16564 	ASSERT(mutex_owned(SD_MUTEX(un)));
16565 	ASSERT(bp != NULL);
16566 
16567 	switch (code) {
16568 	case SD_NO_RETRY_ISSUED:
16569 		/* Command was failed. Someone turned off this target? */
16570 		if (un->un_state != SD_STATE_OFFLINE) {
16571 			/*
16572 			 * Suppress message if we are detaching and
16573 			 * device has been disconnected
16574 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
16575 			 * private interface and not part of the DDI
16576 			 */
16577 			dip = un->un_sd->sd_dev;
16578 			if (!(DEVI_IS_DETACHING(dip) &&
16579 			    DEVI_IS_DEVICE_REMOVED(dip))) {
16580 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16581 				"disk not responding to selection\n");
16582 			}
16583 			New_state(un, SD_STATE_OFFLINE);
16584 		}
16585 		break;
16586 
16587 	case SD_DELAYED_RETRY_ISSUED:
16588 	case SD_IMMEDIATE_RETRY_ISSUED:
16589 	default:
16590 		/* Command was successfully queued for retry */
16591 		sd_print_retry_msg(un, bp, arg, code);
16592 		break;
16593 	}
16594 }
16595 
16596 
16597 /*
16598  *    Function: sd_pkt_reason_cmd_incomplete
16599  *
16600  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
16601  *
16602  *     Context: May be called from interrupt context
16603  */
16604 
16605 static void
16606 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
16607 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16608 {
16609 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
16610 
16611 	ASSERT(un != NULL);
16612 	ASSERT(mutex_owned(SD_MUTEX(un)));
16613 	ASSERT(bp != NULL);
16614 	ASSERT(xp != NULL);
16615 	ASSERT(pktp != NULL);
16616 
16617 	/* Do not do a reset if selection did not complete */
16618 	/* Note: Should this not just check the bit? */
16619 	if (pktp->pkt_state != STATE_GOT_BUS) {
16620 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
16621 		sd_reset_target(un, pktp);
16622 	}
16623 
16624 	/*
16625 	 * If the target was not successfully selected, then set
16626 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
16627 	 * with the target, and further retries and/or commands are
16628 	 * likely to take a long time.
16629 	 */
16630 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
16631 		flag |= SD_RETRIES_FAILFAST;
16632 	}
16633 
16634 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16635 
16636 	sd_retry_command(un, bp, flag,
16637 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16638 }
16639 
16640 
16641 
16642 /*
16643  *    Function: sd_pkt_reason_cmd_tran_err
16644  *
16645  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
16646  *
16647  *     Context: May be called from interrupt context
16648  */
16649 
16650 static void
16651 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
16652 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16653 {
16654 	ASSERT(un != NULL);
16655 	ASSERT(mutex_owned(SD_MUTEX(un)));
16656 	ASSERT(bp != NULL);
16657 	ASSERT(xp != NULL);
16658 	ASSERT(pktp != NULL);
16659 
16660 	/*
16661 	 * Do not reset if we got a parity error, or if
16662 	 * selection did not complete.
16663 	 */
16664 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16665 	/* Note: Should this not just check the bit for pkt_state? */
16666 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
16667 	    (pktp->pkt_state != STATE_GOT_BUS)) {
16668 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
16669 		sd_reset_target(un, pktp);
16670 	}
16671 
16672 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16673 
16674 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
16675 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16676 }
16677 
16678 
16679 
16680 /*
16681  *    Function: sd_pkt_reason_cmd_reset
16682  *
16683  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
16684  *
16685  *     Context: May be called from interrupt context
16686  */
16687 
16688 static void
16689 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
16690 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16691 {
16692 	ASSERT(un != NULL);
16693 	ASSERT(mutex_owned(SD_MUTEX(un)));
16694 	ASSERT(bp != NULL);
16695 	ASSERT(xp != NULL);
16696 	ASSERT(pktp != NULL);
16697 
16698 	/* The target may still be running the command, so try to reset. */
16699 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16700 	sd_reset_target(un, pktp);
16701 
16702 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16703 
16704 	/*
16705 	 * If pkt_reason is CMD_RESET chances are that this pkt got
16706 	 * reset because another target on this bus caused it. The target
16707 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
16708 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
16709 	 */
16710 
16711 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
16712 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16713 }
16714 
16715 
16716 
16717 
16718 /*
16719  *    Function: sd_pkt_reason_cmd_aborted
16720  *
16721  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
16722  *
16723  *     Context: May be called from interrupt context
16724  */
16725 
16726 static void
16727 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
16728 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16729 {
16730 	ASSERT(un != NULL);
16731 	ASSERT(mutex_owned(SD_MUTEX(un)));
16732 	ASSERT(bp != NULL);
16733 	ASSERT(xp != NULL);
16734 	ASSERT(pktp != NULL);
16735 
16736 	/* The target may still be running the command, so try to reset. */
16737 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16738 	sd_reset_target(un, pktp);
16739 
16740 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16741 
16742 	/*
16743 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
16744 	 * aborted because another target on this bus caused it. The target
16745 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
16746 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
16747 	 */
16748 
16749 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
16750 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16751 }
16752 
16753 
16754 
16755 /*
16756  *    Function: sd_pkt_reason_cmd_timeout
16757  *
16758  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
16759  *
16760  *     Context: May be called from interrupt context
16761  */
16762 
16763 static void
16764 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
16765 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16766 {
16767 	ASSERT(un != NULL);
16768 	ASSERT(mutex_owned(SD_MUTEX(un)));
16769 	ASSERT(bp != NULL);
16770 	ASSERT(xp != NULL);
16771 	ASSERT(pktp != NULL);
16772 
16773 
16774 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16775 	sd_reset_target(un, pktp);
16776 
16777 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16778 
16779 	/*
16780 	 * A command timeout indicates that we could not establish
16781 	 * communication with the target, so set SD_RETRIES_FAILFAST
16782 	 * as further retries/commands are likely to take a long time.
16783 	 */
16784 	sd_retry_command(un, bp,
16785 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
16786 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16787 }
16788 
16789 
16790 
16791 /*
16792  *    Function: sd_pkt_reason_cmd_unx_bus_free
16793  *
16794  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
16795  *
16796  *     Context: May be called from interrupt context
16797  */
16798 
16799 static void
16800 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
16801 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16802 {
16803 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
16804 
16805 	ASSERT(un != NULL);
16806 	ASSERT(mutex_owned(SD_MUTEX(un)));
16807 	ASSERT(bp != NULL);
16808 	ASSERT(xp != NULL);
16809 	ASSERT(pktp != NULL);
16810 
16811 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16812 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16813 
16814 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
16815 	    sd_print_retry_msg : NULL;
16816 
16817 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
16818 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16819 }
16820 
16821 
16822 /*
16823  *    Function: sd_pkt_reason_cmd_tag_reject
16824  *
16825  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
16826  *
16827  *     Context: May be called from interrupt context
16828  */
16829 
16830 static void
16831 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
16832 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16833 {
16834 	ASSERT(un != NULL);
16835 	ASSERT(mutex_owned(SD_MUTEX(un)));
16836 	ASSERT(bp != NULL);
16837 	ASSERT(xp != NULL);
16838 	ASSERT(pktp != NULL);
16839 
16840 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16841 	pktp->pkt_flags = 0;
16842 	un->un_tagflags = 0;
16843 	if (un->un_f_opt_queueing == TRUE) {
16844 		un->un_throttle = min(un->un_throttle, 3);
16845 	} else {
16846 		un->un_throttle = 1;
16847 	}
16848 	mutex_exit(SD_MUTEX(un));
16849 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
16850 	mutex_enter(SD_MUTEX(un));
16851 
16852 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16853 
16854 	/* Legacy behavior not to check retry counts here. */
16855 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
16856 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16857 }
16858 
16859 
16860 /*
16861  *    Function: sd_pkt_reason_default
16862  *
16863  * Description: Default recovery actions for SCSA pkt_reason values that
16864  *		do not have more explicit recovery actions.
16865  *
16866  *     Context: May be called from interrupt context
16867  */
16868 
16869 static void
16870 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
16871 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16872 {
16873 	ASSERT(un != NULL);
16874 	ASSERT(mutex_owned(SD_MUTEX(un)));
16875 	ASSERT(bp != NULL);
16876 	ASSERT(xp != NULL);
16877 	ASSERT(pktp != NULL);
16878 
16879 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
16880 	sd_reset_target(un, pktp);
16881 
16882 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16883 
16884 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
16885 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16886 }
16887 
16888 
16889 
16890 /*
16891  *    Function: sd_pkt_status_check_condition
16892  *
16893  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
16894  *
16895  *     Context: May be called from interrupt context
16896  */
16897 
16898 static void
16899 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
16900 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16901 {
16902 	ASSERT(un != NULL);
16903 	ASSERT(mutex_owned(SD_MUTEX(un)));
16904 	ASSERT(bp != NULL);
16905 	ASSERT(xp != NULL);
16906 	ASSERT(pktp != NULL);
16907 
16908 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
16909 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
16910 
16911 	/*
16912 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
16913 	 * command will be retried after the request sense). Otherwise, retry
16914 	 * the command. Note: we are issuing the request sense even though the
16915 	 * retry limit may have been reached for the failed command.
16916 	 */
16917 	if (un->un_f_arq_enabled == FALSE) {
16918 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
16919 		    "no ARQ, sending request sense command\n");
16920 		sd_send_request_sense_command(un, bp, pktp);
16921 	} else {
16922 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
16923 		    "ARQ,retrying request sense command\n");
16924 #if defined(__i386) || defined(__amd64)
16925 		/*
16926 		 * The SD_RETRY_DELAY value need to be adjusted here
16927 		 * when SD_RETRY_DELAY change in sddef.h
16928 		 */
16929 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
16930 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
16931 		    NULL);
16932 #else
16933 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
16934 		    EIO, SD_RETRY_DELAY, NULL);
16935 #endif
16936 	}
16937 
16938 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
16939 }
16940 
16941 
16942 /*
16943  *    Function: sd_pkt_status_busy
16944  *
16945  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
16946  *
16947  *     Context: May be called from interrupt context
16948  */
16949 
16950 static void
16951 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
16952 	struct scsi_pkt *pktp)
16953 {
16954 	ASSERT(un != NULL);
16955 	ASSERT(mutex_owned(SD_MUTEX(un)));
16956 	ASSERT(bp != NULL);
16957 	ASSERT(xp != NULL);
16958 	ASSERT(pktp != NULL);
16959 
16960 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16961 	    "sd_pkt_status_busy: entry\n");
16962 
16963 	/* If retries are exhausted, just fail the command. */
16964 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
16965 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16966 		    "device busy too long\n");
16967 		sd_return_failed_command(un, bp, EIO);
16968 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16969 		    "sd_pkt_status_busy: exit\n");
16970 		return;
16971 	}
16972 	xp->xb_retry_count++;
16973 
16974 	/*
16975 	 * Try to reset the target. However, we do not want to perform
16976 	 * more than one reset if the device continues to fail. The reset
16977 	 * will be performed when the retry count reaches the reset
16978 	 * threshold.  This threshold should be set such that at least
16979 	 * one retry is issued before the reset is performed.
16980 	 */
16981 	if (xp->xb_retry_count ==
16982 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
16983 		int rval = 0;
16984 		mutex_exit(SD_MUTEX(un));
16985 		if (un->un_f_allow_bus_device_reset == TRUE) {
16986 			/*
16987 			 * First try to reset the LUN; if we cannot then
16988 			 * try to reset the target.
16989 			 */
16990 			if (un->un_f_lun_reset_enabled == TRUE) {
16991 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16992 				    "sd_pkt_status_busy: RESET_LUN\n");
16993 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
16994 			}
16995 			if (rval == 0) {
16996 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
16997 				    "sd_pkt_status_busy: RESET_TARGET\n");
16998 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
16999 			}
17000 		}
17001 		if (rval == 0) {
17002 			/*
17003 			 * If the RESET_LUN and/or RESET_TARGET failed,
17004 			 * try RESET_ALL
17005 			 */
17006 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17007 			    "sd_pkt_status_busy: RESET_ALL\n");
17008 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
17009 		}
17010 		mutex_enter(SD_MUTEX(un));
17011 		if (rval == 0) {
17012 			/*
17013 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
17014 			 * At this point we give up & fail the command.
17015 			 */
17016 			sd_return_failed_command(un, bp, EIO);
17017 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17018 			    "sd_pkt_status_busy: exit (failed cmd)\n");
17019 			return;
17020 		}
17021 	}
17022 
17023 	/*
17024 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
17025 	 * we have already checked the retry counts above.
17026 	 */
17027 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
17028 	    EIO, SD_BSY_TIMEOUT, NULL);
17029 
17030 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17031 	    "sd_pkt_status_busy: exit\n");
17032 }
17033 
17034 
17035 /*
17036  *    Function: sd_pkt_status_reservation_conflict
17037  *
17038  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
17039  *		command status.
17040  *
17041  *     Context: May be called from interrupt context
17042  */
17043 
17044 static void
17045 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
17046 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17047 {
17048 	ASSERT(un != NULL);
17049 	ASSERT(mutex_owned(SD_MUTEX(un)));
17050 	ASSERT(bp != NULL);
17051 	ASSERT(xp != NULL);
17052 	ASSERT(pktp != NULL);
17053 
17054 	/*
17055 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
17056 	 * conflict could be due to various reasons like incorrect keys, not
17057 	 * registered or not reserved etc. So, we return EACCES to the caller.
17058 	 */
17059 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
17060 		int cmd = SD_GET_PKT_OPCODE(pktp);
17061 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
17062 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
17063 			sd_return_failed_command(un, bp, EACCES);
17064 			return;
17065 		}
17066 	}
17067 
17068 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
17069 
17070 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
17071 		if (sd_failfast_enable != 0) {
17072 			/* By definition, we must panic here.... */
17073 			sd_panic_for_res_conflict(un);
17074 			/*NOTREACHED*/
17075 		}
17076 		SD_ERROR(SD_LOG_IO, un,
17077 		    "sd_handle_resv_conflict: Disk Reserved\n");
17078 		sd_return_failed_command(un, bp, EACCES);
17079 		return;
17080 	}
17081 
17082 	/*
17083 	 * 1147670: retry only if sd_retry_on_reservation_conflict
17084 	 * property is set (default is 1). Retries will not succeed
17085 	 * on a disk reserved by another initiator. HA systems
17086 	 * may reset this via sd.conf to avoid these retries.
17087 	 *
17088 	 * Note: The legacy return code for this failure is EIO, however EACCES
17089 	 * seems more appropriate for a reservation conflict.
17090 	 */
17091 	if (sd_retry_on_reservation_conflict == 0) {
17092 		SD_ERROR(SD_LOG_IO, un,
17093 		    "sd_handle_resv_conflict: Device Reserved\n");
17094 		sd_return_failed_command(un, bp, EIO);
17095 		return;
17096 	}
17097 
17098 	/*
17099 	 * Retry the command if we can.
17100 	 *
17101 	 * Note: The legacy return code for this failure is EIO, however EACCES
17102 	 * seems more appropriate for a reservation conflict.
17103 	 */
17104 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
17105 	    (clock_t)2, NULL);
17106 }
17107 
17108 
17109 
17110 /*
17111  *    Function: sd_pkt_status_qfull
17112  *
17113  * Description: Handle a QUEUE FULL condition from the target.  This can
17114  *		occur if the HBA does not handle the queue full condition.
17115  *		(Basically this means third-party HBAs as Sun HBAs will
17116  *		handle the queue full condition.)  Note that if there are
17117  *		some commands already in the transport, then the queue full
17118  *		has occurred because the queue for this nexus is actually
17119  *		full. If there are no commands in the transport, then the
17120  *		queue full is resulting from some other initiator or lun
17121  *		consuming all the resources at the target.
17122  *
17123  *     Context: May be called from interrupt context
17124  */
17125 
17126 static void
17127 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
17128 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17129 {
17130 	ASSERT(un != NULL);
17131 	ASSERT(mutex_owned(SD_MUTEX(un)));
17132 	ASSERT(bp != NULL);
17133 	ASSERT(xp != NULL);
17134 	ASSERT(pktp != NULL);
17135 
17136 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17137 	    "sd_pkt_status_qfull: entry\n");
17138 
17139 	/*
17140 	 * Just lower the QFULL throttle and retry the command.  Note that
17141 	 * we do not limit the number of retries here.
17142 	 */
17143 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
17144 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
17145 	    SD_RESTART_TIMEOUT, NULL);
17146 
17147 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17148 	    "sd_pkt_status_qfull: exit\n");
17149 }
17150 
17151 
17152 /*
17153  *    Function: sd_reset_target
17154  *
17155  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
17156  *		RESET_TARGET, or RESET_ALL.
17157  *
17158  *     Context: May be called under interrupt context.
17159  */
17160 
17161 static void
17162 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
17163 {
17164 	int rval = 0;
17165 
17166 	ASSERT(un != NULL);
17167 	ASSERT(mutex_owned(SD_MUTEX(un)));
17168 	ASSERT(pktp != NULL);
17169 
17170 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
17171 
17172 	/*
17173 	 * No need to reset if the transport layer has already done so.
17174 	 */
17175 	if ((pktp->pkt_statistics &
17176 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
17177 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17178 		    "sd_reset_target: no reset\n");
17179 		return;
17180 	}
17181 
17182 	mutex_exit(SD_MUTEX(un));
17183 
17184 	if (un->un_f_allow_bus_device_reset == TRUE) {
17185 		if (un->un_f_lun_reset_enabled == TRUE) {
17186 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17187 			    "sd_reset_target: RESET_LUN\n");
17188 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
17189 		}
17190 		if (rval == 0) {
17191 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17192 			    "sd_reset_target: RESET_TARGET\n");
17193 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
17194 		}
17195 	}
17196 
17197 	if (rval == 0) {
17198 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17199 		    "sd_reset_target: RESET_ALL\n");
17200 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
17201 	}
17202 
17203 	mutex_enter(SD_MUTEX(un));
17204 
17205 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
17206 }
17207 
17208 
17209 /*
17210  *    Function: sd_media_change_task
17211  *
17212  * Description: Recovery action for CDROM to become available.
17213  *
17214  *     Context: Executes in a taskq() thread context
17215  */
17216 
17217 static void
17218 sd_media_change_task(void *arg)
17219 {
17220 	struct	scsi_pkt	*pktp = arg;
17221 	struct	sd_lun		*un;
17222 	struct	buf		*bp;
17223 	struct	sd_xbuf		*xp;
17224 	int	err		= 0;
17225 	int	retry_count	= 0;
17226 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
17227 	struct	sd_sense_info	si;
17228 
17229 	ASSERT(pktp != NULL);
17230 	bp = (struct buf *)pktp->pkt_private;
17231 	ASSERT(bp != NULL);
17232 	xp = SD_GET_XBUF(bp);
17233 	ASSERT(xp != NULL);
17234 	un = SD_GET_UN(bp);
17235 	ASSERT(un != NULL);
17236 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17237 	ASSERT(un->un_f_monitor_media_state);
17238 
17239 	si.ssi_severity = SCSI_ERR_INFO;
17240 	si.ssi_pfa_flag = FALSE;
17241 
17242 	/*
17243 	 * When a reset is issued on a CDROM, it takes a long time to
17244 	 * recover. First few attempts to read capacity and other things
17245 	 * related to handling unit attention fail (with a ASC 0x4 and
17246 	 * ASCQ 0x1). In that case we want to do enough retries and we want
17247 	 * to limit the retries in other cases of genuine failures like
17248 	 * no media in drive.
17249 	 */
17250 	while (retry_count++ < retry_limit) {
17251 		if ((err = sd_handle_mchange(un)) == 0) {
17252 			break;
17253 		}
17254 		if (err == EAGAIN) {
17255 			retry_limit = SD_UNIT_ATTENTION_RETRY;
17256 		}
17257 		/* Sleep for 0.5 sec. & try again */
17258 		delay(drv_usectohz(500000));
17259 	}
17260 
17261 	/*
17262 	 * Dispatch (retry or fail) the original command here,
17263 	 * along with appropriate console messages....
17264 	 *
17265 	 * Must grab the mutex before calling sd_retry_command,
17266 	 * sd_print_sense_msg and sd_return_failed_command.
17267 	 */
17268 	mutex_enter(SD_MUTEX(un));
17269 	if (err != SD_CMD_SUCCESS) {
17270 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17271 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
17272 		si.ssi_severity = SCSI_ERR_FATAL;
17273 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17274 		sd_return_failed_command(un, bp, EIO);
17275 	} else {
17276 		sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
17277 		    &si, EIO, (clock_t)0, NULL);
17278 	}
17279 	mutex_exit(SD_MUTEX(un));
17280 }
17281 
17282 
17283 
17284 /*
17285  *    Function: sd_handle_mchange
17286  *
17287  * Description: Perform geometry validation & other recovery when CDROM
17288  *		has been removed from drive.
17289  *
17290  * Return Code: 0 for success
17291  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
17292  *		sd_send_scsi_READ_CAPACITY()
17293  *
17294  *     Context: Executes in a taskq() thread context
17295  */
17296 
17297 static int
17298 sd_handle_mchange(struct sd_lun *un)
17299 {
17300 	uint64_t	capacity;
17301 	uint32_t	lbasize;
17302 	int		rval;
17303 
17304 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17305 	ASSERT(un->un_f_monitor_media_state);
17306 
17307 	if ((rval = sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
17308 	    SD_PATH_DIRECT_PRIORITY)) != 0) {
17309 		return (rval);
17310 	}
17311 
17312 	mutex_enter(SD_MUTEX(un));
17313 	sd_update_block_info(un, lbasize, capacity);
17314 
17315 	if (un->un_errstats != NULL) {
17316 		struct	sd_errstats *stp =
17317 		    (struct sd_errstats *)un->un_errstats->ks_data;
17318 		stp->sd_capacity.value.ui64 = (uint64_t)
17319 		    ((uint64_t)un->un_blockcount *
17320 		    (uint64_t)un->un_tgt_blocksize);
17321 	}
17322 
17323 
17324 	/*
17325 	 * Check if the media in the device is writable or not
17326 	 */
17327 	if (ISCD(un))
17328 		sd_check_for_writable_cd(un, SD_PATH_DIRECT_PRIORITY);
17329 
17330 	/*
17331 	 * Note: Maybe let the strategy/partitioning chain worry about getting
17332 	 * valid geometry.
17333 	 */
17334 	mutex_exit(SD_MUTEX(un));
17335 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
17336 
17337 
17338 	if (cmlb_validate(un->un_cmlbhandle, 0,
17339 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
17340 		return (EIO);
17341 	} else {
17342 		if (un->un_f_pkstats_enabled) {
17343 			sd_set_pstats(un);
17344 			SD_TRACE(SD_LOG_IO_PARTITION, un,
17345 			    "sd_handle_mchange: un:0x%p pstats created and "
17346 			    "set\n", un);
17347 		}
17348 	}
17349 
17350 
17351 	/*
17352 	 * Try to lock the door
17353 	 */
17354 	return (sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
17355 	    SD_PATH_DIRECT_PRIORITY));
17356 }
17357 
17358 
17359 /*
17360  *    Function: sd_send_scsi_DOORLOCK
17361  *
17362  * Description: Issue the scsi DOOR LOCK command
17363  *
17364  *   Arguments: un    - pointer to driver soft state (unit) structure for
17365  *			this target.
17366  *		flag  - SD_REMOVAL_ALLOW
17367  *			SD_REMOVAL_PREVENT
17368  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17369  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17370  *			to use the USCSI "direct" chain and bypass the normal
17371  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17372  *			command is issued as part of an error recovery action.
17373  *
17374  * Return Code: 0   - Success
17375  *		errno return code from sd_send_scsi_cmd()
17376  *
17377  *     Context: Can sleep.
17378  */
17379 
17380 static int
17381 sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag)
17382 {
17383 	union scsi_cdb		cdb;
17384 	struct uscsi_cmd	ucmd_buf;
17385 	struct scsi_extended_sense	sense_buf;
17386 	int			status;
17387 
17388 	ASSERT(un != NULL);
17389 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17390 
17391 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
17392 
17393 	/* already determined doorlock is not supported, fake success */
17394 	if (un->un_f_doorlock_supported == FALSE) {
17395 		return (0);
17396 	}
17397 
17398 	/*
17399 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
17400 	 * ignore the command so we can complete the eject
17401 	 * operation.
17402 	 */
17403 	if (flag == SD_REMOVAL_PREVENT) {
17404 		mutex_enter(SD_MUTEX(un));
17405 		if (un->un_f_ejecting == TRUE) {
17406 			mutex_exit(SD_MUTEX(un));
17407 			return (EAGAIN);
17408 		}
17409 		mutex_exit(SD_MUTEX(un));
17410 	}
17411 
17412 	bzero(&cdb, sizeof (cdb));
17413 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17414 
17415 	cdb.scc_cmd = SCMD_DOORLOCK;
17416 	cdb.cdb_opaque[4] = (uchar_t)flag;
17417 
17418 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17419 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
17420 	ucmd_buf.uscsi_bufaddr	= NULL;
17421 	ucmd_buf.uscsi_buflen	= 0;
17422 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17423 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17424 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
17425 	ucmd_buf.uscsi_timeout	= 15;
17426 
17427 	SD_TRACE(SD_LOG_IO, un,
17428 	    "sd_send_scsi_DOORLOCK: returning sd_send_scsi_cmd()\n");
17429 
17430 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17431 	    UIO_SYSSPACE, path_flag);
17432 
17433 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
17434 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17435 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
17436 		/* fake success and skip subsequent doorlock commands */
17437 		un->un_f_doorlock_supported = FALSE;
17438 		return (0);
17439 	}
17440 
17441 	return (status);
17442 }
17443 
17444 /*
17445  *    Function: sd_send_scsi_READ_CAPACITY
17446  *
17447  * Description: This routine uses the scsi READ CAPACITY command to determine
17448  *		the device capacity in number of blocks and the device native
17449  *		block size. If this function returns a failure, then the
17450  *		values in *capp and *lbap are undefined.  If the capacity
17451  *		returned is 0xffffffff then the lun is too large for a
17452  *		normal READ CAPACITY command and the results of a
17453  *		READ CAPACITY 16 will be used instead.
17454  *
17455  *   Arguments: un   - ptr to soft state struct for the target
17456  *		capp - ptr to unsigned 64-bit variable to receive the
17457  *			capacity value from the command.
17458  *		lbap - ptr to unsigned 32-bit varaible to receive the
17459  *			block size value from the command
17460  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17461  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17462  *			to use the USCSI "direct" chain and bypass the normal
17463  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17464  *			command is issued as part of an error recovery action.
17465  *
17466  * Return Code: 0   - Success
17467  *		EIO - IO error
17468  *		EACCES - Reservation conflict detected
17469  *		EAGAIN - Device is becoming ready
17470  *		errno return code from sd_send_scsi_cmd()
17471  *
17472  *     Context: Can sleep.  Blocks until command completes.
17473  */
17474 
17475 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
17476 
17477 static int
17478 sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp, uint32_t *lbap,
17479 	int path_flag)
17480 {
17481 	struct	scsi_extended_sense	sense_buf;
17482 	struct	uscsi_cmd	ucmd_buf;
17483 	union	scsi_cdb	cdb;
17484 	uint32_t		*capacity_buf;
17485 	uint64_t		capacity;
17486 	uint32_t		lbasize;
17487 	int			status;
17488 
17489 	ASSERT(un != NULL);
17490 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17491 	ASSERT(capp != NULL);
17492 	ASSERT(lbap != NULL);
17493 
17494 	SD_TRACE(SD_LOG_IO, un,
17495 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
17496 
17497 	/*
17498 	 * First send a READ_CAPACITY command to the target.
17499 	 * (This command is mandatory under SCSI-2.)
17500 	 *
17501 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
17502 	 * Medium Indicator bit is cleared.  The address field must be
17503 	 * zero if the PMI bit is zero.
17504 	 */
17505 	bzero(&cdb, sizeof (cdb));
17506 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17507 
17508 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
17509 
17510 	cdb.scc_cmd = SCMD_READ_CAPACITY;
17511 
17512 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17513 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
17514 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
17515 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
17516 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17517 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17518 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
17519 	ucmd_buf.uscsi_timeout	= 60;
17520 
17521 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17522 	    UIO_SYSSPACE, path_flag);
17523 
17524 	switch (status) {
17525 	case 0:
17526 		/* Return failure if we did not get valid capacity data. */
17527 		if (ucmd_buf.uscsi_resid != 0) {
17528 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17529 			return (EIO);
17530 		}
17531 
17532 		/*
17533 		 * Read capacity and block size from the READ CAPACITY 10 data.
17534 		 * This data may be adjusted later due to device specific
17535 		 * issues.
17536 		 *
17537 		 * According to the SCSI spec, the READ CAPACITY 10
17538 		 * command returns the following:
17539 		 *
17540 		 *  bytes 0-3: Maximum logical block address available.
17541 		 *		(MSB in byte:0 & LSB in byte:3)
17542 		 *
17543 		 *  bytes 4-7: Block length in bytes
17544 		 *		(MSB in byte:4 & LSB in byte:7)
17545 		 *
17546 		 */
17547 		capacity = BE_32(capacity_buf[0]);
17548 		lbasize = BE_32(capacity_buf[1]);
17549 
17550 		/*
17551 		 * Done with capacity_buf
17552 		 */
17553 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17554 
17555 		/*
17556 		 * if the reported capacity is set to all 0xf's, then
17557 		 * this disk is too large and requires SBC-2 commands.
17558 		 * Reissue the request using READ CAPACITY 16.
17559 		 */
17560 		if (capacity == 0xffffffff) {
17561 			status = sd_send_scsi_READ_CAPACITY_16(un, &capacity,
17562 			    &lbasize, path_flag);
17563 			if (status != 0) {
17564 				return (status);
17565 			}
17566 		}
17567 		break;	/* Success! */
17568 	case EIO:
17569 		switch (ucmd_buf.uscsi_status) {
17570 		case STATUS_RESERVATION_CONFLICT:
17571 			status = EACCES;
17572 			break;
17573 		case STATUS_CHECK:
17574 			/*
17575 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
17576 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
17577 			 */
17578 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17579 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
17580 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
17581 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17582 				return (EAGAIN);
17583 			}
17584 			break;
17585 		default:
17586 			break;
17587 		}
17588 		/* FALLTHRU */
17589 	default:
17590 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17591 		return (status);
17592 	}
17593 
17594 	/*
17595 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
17596 	 * (2352 and 0 are common) so for these devices always force the value
17597 	 * to 2048 as required by the ATAPI specs.
17598 	 */
17599 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
17600 		lbasize = 2048;
17601 	}
17602 
17603 	/*
17604 	 * Get the maximum LBA value from the READ CAPACITY data.
17605 	 * Here we assume that the Partial Medium Indicator (PMI) bit
17606 	 * was cleared when issuing the command. This means that the LBA
17607 	 * returned from the device is the LBA of the last logical block
17608 	 * on the logical unit.  The actual logical block count will be
17609 	 * this value plus one.
17610 	 *
17611 	 * Currently the capacity is saved in terms of un->un_sys_blocksize,
17612 	 * so scale the capacity value to reflect this.
17613 	 */
17614 	capacity = (capacity + 1) * (lbasize / un->un_sys_blocksize);
17615 
17616 	/*
17617 	 * Copy the values from the READ CAPACITY command into the space
17618 	 * provided by the caller.
17619 	 */
17620 	*capp = capacity;
17621 	*lbap = lbasize;
17622 
17623 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
17624 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
17625 
17626 	/*
17627 	 * Both the lbasize and capacity from the device must be nonzero,
17628 	 * otherwise we assume that the values are not valid and return
17629 	 * failure to the caller. (4203735)
17630 	 */
17631 	if ((capacity == 0) || (lbasize == 0)) {
17632 		return (EIO);
17633 	}
17634 
17635 	return (0);
17636 }
17637 
17638 /*
17639  *    Function: sd_send_scsi_READ_CAPACITY_16
17640  *
17641  * Description: This routine uses the scsi READ CAPACITY 16 command to
17642  *		determine the device capacity in number of blocks and the
17643  *		device native block size.  If this function returns a failure,
17644  *		then the values in *capp and *lbap are undefined.
17645  *		This routine should always be called by
17646  *		sd_send_scsi_READ_CAPACITY which will appy any device
17647  *		specific adjustments to capacity and lbasize.
17648  *
17649  *   Arguments: un   - ptr to soft state struct for the target
17650  *		capp - ptr to unsigned 64-bit variable to receive the
17651  *			capacity value from the command.
17652  *		lbap - ptr to unsigned 32-bit varaible to receive the
17653  *			block size value from the command
17654  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17655  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17656  *			to use the USCSI "direct" chain and bypass the normal
17657  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
17658  *			this command is issued as part of an error recovery
17659  *			action.
17660  *
17661  * Return Code: 0   - Success
17662  *		EIO - IO error
17663  *		EACCES - Reservation conflict detected
17664  *		EAGAIN - Device is becoming ready
17665  *		errno return code from sd_send_scsi_cmd()
17666  *
17667  *     Context: Can sleep.  Blocks until command completes.
17668  */
17669 
17670 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
17671 
17672 static int
17673 sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
17674 	uint32_t *lbap, int path_flag)
17675 {
17676 	struct	scsi_extended_sense	sense_buf;
17677 	struct	uscsi_cmd	ucmd_buf;
17678 	union	scsi_cdb	cdb;
17679 	uint64_t		*capacity16_buf;
17680 	uint64_t		capacity;
17681 	uint32_t		lbasize;
17682 	int			status;
17683 
17684 	ASSERT(un != NULL);
17685 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17686 	ASSERT(capp != NULL);
17687 	ASSERT(lbap != NULL);
17688 
17689 	SD_TRACE(SD_LOG_IO, un,
17690 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
17691 
17692 	/*
17693 	 * First send a READ_CAPACITY_16 command to the target.
17694 	 *
17695 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
17696 	 * Medium Indicator bit is cleared.  The address field must be
17697 	 * zero if the PMI bit is zero.
17698 	 */
17699 	bzero(&cdb, sizeof (cdb));
17700 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17701 
17702 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
17703 
17704 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17705 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
17706 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
17707 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
17708 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17709 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17710 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
17711 	ucmd_buf.uscsi_timeout	= 60;
17712 
17713 	/*
17714 	 * Read Capacity (16) is a Service Action In command.  One
17715 	 * command byte (0x9E) is overloaded for multiple operations,
17716 	 * with the second CDB byte specifying the desired operation
17717 	 */
17718 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
17719 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
17720 
17721 	/*
17722 	 * Fill in allocation length field
17723 	 */
17724 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
17725 
17726 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17727 	    UIO_SYSSPACE, path_flag);
17728 
17729 	switch (status) {
17730 	case 0:
17731 		/* Return failure if we did not get valid capacity data. */
17732 		if (ucmd_buf.uscsi_resid > 20) {
17733 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17734 			return (EIO);
17735 		}
17736 
17737 		/*
17738 		 * Read capacity and block size from the READ CAPACITY 10 data.
17739 		 * This data may be adjusted later due to device specific
17740 		 * issues.
17741 		 *
17742 		 * According to the SCSI spec, the READ CAPACITY 10
17743 		 * command returns the following:
17744 		 *
17745 		 *  bytes 0-7: Maximum logical block address available.
17746 		 *		(MSB in byte:0 & LSB in byte:7)
17747 		 *
17748 		 *  bytes 8-11: Block length in bytes
17749 		 *		(MSB in byte:8 & LSB in byte:11)
17750 		 *
17751 		 */
17752 		capacity = BE_64(capacity16_buf[0]);
17753 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
17754 
17755 		/*
17756 		 * Done with capacity16_buf
17757 		 */
17758 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17759 
17760 		/*
17761 		 * if the reported capacity is set to all 0xf's, then
17762 		 * this disk is too large.  This could only happen with
17763 		 * a device that supports LBAs larger than 64 bits which
17764 		 * are not defined by any current T10 standards.
17765 		 */
17766 		if (capacity == 0xffffffffffffffff) {
17767 			return (EIO);
17768 		}
17769 		break;	/* Success! */
17770 	case EIO:
17771 		switch (ucmd_buf.uscsi_status) {
17772 		case STATUS_RESERVATION_CONFLICT:
17773 			status = EACCES;
17774 			break;
17775 		case STATUS_CHECK:
17776 			/*
17777 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
17778 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
17779 			 */
17780 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17781 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
17782 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
17783 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17784 				return (EAGAIN);
17785 			}
17786 			break;
17787 		default:
17788 			break;
17789 		}
17790 		/* FALLTHRU */
17791 	default:
17792 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
17793 		return (status);
17794 	}
17795 
17796 	*capp = capacity;
17797 	*lbap = lbasize;
17798 
17799 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
17800 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
17801 
17802 	return (0);
17803 }
17804 
17805 
17806 /*
17807  *    Function: sd_send_scsi_START_STOP_UNIT
17808  *
17809  * Description: Issue a scsi START STOP UNIT command to the target.
17810  *
17811  *   Arguments: un    - pointer to driver soft state (unit) structure for
17812  *			this target.
17813  *		flag  - SD_TARGET_START
17814  *			SD_TARGET_STOP
17815  *			SD_TARGET_EJECT
17816  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17817  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17818  *			to use the USCSI "direct" chain and bypass the normal
17819  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17820  *			command is issued as part of an error recovery action.
17821  *
17822  * Return Code: 0   - Success
17823  *		EIO - IO error
17824  *		EACCES - Reservation conflict detected
17825  *		ENXIO  - Not Ready, medium not present
17826  *		errno return code from sd_send_scsi_cmd()
17827  *
17828  *     Context: Can sleep.
17829  */
17830 
17831 static int
17832 sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag, int path_flag)
17833 {
17834 	struct	scsi_extended_sense	sense_buf;
17835 	union scsi_cdb		cdb;
17836 	struct uscsi_cmd	ucmd_buf;
17837 	int			status;
17838 
17839 	ASSERT(un != NULL);
17840 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17841 
17842 	SD_TRACE(SD_LOG_IO, un,
17843 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
17844 
17845 	if (un->un_f_check_start_stop &&
17846 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
17847 	    (un->un_f_start_stop_supported != TRUE)) {
17848 		return (0);
17849 	}
17850 
17851 	/*
17852 	 * If we are performing an eject operation and
17853 	 * we receive any command other than SD_TARGET_EJECT
17854 	 * we should immediately return.
17855 	 */
17856 	if (flag != SD_TARGET_EJECT) {
17857 		mutex_enter(SD_MUTEX(un));
17858 		if (un->un_f_ejecting == TRUE) {
17859 			mutex_exit(SD_MUTEX(un));
17860 			return (EAGAIN);
17861 		}
17862 		mutex_exit(SD_MUTEX(un));
17863 	}
17864 
17865 	bzero(&cdb, sizeof (cdb));
17866 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17867 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
17868 
17869 	cdb.scc_cmd = SCMD_START_STOP;
17870 	cdb.cdb_opaque[4] = (uchar_t)flag;
17871 
17872 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17873 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
17874 	ucmd_buf.uscsi_bufaddr	= NULL;
17875 	ucmd_buf.uscsi_buflen	= 0;
17876 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17877 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
17878 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
17879 	ucmd_buf.uscsi_timeout	= 200;
17880 
17881 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17882 	    UIO_SYSSPACE, path_flag);
17883 
17884 	switch (status) {
17885 	case 0:
17886 		break;	/* Success! */
17887 	case EIO:
17888 		switch (ucmd_buf.uscsi_status) {
17889 		case STATUS_RESERVATION_CONFLICT:
17890 			status = EACCES;
17891 			break;
17892 		case STATUS_CHECK:
17893 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
17894 				switch (scsi_sense_key(
17895 				    (uint8_t *)&sense_buf)) {
17896 				case KEY_ILLEGAL_REQUEST:
17897 					status = ENOTSUP;
17898 					break;
17899 				case KEY_NOT_READY:
17900 					if (scsi_sense_asc(
17901 					    (uint8_t *)&sense_buf)
17902 					    == 0x3A) {
17903 						status = ENXIO;
17904 					}
17905 					break;
17906 				default:
17907 					break;
17908 				}
17909 			}
17910 			break;
17911 		default:
17912 			break;
17913 		}
17914 		break;
17915 	default:
17916 		break;
17917 	}
17918 
17919 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
17920 
17921 	return (status);
17922 }
17923 
17924 
17925 /*
17926  *    Function: sd_start_stop_unit_callback
17927  *
17928  * Description: timeout(9F) callback to begin recovery process for a
17929  *		device that has spun down.
17930  *
17931  *   Arguments: arg - pointer to associated softstate struct.
17932  *
17933  *     Context: Executes in a timeout(9F) thread context
17934  */
17935 
17936 static void
17937 sd_start_stop_unit_callback(void *arg)
17938 {
17939 	struct sd_lun	*un = arg;
17940 	ASSERT(un != NULL);
17941 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17942 
17943 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
17944 
17945 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
17946 }
17947 
17948 
17949 /*
17950  *    Function: sd_start_stop_unit_task
17951  *
17952  * Description: Recovery procedure when a drive is spun down.
17953  *
17954  *   Arguments: arg - pointer to associated softstate struct.
17955  *
17956  *     Context: Executes in a taskq() thread context
17957  */
17958 
17959 static void
17960 sd_start_stop_unit_task(void *arg)
17961 {
17962 	struct sd_lun	*un = arg;
17963 
17964 	ASSERT(un != NULL);
17965 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17966 
17967 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
17968 
17969 	/*
17970 	 * Some unformatted drives report not ready error, no need to
17971 	 * restart if format has been initiated.
17972 	 */
17973 	mutex_enter(SD_MUTEX(un));
17974 	if (un->un_f_format_in_progress == TRUE) {
17975 		mutex_exit(SD_MUTEX(un));
17976 		return;
17977 	}
17978 	mutex_exit(SD_MUTEX(un));
17979 
17980 	/*
17981 	 * When a START STOP command is issued from here, it is part of a
17982 	 * failure recovery operation and must be issued before any other
17983 	 * commands, including any pending retries. Thus it must be sent
17984 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
17985 	 * succeeds or not, we will start I/O after the attempt.
17986 	 */
17987 	(void) sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
17988 	    SD_PATH_DIRECT_PRIORITY);
17989 
17990 	/*
17991 	 * The above call blocks until the START_STOP_UNIT command completes.
17992 	 * Now that it has completed, we must re-try the original IO that
17993 	 * received the NOT READY condition in the first place. There are
17994 	 * three possible conditions here:
17995 	 *
17996 	 *  (1) The original IO is on un_retry_bp.
17997 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
17998 	 *	is NULL.
17999 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
18000 	 *	points to some other, unrelated bp.
18001 	 *
18002 	 * For each case, we must call sd_start_cmds() with un_retry_bp
18003 	 * as the argument. If un_retry_bp is NULL, this will initiate
18004 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
18005 	 * then this will process the bp on un_retry_bp. That may or may not
18006 	 * be the original IO, but that does not matter: the important thing
18007 	 * is to keep the IO processing going at this point.
18008 	 *
18009 	 * Note: This is a very specific error recovery sequence associated
18010 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
18011 	 * serialize the I/O with completion of the spin-up.
18012 	 */
18013 	mutex_enter(SD_MUTEX(un));
18014 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18015 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
18016 	    un, un->un_retry_bp);
18017 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
18018 	sd_start_cmds(un, un->un_retry_bp);
18019 	mutex_exit(SD_MUTEX(un));
18020 
18021 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
18022 }
18023 
18024 
18025 /*
18026  *    Function: sd_send_scsi_INQUIRY
18027  *
18028  * Description: Issue the scsi INQUIRY command.
18029  *
18030  *   Arguments: un
18031  *		bufaddr
18032  *		buflen
18033  *		evpd
18034  *		page_code
18035  *		page_length
18036  *
18037  * Return Code: 0   - Success
18038  *		errno return code from sd_send_scsi_cmd()
18039  *
18040  *     Context: Can sleep. Does not return until command is completed.
18041  */
18042 
18043 static int
18044 sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr, size_t buflen,
18045 	uchar_t evpd, uchar_t page_code, size_t *residp)
18046 {
18047 	union scsi_cdb		cdb;
18048 	struct uscsi_cmd	ucmd_buf;
18049 	int			status;
18050 
18051 	ASSERT(un != NULL);
18052 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18053 	ASSERT(bufaddr != NULL);
18054 
18055 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
18056 
18057 	bzero(&cdb, sizeof (cdb));
18058 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18059 	bzero(bufaddr, buflen);
18060 
18061 	cdb.scc_cmd = SCMD_INQUIRY;
18062 	cdb.cdb_opaque[1] = evpd;
18063 	cdb.cdb_opaque[2] = page_code;
18064 	FORMG0COUNT(&cdb, buflen);
18065 
18066 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18067 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18068 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
18069 	ucmd_buf.uscsi_buflen	= buflen;
18070 	ucmd_buf.uscsi_rqbuf	= NULL;
18071 	ucmd_buf.uscsi_rqlen	= 0;
18072 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
18073 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
18074 
18075 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18076 	    UIO_SYSSPACE, SD_PATH_DIRECT);
18077 
18078 	if ((status == 0) && (residp != NULL)) {
18079 		*residp = ucmd_buf.uscsi_resid;
18080 	}
18081 
18082 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
18083 
18084 	return (status);
18085 }
18086 
18087 
18088 /*
18089  *    Function: sd_send_scsi_TEST_UNIT_READY
18090  *
18091  * Description: Issue the scsi TEST UNIT READY command.
18092  *		This routine can be told to set the flag USCSI_DIAGNOSE to
18093  *		prevent retrying failed commands. Use this when the intent
18094  *		is either to check for device readiness, to clear a Unit
18095  *		Attention, or to clear any outstanding sense data.
18096  *		However under specific conditions the expected behavior
18097  *		is for retries to bring a device ready, so use the flag
18098  *		with caution.
18099  *
18100  *   Arguments: un
18101  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
18102  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
18103  *			0: dont check for media present, do retries on cmd.
18104  *
18105  * Return Code: 0   - Success
18106  *		EIO - IO error
18107  *		EACCES - Reservation conflict detected
18108  *		ENXIO  - Not Ready, medium not present
18109  *		errno return code from sd_send_scsi_cmd()
18110  *
18111  *     Context: Can sleep. Does not return until command is completed.
18112  */
18113 
18114 static int
18115 sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag)
18116 {
18117 	struct	scsi_extended_sense	sense_buf;
18118 	union scsi_cdb		cdb;
18119 	struct uscsi_cmd	ucmd_buf;
18120 	int			status;
18121 
18122 	ASSERT(un != NULL);
18123 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18124 
18125 	SD_TRACE(SD_LOG_IO, un,
18126 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
18127 
18128 	/*
18129 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
18130 	 * timeouts when they receive a TUR and the queue is not empty. Check
18131 	 * the configuration flag set during attach (indicating the drive has
18132 	 * this firmware bug) and un_ncmds_in_transport before issuing the
18133 	 * TUR. If there are
18134 	 * pending commands return success, this is a bit arbitrary but is ok
18135 	 * for non-removables (i.e. the eliteI disks) and non-clustering
18136 	 * configurations.
18137 	 */
18138 	if (un->un_f_cfg_tur_check == TRUE) {
18139 		mutex_enter(SD_MUTEX(un));
18140 		if (un->un_ncmds_in_transport != 0) {
18141 			mutex_exit(SD_MUTEX(un));
18142 			return (0);
18143 		}
18144 		mutex_exit(SD_MUTEX(un));
18145 	}
18146 
18147 	bzero(&cdb, sizeof (cdb));
18148 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18149 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18150 
18151 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
18152 
18153 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18154 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18155 	ucmd_buf.uscsi_bufaddr	= NULL;
18156 	ucmd_buf.uscsi_buflen	= 0;
18157 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18158 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18159 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18160 
18161 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
18162 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
18163 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
18164 	}
18165 	ucmd_buf.uscsi_timeout	= 60;
18166 
18167 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18168 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
18169 	    SD_PATH_STANDARD));
18170 
18171 	switch (status) {
18172 	case 0:
18173 		break;	/* Success! */
18174 	case EIO:
18175 		switch (ucmd_buf.uscsi_status) {
18176 		case STATUS_RESERVATION_CONFLICT:
18177 			status = EACCES;
18178 			break;
18179 		case STATUS_CHECK:
18180 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
18181 				break;
18182 			}
18183 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18184 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18185 			    KEY_NOT_READY) &&
18186 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
18187 				status = ENXIO;
18188 			}
18189 			break;
18190 		default:
18191 			break;
18192 		}
18193 		break;
18194 	default:
18195 		break;
18196 	}
18197 
18198 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
18199 
18200 	return (status);
18201 }
18202 
18203 
18204 /*
18205  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
18206  *
18207  * Description: Issue the scsi PERSISTENT RESERVE IN command.
18208  *
18209  *   Arguments: un
18210  *
18211  * Return Code: 0   - Success
18212  *		EACCES
18213  *		ENOTSUP
18214  *		errno return code from sd_send_scsi_cmd()
18215  *
18216  *     Context: Can sleep. Does not return until command is completed.
18217  */
18218 
18219 static int
18220 sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un, uchar_t  usr_cmd,
18221 	uint16_t data_len, uchar_t *data_bufp)
18222 {
18223 	struct scsi_extended_sense	sense_buf;
18224 	union scsi_cdb		cdb;
18225 	struct uscsi_cmd	ucmd_buf;
18226 	int			status;
18227 	int			no_caller_buf = FALSE;
18228 
18229 	ASSERT(un != NULL);
18230 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18231 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
18232 
18233 	SD_TRACE(SD_LOG_IO, un,
18234 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
18235 
18236 	bzero(&cdb, sizeof (cdb));
18237 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18238 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18239 	if (data_bufp == NULL) {
18240 		/* Allocate a default buf if the caller did not give one */
18241 		ASSERT(data_len == 0);
18242 		data_len  = MHIOC_RESV_KEY_SIZE;
18243 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
18244 		no_caller_buf = TRUE;
18245 	}
18246 
18247 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
18248 	cdb.cdb_opaque[1] = usr_cmd;
18249 	FORMG1COUNT(&cdb, data_len);
18250 
18251 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18252 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18253 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
18254 	ucmd_buf.uscsi_buflen	= data_len;
18255 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18256 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18257 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
18258 	ucmd_buf.uscsi_timeout	= 60;
18259 
18260 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18261 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18262 
18263 	switch (status) {
18264 	case 0:
18265 		break;	/* Success! */
18266 	case EIO:
18267 		switch (ucmd_buf.uscsi_status) {
18268 		case STATUS_RESERVATION_CONFLICT:
18269 			status = EACCES;
18270 			break;
18271 		case STATUS_CHECK:
18272 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18273 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18274 			    KEY_ILLEGAL_REQUEST)) {
18275 				status = ENOTSUP;
18276 			}
18277 			break;
18278 		default:
18279 			break;
18280 		}
18281 		break;
18282 	default:
18283 		break;
18284 	}
18285 
18286 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
18287 
18288 	if (no_caller_buf == TRUE) {
18289 		kmem_free(data_bufp, data_len);
18290 	}
18291 
18292 	return (status);
18293 }
18294 
18295 
18296 /*
18297  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
18298  *
18299  * Description: This routine is the driver entry point for handling CD-ROM
18300  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
18301  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
18302  *		device.
18303  *
18304  *   Arguments: un  -   Pointer to soft state struct for the target.
18305  *		usr_cmd SCSI-3 reservation facility command (one of
18306  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
18307  *			SD_SCSI3_PREEMPTANDABORT)
18308  *		usr_bufp - user provided pointer register, reserve descriptor or
18309  *			preempt and abort structure (mhioc_register_t,
18310  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
18311  *
18312  * Return Code: 0   - Success
18313  *		EACCES
18314  *		ENOTSUP
18315  *		errno return code from sd_send_scsi_cmd()
18316  *
18317  *     Context: Can sleep. Does not return until command is completed.
18318  */
18319 
18320 static int
18321 sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un, uchar_t usr_cmd,
18322 	uchar_t	*usr_bufp)
18323 {
18324 	struct scsi_extended_sense	sense_buf;
18325 	union scsi_cdb		cdb;
18326 	struct uscsi_cmd	ucmd_buf;
18327 	int			status;
18328 	uchar_t			data_len = sizeof (sd_prout_t);
18329 	sd_prout_t		*prp;
18330 
18331 	ASSERT(un != NULL);
18332 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18333 	ASSERT(data_len == 24);	/* required by scsi spec */
18334 
18335 	SD_TRACE(SD_LOG_IO, un,
18336 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
18337 
18338 	if (usr_bufp == NULL) {
18339 		return (EINVAL);
18340 	}
18341 
18342 	bzero(&cdb, sizeof (cdb));
18343 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18344 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18345 	prp = kmem_zalloc(data_len, KM_SLEEP);
18346 
18347 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
18348 	cdb.cdb_opaque[1] = usr_cmd;
18349 	FORMG1COUNT(&cdb, data_len);
18350 
18351 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18352 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18353 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
18354 	ucmd_buf.uscsi_buflen	= data_len;
18355 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18356 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18357 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
18358 	ucmd_buf.uscsi_timeout	= 60;
18359 
18360 	switch (usr_cmd) {
18361 	case SD_SCSI3_REGISTER: {
18362 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
18363 
18364 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18365 		bcopy(ptr->newkey.key, prp->service_key,
18366 		    MHIOC_RESV_KEY_SIZE);
18367 		prp->aptpl = ptr->aptpl;
18368 		break;
18369 	}
18370 	case SD_SCSI3_RESERVE:
18371 	case SD_SCSI3_RELEASE: {
18372 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
18373 
18374 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18375 		prp->scope_address = BE_32(ptr->scope_specific_addr);
18376 		cdb.cdb_opaque[2] = ptr->type;
18377 		break;
18378 	}
18379 	case SD_SCSI3_PREEMPTANDABORT: {
18380 		mhioc_preemptandabort_t *ptr =
18381 		    (mhioc_preemptandabort_t *)usr_bufp;
18382 
18383 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18384 		bcopy(ptr->victim_key.key, prp->service_key,
18385 		    MHIOC_RESV_KEY_SIZE);
18386 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
18387 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
18388 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
18389 		break;
18390 	}
18391 	case SD_SCSI3_REGISTERANDIGNOREKEY:
18392 	{
18393 		mhioc_registerandignorekey_t *ptr;
18394 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
18395 		bcopy(ptr->newkey.key,
18396 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
18397 		prp->aptpl = ptr->aptpl;
18398 		break;
18399 	}
18400 	default:
18401 		ASSERT(FALSE);
18402 		break;
18403 	}
18404 
18405 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18406 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18407 
18408 	switch (status) {
18409 	case 0:
18410 		break;	/* Success! */
18411 	case EIO:
18412 		switch (ucmd_buf.uscsi_status) {
18413 		case STATUS_RESERVATION_CONFLICT:
18414 			status = EACCES;
18415 			break;
18416 		case STATUS_CHECK:
18417 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18418 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18419 			    KEY_ILLEGAL_REQUEST)) {
18420 				status = ENOTSUP;
18421 			}
18422 			break;
18423 		default:
18424 			break;
18425 		}
18426 		break;
18427 	default:
18428 		break;
18429 	}
18430 
18431 	kmem_free(prp, data_len);
18432 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
18433 	return (status);
18434 }
18435 
18436 
18437 /*
18438  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
18439  *
18440  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
18441  *
18442  *   Arguments: un - pointer to the target's soft state struct
18443  *
18444  * Return Code: 0 - success
18445  *		errno-type error code
18446  *
18447  *     Context: kernel thread context only.
18448  */
18449 
18450 static int
18451 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
18452 {
18453 	struct sd_uscsi_info	*uip;
18454 	struct uscsi_cmd	*uscmd;
18455 	union scsi_cdb		*cdb;
18456 	struct buf		*bp;
18457 	int			rval = 0;
18458 
18459 	SD_TRACE(SD_LOG_IO, un,
18460 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
18461 
18462 	ASSERT(un != NULL);
18463 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18464 
18465 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
18466 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
18467 
18468 	/*
18469 	 * First get some memory for the uscsi_cmd struct and cdb
18470 	 * and initialize for SYNCHRONIZE_CACHE cmd.
18471 	 */
18472 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
18473 	uscmd->uscsi_cdblen = CDB_GROUP1;
18474 	uscmd->uscsi_cdb = (caddr_t)cdb;
18475 	uscmd->uscsi_bufaddr = NULL;
18476 	uscmd->uscsi_buflen = 0;
18477 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
18478 	uscmd->uscsi_rqlen = SENSE_LENGTH;
18479 	uscmd->uscsi_rqresid = SENSE_LENGTH;
18480 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
18481 	uscmd->uscsi_timeout = sd_io_time;
18482 
18483 	/*
18484 	 * Allocate an sd_uscsi_info struct and fill it with the info
18485 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
18486 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
18487 	 * since we allocate the buf here in this function, we do not
18488 	 * need to preserve the prior contents of b_private.
18489 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
18490 	 */
18491 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
18492 	uip->ui_flags = SD_PATH_DIRECT;
18493 	uip->ui_cmdp  = uscmd;
18494 
18495 	bp = getrbuf(KM_SLEEP);
18496 	bp->b_private = uip;
18497 
18498 	/*
18499 	 * Setup buffer to carry uscsi request.
18500 	 */
18501 	bp->b_flags  = B_BUSY;
18502 	bp->b_bcount = 0;
18503 	bp->b_blkno  = 0;
18504 
18505 	if (dkc != NULL) {
18506 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
18507 		uip->ui_dkc = *dkc;
18508 	}
18509 
18510 	bp->b_edev = SD_GET_DEV(un);
18511 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
18512 
18513 	(void) sd_uscsi_strategy(bp);
18514 
18515 	/*
18516 	 * If synchronous request, wait for completion
18517 	 * If async just return and let b_iodone callback
18518 	 * cleanup.
18519 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
18520 	 * but it was also incremented in sd_uscsi_strategy(), so
18521 	 * we should be ok.
18522 	 */
18523 	if (dkc == NULL) {
18524 		(void) biowait(bp);
18525 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
18526 	}
18527 
18528 	return (rval);
18529 }
18530 
18531 
18532 static int
18533 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
18534 {
18535 	struct sd_uscsi_info *uip;
18536 	struct uscsi_cmd *uscmd;
18537 	uint8_t *sense_buf;
18538 	struct sd_lun *un;
18539 	int status;
18540 
18541 	uip = (struct sd_uscsi_info *)(bp->b_private);
18542 	ASSERT(uip != NULL);
18543 
18544 	uscmd = uip->ui_cmdp;
18545 	ASSERT(uscmd != NULL);
18546 
18547 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
18548 	ASSERT(sense_buf != NULL);
18549 
18550 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
18551 	ASSERT(un != NULL);
18552 
18553 	status = geterror(bp);
18554 	switch (status) {
18555 	case 0:
18556 		break;	/* Success! */
18557 	case EIO:
18558 		switch (uscmd->uscsi_status) {
18559 		case STATUS_RESERVATION_CONFLICT:
18560 			/* Ignore reservation conflict */
18561 			status = 0;
18562 			goto done;
18563 
18564 		case STATUS_CHECK:
18565 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
18566 			    (scsi_sense_key(sense_buf) ==
18567 			    KEY_ILLEGAL_REQUEST)) {
18568 				/* Ignore Illegal Request error */
18569 				mutex_enter(SD_MUTEX(un));
18570 				un->un_f_sync_cache_supported = FALSE;
18571 				mutex_exit(SD_MUTEX(un));
18572 				status = ENOTSUP;
18573 				goto done;
18574 			}
18575 			break;
18576 		default:
18577 			break;
18578 		}
18579 		/* FALLTHRU */
18580 	default:
18581 		/*
18582 		 * Don't log an error message if this device
18583 		 * has removable media.
18584 		 */
18585 		if (!un->un_f_has_removable_media) {
18586 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
18587 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
18588 		}
18589 		break;
18590 	}
18591 
18592 done:
18593 	if (uip->ui_dkc.dkc_callback != NULL) {
18594 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
18595 	}
18596 
18597 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
18598 	freerbuf(bp);
18599 	kmem_free(uip, sizeof (struct sd_uscsi_info));
18600 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
18601 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
18602 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
18603 
18604 	return (status);
18605 }
18606 
18607 
18608 /*
18609  *    Function: sd_send_scsi_GET_CONFIGURATION
18610  *
18611  * Description: Issues the get configuration command to the device.
18612  *		Called from sd_check_for_writable_cd & sd_get_media_info
18613  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
18614  *   Arguments: un
18615  *		ucmdbuf
18616  *		rqbuf
18617  *		rqbuflen
18618  *		bufaddr
18619  *		buflen
18620  *		path_flag
18621  *
18622  * Return Code: 0   - Success
18623  *		errno return code from sd_send_scsi_cmd()
18624  *
18625  *     Context: Can sleep. Does not return until command is completed.
18626  *
18627  */
18628 
18629 static int
18630 sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un, struct uscsi_cmd *ucmdbuf,
18631 	uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
18632 	int path_flag)
18633 {
18634 	char	cdb[CDB_GROUP1];
18635 	int	status;
18636 
18637 	ASSERT(un != NULL);
18638 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18639 	ASSERT(bufaddr != NULL);
18640 	ASSERT(ucmdbuf != NULL);
18641 	ASSERT(rqbuf != NULL);
18642 
18643 	SD_TRACE(SD_LOG_IO, un,
18644 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
18645 
18646 	bzero(cdb, sizeof (cdb));
18647 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
18648 	bzero(rqbuf, rqbuflen);
18649 	bzero(bufaddr, buflen);
18650 
18651 	/*
18652 	 * Set up cdb field for the get configuration command.
18653 	 */
18654 	cdb[0] = SCMD_GET_CONFIGURATION;
18655 	cdb[1] = 0x02;  /* Requested Type */
18656 	cdb[8] = SD_PROFILE_HEADER_LEN;
18657 	ucmdbuf->uscsi_cdb = cdb;
18658 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
18659 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
18660 	ucmdbuf->uscsi_buflen = buflen;
18661 	ucmdbuf->uscsi_timeout = sd_io_time;
18662 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
18663 	ucmdbuf->uscsi_rqlen = rqbuflen;
18664 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
18665 
18666 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, FKIOCTL,
18667 	    UIO_SYSSPACE, path_flag);
18668 
18669 	switch (status) {
18670 	case 0:
18671 		break;  /* Success! */
18672 	case EIO:
18673 		switch (ucmdbuf->uscsi_status) {
18674 		case STATUS_RESERVATION_CONFLICT:
18675 			status = EACCES;
18676 			break;
18677 		default:
18678 			break;
18679 		}
18680 		break;
18681 	default:
18682 		break;
18683 	}
18684 
18685 	if (status == 0) {
18686 		SD_DUMP_MEMORY(un, SD_LOG_IO,
18687 		    "sd_send_scsi_GET_CONFIGURATION: data",
18688 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
18689 	}
18690 
18691 	SD_TRACE(SD_LOG_IO, un,
18692 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
18693 
18694 	return (status);
18695 }
18696 
18697 /*
18698  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
18699  *
18700  * Description: Issues the get configuration command to the device to
18701  *              retrieve a specific feature. Called from
18702  *		sd_check_for_writable_cd & sd_set_mmc_caps.
18703  *   Arguments: un
18704  *              ucmdbuf
18705  *              rqbuf
18706  *              rqbuflen
18707  *              bufaddr
18708  *              buflen
18709  *		feature
18710  *
18711  * Return Code: 0   - Success
18712  *              errno return code from sd_send_scsi_cmd()
18713  *
18714  *     Context: Can sleep. Does not return until command is completed.
18715  *
18716  */
18717 static int
18718 sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
18719 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
18720 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag)
18721 {
18722 	char    cdb[CDB_GROUP1];
18723 	int	status;
18724 
18725 	ASSERT(un != NULL);
18726 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18727 	ASSERT(bufaddr != NULL);
18728 	ASSERT(ucmdbuf != NULL);
18729 	ASSERT(rqbuf != NULL);
18730 
18731 	SD_TRACE(SD_LOG_IO, un,
18732 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
18733 
18734 	bzero(cdb, sizeof (cdb));
18735 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
18736 	bzero(rqbuf, rqbuflen);
18737 	bzero(bufaddr, buflen);
18738 
18739 	/*
18740 	 * Set up cdb field for the get configuration command.
18741 	 */
18742 	cdb[0] = SCMD_GET_CONFIGURATION;
18743 	cdb[1] = 0x02;  /* Requested Type */
18744 	cdb[3] = feature;
18745 	cdb[8] = buflen;
18746 	ucmdbuf->uscsi_cdb = cdb;
18747 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
18748 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
18749 	ucmdbuf->uscsi_buflen = buflen;
18750 	ucmdbuf->uscsi_timeout = sd_io_time;
18751 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
18752 	ucmdbuf->uscsi_rqlen = rqbuflen;
18753 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
18754 
18755 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, FKIOCTL,
18756 	    UIO_SYSSPACE, path_flag);
18757 
18758 	switch (status) {
18759 	case 0:
18760 		break;  /* Success! */
18761 	case EIO:
18762 		switch (ucmdbuf->uscsi_status) {
18763 		case STATUS_RESERVATION_CONFLICT:
18764 			status = EACCES;
18765 			break;
18766 		default:
18767 			break;
18768 		}
18769 		break;
18770 	default:
18771 		break;
18772 	}
18773 
18774 	if (status == 0) {
18775 		SD_DUMP_MEMORY(un, SD_LOG_IO,
18776 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
18777 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
18778 	}
18779 
18780 	SD_TRACE(SD_LOG_IO, un,
18781 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
18782 
18783 	return (status);
18784 }
18785 
18786 
18787 /*
18788  *    Function: sd_send_scsi_MODE_SENSE
18789  *
18790  * Description: Utility function for issuing a scsi MODE SENSE command.
18791  *		Note: This routine uses a consistent implementation for Group0,
18792  *		Group1, and Group2 commands across all platforms. ATAPI devices
18793  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
18794  *
18795  *   Arguments: un - pointer to the softstate struct for the target.
18796  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
18797  *			  CDB_GROUP[1|2] (10 byte).
18798  *		bufaddr - buffer for page data retrieved from the target.
18799  *		buflen - size of page to be retrieved.
18800  *		page_code - page code of data to be retrieved from the target.
18801  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
18802  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
18803  *			to use the USCSI "direct" chain and bypass the normal
18804  *			command waitq.
18805  *
18806  * Return Code: 0   - Success
18807  *		errno return code from sd_send_scsi_cmd()
18808  *
18809  *     Context: Can sleep. Does not return until command is completed.
18810  */
18811 
18812 static int
18813 sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
18814 	size_t buflen,  uchar_t page_code, int path_flag)
18815 {
18816 	struct	scsi_extended_sense	sense_buf;
18817 	union scsi_cdb		cdb;
18818 	struct uscsi_cmd	ucmd_buf;
18819 	int			status;
18820 	int			headlen;
18821 
18822 	ASSERT(un != NULL);
18823 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18824 	ASSERT(bufaddr != NULL);
18825 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
18826 	    (cdbsize == CDB_GROUP2));
18827 
18828 	SD_TRACE(SD_LOG_IO, un,
18829 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
18830 
18831 	bzero(&cdb, sizeof (cdb));
18832 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18833 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18834 	bzero(bufaddr, buflen);
18835 
18836 	if (cdbsize == CDB_GROUP0) {
18837 		cdb.scc_cmd = SCMD_MODE_SENSE;
18838 		cdb.cdb_opaque[2] = page_code;
18839 		FORMG0COUNT(&cdb, buflen);
18840 		headlen = MODE_HEADER_LENGTH;
18841 	} else {
18842 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
18843 		cdb.cdb_opaque[2] = page_code;
18844 		FORMG1COUNT(&cdb, buflen);
18845 		headlen = MODE_HEADER_LENGTH_GRP2;
18846 	}
18847 
18848 	ASSERT(headlen <= buflen);
18849 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
18850 
18851 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18852 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
18853 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
18854 	ucmd_buf.uscsi_buflen	= buflen;
18855 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18856 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18857 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
18858 	ucmd_buf.uscsi_timeout	= 60;
18859 
18860 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18861 	    UIO_SYSSPACE, path_flag);
18862 
18863 	switch (status) {
18864 	case 0:
18865 		/*
18866 		 * sr_check_wp() uses 0x3f page code and check the header of
18867 		 * mode page to determine if target device is write-protected.
18868 		 * But some USB devices return 0 bytes for 0x3f page code. For
18869 		 * this case, make sure that mode page header is returned at
18870 		 * least.
18871 		 */
18872 		if (buflen - ucmd_buf.uscsi_resid <  headlen)
18873 			status = EIO;
18874 		break;	/* Success! */
18875 	case EIO:
18876 		switch (ucmd_buf.uscsi_status) {
18877 		case STATUS_RESERVATION_CONFLICT:
18878 			status = EACCES;
18879 			break;
18880 		default:
18881 			break;
18882 		}
18883 		break;
18884 	default:
18885 		break;
18886 	}
18887 
18888 	if (status == 0) {
18889 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
18890 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
18891 	}
18892 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
18893 
18894 	return (status);
18895 }
18896 
18897 
18898 /*
18899  *    Function: sd_send_scsi_MODE_SELECT
18900  *
18901  * Description: Utility function for issuing a scsi MODE SELECT command.
18902  *		Note: This routine uses a consistent implementation for Group0,
18903  *		Group1, and Group2 commands across all platforms. ATAPI devices
18904  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
18905  *
18906  *   Arguments: un - pointer to the softstate struct for the target.
18907  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
18908  *			  CDB_GROUP[1|2] (10 byte).
18909  *		bufaddr - buffer for page data retrieved from the target.
18910  *		buflen - size of page to be retrieved.
18911  *		save_page - boolean to determin if SP bit should be set.
18912  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
18913  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
18914  *			to use the USCSI "direct" chain and bypass the normal
18915  *			command waitq.
18916  *
18917  * Return Code: 0   - Success
18918  *		errno return code from sd_send_scsi_cmd()
18919  *
18920  *     Context: Can sleep. Does not return until command is completed.
18921  */
18922 
18923 static int
18924 sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
18925 	size_t buflen,  uchar_t save_page, int path_flag)
18926 {
18927 	struct	scsi_extended_sense	sense_buf;
18928 	union scsi_cdb		cdb;
18929 	struct uscsi_cmd	ucmd_buf;
18930 	int			status;
18931 
18932 	ASSERT(un != NULL);
18933 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18934 	ASSERT(bufaddr != NULL);
18935 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
18936 	    (cdbsize == CDB_GROUP2));
18937 
18938 	SD_TRACE(SD_LOG_IO, un,
18939 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
18940 
18941 	bzero(&cdb, sizeof (cdb));
18942 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18943 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18944 
18945 	/* Set the PF bit for many third party drives */
18946 	cdb.cdb_opaque[1] = 0x10;
18947 
18948 	/* Set the savepage(SP) bit if given */
18949 	if (save_page == SD_SAVE_PAGE) {
18950 		cdb.cdb_opaque[1] |= 0x01;
18951 	}
18952 
18953 	if (cdbsize == CDB_GROUP0) {
18954 		cdb.scc_cmd = SCMD_MODE_SELECT;
18955 		FORMG0COUNT(&cdb, buflen);
18956 	} else {
18957 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
18958 		FORMG1COUNT(&cdb, buflen);
18959 	}
18960 
18961 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
18962 
18963 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18964 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
18965 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
18966 	ucmd_buf.uscsi_buflen	= buflen;
18967 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18968 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18969 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
18970 	ucmd_buf.uscsi_timeout	= 60;
18971 
18972 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18973 	    UIO_SYSSPACE, path_flag);
18974 
18975 	switch (status) {
18976 	case 0:
18977 		break;	/* Success! */
18978 	case EIO:
18979 		switch (ucmd_buf.uscsi_status) {
18980 		case STATUS_RESERVATION_CONFLICT:
18981 			status = EACCES;
18982 			break;
18983 		default:
18984 			break;
18985 		}
18986 		break;
18987 	default:
18988 		break;
18989 	}
18990 
18991 	if (status == 0) {
18992 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
18993 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
18994 	}
18995 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
18996 
18997 	return (status);
18998 }
18999 
19000 
19001 /*
19002  *    Function: sd_send_scsi_RDWR
19003  *
19004  * Description: Issue a scsi READ or WRITE command with the given parameters.
19005  *
19006  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19007  *		cmd:	 SCMD_READ or SCMD_WRITE
19008  *		bufaddr: Address of caller's buffer to receive the RDWR data
19009  *		buflen:  Length of caller's buffer receive the RDWR data.
19010  *		start_block: Block number for the start of the RDWR operation.
19011  *			 (Assumes target-native block size.)
19012  *		residp:  Pointer to variable to receive the redisual of the
19013  *			 RDWR operation (may be NULL of no residual requested).
19014  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19015  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19016  *			to use the USCSI "direct" chain and bypass the normal
19017  *			command waitq.
19018  *
19019  * Return Code: 0   - Success
19020  *		errno return code from sd_send_scsi_cmd()
19021  *
19022  *     Context: Can sleep. Does not return until command is completed.
19023  */
19024 
19025 static int
19026 sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
19027 	size_t buflen, daddr_t start_block, int path_flag)
19028 {
19029 	struct	scsi_extended_sense	sense_buf;
19030 	union scsi_cdb		cdb;
19031 	struct uscsi_cmd	ucmd_buf;
19032 	uint32_t		block_count;
19033 	int			status;
19034 	int			cdbsize;
19035 	uchar_t			flag;
19036 
19037 	ASSERT(un != NULL);
19038 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19039 	ASSERT(bufaddr != NULL);
19040 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
19041 
19042 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
19043 
19044 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
19045 		return (EINVAL);
19046 	}
19047 
19048 	mutex_enter(SD_MUTEX(un));
19049 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
19050 	mutex_exit(SD_MUTEX(un));
19051 
19052 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
19053 
19054 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
19055 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
19056 	    bufaddr, buflen, start_block, block_count);
19057 
19058 	bzero(&cdb, sizeof (cdb));
19059 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19060 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19061 
19062 	/* Compute CDB size to use */
19063 	if (start_block > 0xffffffff)
19064 		cdbsize = CDB_GROUP4;
19065 	else if ((start_block & 0xFFE00000) ||
19066 	    (un->un_f_cfg_is_atapi == TRUE))
19067 		cdbsize = CDB_GROUP1;
19068 	else
19069 		cdbsize = CDB_GROUP0;
19070 
19071 	switch (cdbsize) {
19072 	case CDB_GROUP0:	/* 6-byte CDBs */
19073 		cdb.scc_cmd = cmd;
19074 		FORMG0ADDR(&cdb, start_block);
19075 		FORMG0COUNT(&cdb, block_count);
19076 		break;
19077 	case CDB_GROUP1:	/* 10-byte CDBs */
19078 		cdb.scc_cmd = cmd | SCMD_GROUP1;
19079 		FORMG1ADDR(&cdb, start_block);
19080 		FORMG1COUNT(&cdb, block_count);
19081 		break;
19082 	case CDB_GROUP4:	/* 16-byte CDBs */
19083 		cdb.scc_cmd = cmd | SCMD_GROUP4;
19084 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
19085 		FORMG4COUNT(&cdb, block_count);
19086 		break;
19087 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
19088 	default:
19089 		/* All others reserved */
19090 		return (EINVAL);
19091 	}
19092 
19093 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
19094 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19095 
19096 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19097 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19098 	ucmd_buf.uscsi_bufaddr	= bufaddr;
19099 	ucmd_buf.uscsi_buflen	= buflen;
19100 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19101 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19102 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
19103 	ucmd_buf.uscsi_timeout	= 60;
19104 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19105 	    UIO_SYSSPACE, path_flag);
19106 	switch (status) {
19107 	case 0:
19108 		break;	/* Success! */
19109 	case EIO:
19110 		switch (ucmd_buf.uscsi_status) {
19111 		case STATUS_RESERVATION_CONFLICT:
19112 			status = EACCES;
19113 			break;
19114 		default:
19115 			break;
19116 		}
19117 		break;
19118 	default:
19119 		break;
19120 	}
19121 
19122 	if (status == 0) {
19123 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
19124 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19125 	}
19126 
19127 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
19128 
19129 	return (status);
19130 }
19131 
19132 
19133 /*
19134  *    Function: sd_send_scsi_LOG_SENSE
19135  *
19136  * Description: Issue a scsi LOG_SENSE command with the given parameters.
19137  *
19138  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19139  *
19140  * Return Code: 0   - Success
19141  *		errno return code from sd_send_scsi_cmd()
19142  *
19143  *     Context: Can sleep. Does not return until command is completed.
19144  */
19145 
19146 static int
19147 sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr, uint16_t buflen,
19148 	uchar_t page_code, uchar_t page_control, uint16_t param_ptr,
19149 	int path_flag)
19150 
19151 {
19152 	struct	scsi_extended_sense	sense_buf;
19153 	union scsi_cdb		cdb;
19154 	struct uscsi_cmd	ucmd_buf;
19155 	int			status;
19156 
19157 	ASSERT(un != NULL);
19158 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19159 
19160 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
19161 
19162 	bzero(&cdb, sizeof (cdb));
19163 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19164 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19165 
19166 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
19167 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
19168 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
19169 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
19170 	FORMG1COUNT(&cdb, buflen);
19171 
19172 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19173 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19174 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19175 	ucmd_buf.uscsi_buflen	= buflen;
19176 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19177 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19178 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19179 	ucmd_buf.uscsi_timeout	= 60;
19180 
19181 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19182 	    UIO_SYSSPACE, path_flag);
19183 
19184 	switch (status) {
19185 	case 0:
19186 		break;
19187 	case EIO:
19188 		switch (ucmd_buf.uscsi_status) {
19189 		case STATUS_RESERVATION_CONFLICT:
19190 			status = EACCES;
19191 			break;
19192 		case STATUS_CHECK:
19193 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19194 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
19195 				KEY_ILLEGAL_REQUEST) &&
19196 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
19197 				/*
19198 				 * ASC 0x24: INVALID FIELD IN CDB
19199 				 */
19200 				switch (page_code) {
19201 				case START_STOP_CYCLE_PAGE:
19202 					/*
19203 					 * The start stop cycle counter is
19204 					 * implemented as page 0x31 in earlier
19205 					 * generation disks. In new generation
19206 					 * disks the start stop cycle counter is
19207 					 * implemented as page 0xE. To properly
19208 					 * handle this case if an attempt for
19209 					 * log page 0xE is made and fails we
19210 					 * will try again using page 0x31.
19211 					 *
19212 					 * Network storage BU committed to
19213 					 * maintain the page 0x31 for this
19214 					 * purpose and will not have any other
19215 					 * page implemented with page code 0x31
19216 					 * until all disks transition to the
19217 					 * standard page.
19218 					 */
19219 					mutex_enter(SD_MUTEX(un));
19220 					un->un_start_stop_cycle_page =
19221 					    START_STOP_CYCLE_VU_PAGE;
19222 					cdb.cdb_opaque[2] =
19223 					    (char)(page_control << 6) |
19224 					    un->un_start_stop_cycle_page;
19225 					mutex_exit(SD_MUTEX(un));
19226 					status = sd_send_scsi_cmd(
19227 					    SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19228 					    UIO_SYSSPACE, path_flag);
19229 
19230 					break;
19231 				case TEMPERATURE_PAGE:
19232 					status = ENOTTY;
19233 					break;
19234 				default:
19235 					break;
19236 				}
19237 			}
19238 			break;
19239 		default:
19240 			break;
19241 		}
19242 		break;
19243 	default:
19244 		break;
19245 	}
19246 
19247 	if (status == 0) {
19248 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
19249 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19250 	}
19251 
19252 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
19253 
19254 	return (status);
19255 }
19256 
19257 
19258 /*
19259  *    Function: sdioctl
19260  *
19261  * Description: Driver's ioctl(9e) entry point function.
19262  *
19263  *   Arguments: dev     - device number
19264  *		cmd     - ioctl operation to be performed
19265  *		arg     - user argument, contains data to be set or reference
19266  *			  parameter for get
19267  *		flag    - bit flag, indicating open settings, 32/64 bit type
19268  *		cred_p  - user credential pointer
19269  *		rval_p  - calling process return value (OPT)
19270  *
19271  * Return Code: EINVAL
19272  *		ENOTTY
19273  *		ENXIO
19274  *		EIO
19275  *		EFAULT
19276  *		ENOTSUP
19277  *		EPERM
19278  *
19279  *     Context: Called from the device switch at normal priority.
19280  */
19281 
19282 static int
19283 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
19284 {
19285 	struct sd_lun	*un = NULL;
19286 	int		err = 0;
19287 	int		i = 0;
19288 	cred_t		*cr;
19289 	int		tmprval = EINVAL;
19290 	int 		is_valid;
19291 
19292 	/*
19293 	 * All device accesses go thru sdstrategy where we check on suspend
19294 	 * status
19295 	 */
19296 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
19297 		return (ENXIO);
19298 	}
19299 
19300 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19301 
19302 
19303 	is_valid = SD_IS_VALID_LABEL(un);
19304 
19305 	/*
19306 	 * Moved this wait from sd_uscsi_strategy to here for
19307 	 * reasons of deadlock prevention. Internal driver commands,
19308 	 * specifically those to change a devices power level, result
19309 	 * in a call to sd_uscsi_strategy.
19310 	 */
19311 	mutex_enter(SD_MUTEX(un));
19312 	while ((un->un_state == SD_STATE_SUSPENDED) ||
19313 	    (un->un_state == SD_STATE_PM_CHANGING)) {
19314 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
19315 	}
19316 	/*
19317 	 * Twiddling the counter here protects commands from now
19318 	 * through to the top of sd_uscsi_strategy. Without the
19319 	 * counter inc. a power down, for example, could get in
19320 	 * after the above check for state is made and before
19321 	 * execution gets to the top of sd_uscsi_strategy.
19322 	 * That would cause problems.
19323 	 */
19324 	un->un_ncmds_in_driver++;
19325 
19326 	if (!is_valid &&
19327 	    (flag & (FNDELAY | FNONBLOCK))) {
19328 		switch (cmd) {
19329 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
19330 		case DKIOCGVTOC:
19331 		case DKIOCGAPART:
19332 		case DKIOCPARTINFO:
19333 		case DKIOCSGEOM:
19334 		case DKIOCSAPART:
19335 		case DKIOCGETEFI:
19336 		case DKIOCPARTITION:
19337 		case DKIOCSVTOC:
19338 		case DKIOCSETEFI:
19339 		case DKIOCGMBOOT:
19340 		case DKIOCSMBOOT:
19341 		case DKIOCG_PHYGEOM:
19342 		case DKIOCG_VIRTGEOM:
19343 			/* let cmlb handle it */
19344 			goto skip_ready_valid;
19345 
19346 		case CDROMPAUSE:
19347 		case CDROMRESUME:
19348 		case CDROMPLAYMSF:
19349 		case CDROMPLAYTRKIND:
19350 		case CDROMREADTOCHDR:
19351 		case CDROMREADTOCENTRY:
19352 		case CDROMSTOP:
19353 		case CDROMSTART:
19354 		case CDROMVOLCTRL:
19355 		case CDROMSUBCHNL:
19356 		case CDROMREADMODE2:
19357 		case CDROMREADMODE1:
19358 		case CDROMREADOFFSET:
19359 		case CDROMSBLKMODE:
19360 		case CDROMGBLKMODE:
19361 		case CDROMGDRVSPEED:
19362 		case CDROMSDRVSPEED:
19363 		case CDROMCDDA:
19364 		case CDROMCDXA:
19365 		case CDROMSUBCODE:
19366 			if (!ISCD(un)) {
19367 				un->un_ncmds_in_driver--;
19368 				ASSERT(un->un_ncmds_in_driver >= 0);
19369 				mutex_exit(SD_MUTEX(un));
19370 				return (ENOTTY);
19371 			}
19372 			break;
19373 		case FDEJECT:
19374 		case DKIOCEJECT:
19375 		case CDROMEJECT:
19376 			if (!un->un_f_eject_media_supported) {
19377 				un->un_ncmds_in_driver--;
19378 				ASSERT(un->un_ncmds_in_driver >= 0);
19379 				mutex_exit(SD_MUTEX(un));
19380 				return (ENOTTY);
19381 			}
19382 			break;
19383 		case DKIOCFLUSHWRITECACHE:
19384 			mutex_exit(SD_MUTEX(un));
19385 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
19386 			if (err != 0) {
19387 				mutex_enter(SD_MUTEX(un));
19388 				un->un_ncmds_in_driver--;
19389 				ASSERT(un->un_ncmds_in_driver >= 0);
19390 				mutex_exit(SD_MUTEX(un));
19391 				return (EIO);
19392 			}
19393 			mutex_enter(SD_MUTEX(un));
19394 			/* FALLTHROUGH */
19395 		case DKIOCREMOVABLE:
19396 		case DKIOCHOTPLUGGABLE:
19397 		case DKIOCINFO:
19398 		case DKIOCGMEDIAINFO:
19399 		case MHIOCENFAILFAST:
19400 		case MHIOCSTATUS:
19401 		case MHIOCTKOWN:
19402 		case MHIOCRELEASE:
19403 		case MHIOCGRP_INKEYS:
19404 		case MHIOCGRP_INRESV:
19405 		case MHIOCGRP_REGISTER:
19406 		case MHIOCGRP_RESERVE:
19407 		case MHIOCGRP_PREEMPTANDABORT:
19408 		case MHIOCGRP_REGISTERANDIGNOREKEY:
19409 		case CDROMCLOSETRAY:
19410 		case USCSICMD:
19411 			goto skip_ready_valid;
19412 		default:
19413 			break;
19414 		}
19415 
19416 		mutex_exit(SD_MUTEX(un));
19417 		err = sd_ready_and_valid(un);
19418 		mutex_enter(SD_MUTEX(un));
19419 
19420 		if (err != SD_READY_VALID) {
19421 			switch (cmd) {
19422 			case DKIOCSTATE:
19423 			case CDROMGDRVSPEED:
19424 			case CDROMSDRVSPEED:
19425 			case FDEJECT:	/* for eject command */
19426 			case DKIOCEJECT:
19427 			case CDROMEJECT:
19428 			case DKIOCREMOVABLE:
19429 			case DKIOCHOTPLUGGABLE:
19430 				break;
19431 			default:
19432 				if (un->un_f_has_removable_media) {
19433 					err = ENXIO;
19434 				} else {
19435 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
19436 					if (err == SD_RESERVED_BY_OTHERS) {
19437 						err = EACCES;
19438 					} else {
19439 						err = EIO;
19440 					}
19441 				}
19442 				un->un_ncmds_in_driver--;
19443 				ASSERT(un->un_ncmds_in_driver >= 0);
19444 				mutex_exit(SD_MUTEX(un));
19445 				return (err);
19446 			}
19447 		}
19448 	}
19449 
19450 skip_ready_valid:
19451 	mutex_exit(SD_MUTEX(un));
19452 
19453 	switch (cmd) {
19454 	case DKIOCINFO:
19455 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
19456 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
19457 		break;
19458 
19459 	case DKIOCGMEDIAINFO:
19460 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
19461 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
19462 		break;
19463 
19464 	case DKIOCGGEOM:
19465 	case DKIOCGVTOC:
19466 	case DKIOCGAPART:
19467 	case DKIOCPARTINFO:
19468 	case DKIOCSGEOM:
19469 	case DKIOCSAPART:
19470 	case DKIOCGETEFI:
19471 	case DKIOCPARTITION:
19472 	case DKIOCSVTOC:
19473 	case DKIOCSETEFI:
19474 	case DKIOCGMBOOT:
19475 	case DKIOCSMBOOT:
19476 	case DKIOCG_PHYGEOM:
19477 	case DKIOCG_VIRTGEOM:
19478 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
19479 
19480 		/* TUR should spin up */
19481 
19482 		if (un->un_f_has_removable_media)
19483 			err = sd_send_scsi_TEST_UNIT_READY(un,
19484 			    SD_CHECK_FOR_MEDIA);
19485 		else
19486 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
19487 
19488 		if (err != 0)
19489 			break;
19490 
19491 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
19492 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
19493 
19494 		if ((err == 0) &&
19495 		    ((cmd == DKIOCSETEFI) ||
19496 		    (un->un_f_pkstats_enabled) &&
19497 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC))) {
19498 
19499 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
19500 			    (void *)SD_PATH_DIRECT);
19501 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
19502 				sd_set_pstats(un);
19503 				SD_TRACE(SD_LOG_IO_PARTITION, un,
19504 				    "sd_ioctl: un:0x%p pstats created and "
19505 				    "set\n", un);
19506 			}
19507 		}
19508 
19509 		if ((cmd == DKIOCSVTOC) ||
19510 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
19511 
19512 			mutex_enter(SD_MUTEX(un));
19513 			if (un->un_f_devid_supported &&
19514 			    (un->un_f_opt_fab_devid == TRUE)) {
19515 				if (un->un_devid == NULL) {
19516 					sd_register_devid(un, SD_DEVINFO(un),
19517 					    SD_TARGET_IS_UNRESERVED);
19518 				} else {
19519 					/*
19520 					 * The device id for this disk
19521 					 * has been fabricated. The
19522 					 * device id must be preserved
19523 					 * by writing it back out to
19524 					 * disk.
19525 					 */
19526 					if (sd_write_deviceid(un) != 0) {
19527 						ddi_devid_free(un->un_devid);
19528 						un->un_devid = NULL;
19529 					}
19530 				}
19531 			}
19532 			mutex_exit(SD_MUTEX(un));
19533 		}
19534 
19535 		break;
19536 
19537 	case DKIOCLOCK:
19538 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
19539 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
19540 		    SD_PATH_STANDARD);
19541 		break;
19542 
19543 	case DKIOCUNLOCK:
19544 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
19545 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
19546 		    SD_PATH_STANDARD);
19547 		break;
19548 
19549 	case DKIOCSTATE: {
19550 		enum dkio_state		state;
19551 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
19552 
19553 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
19554 			err = EFAULT;
19555 		} else {
19556 			err = sd_check_media(dev, state);
19557 			if (err == 0) {
19558 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
19559 				    sizeof (int), flag) != 0)
19560 					err = EFAULT;
19561 			}
19562 		}
19563 		break;
19564 	}
19565 
19566 	case DKIOCREMOVABLE:
19567 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
19568 		i = un->un_f_has_removable_media ? 1 : 0;
19569 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
19570 			err = EFAULT;
19571 		} else {
19572 			err = 0;
19573 		}
19574 		break;
19575 
19576 	case DKIOCHOTPLUGGABLE:
19577 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
19578 		i = un->un_f_is_hotpluggable ? 1 : 0;
19579 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
19580 			err = EFAULT;
19581 		} else {
19582 			err = 0;
19583 		}
19584 		break;
19585 
19586 	case DKIOCGTEMPERATURE:
19587 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
19588 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
19589 		break;
19590 
19591 	case MHIOCENFAILFAST:
19592 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
19593 		if ((err = drv_priv(cred_p)) == 0) {
19594 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
19595 		}
19596 		break;
19597 
19598 	case MHIOCTKOWN:
19599 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
19600 		if ((err = drv_priv(cred_p)) == 0) {
19601 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
19602 		}
19603 		break;
19604 
19605 	case MHIOCRELEASE:
19606 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
19607 		if ((err = drv_priv(cred_p)) == 0) {
19608 			err = sd_mhdioc_release(dev);
19609 		}
19610 		break;
19611 
19612 	case MHIOCSTATUS:
19613 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
19614 		if ((err = drv_priv(cred_p)) == 0) {
19615 			switch (sd_send_scsi_TEST_UNIT_READY(un, 0)) {
19616 			case 0:
19617 				err = 0;
19618 				break;
19619 			case EACCES:
19620 				*rval_p = 1;
19621 				err = 0;
19622 				break;
19623 			default:
19624 				err = EIO;
19625 				break;
19626 			}
19627 		}
19628 		break;
19629 
19630 	case MHIOCQRESERVE:
19631 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
19632 		if ((err = drv_priv(cred_p)) == 0) {
19633 			err = sd_reserve_release(dev, SD_RESERVE);
19634 		}
19635 		break;
19636 
19637 	case MHIOCREREGISTERDEVID:
19638 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
19639 		if (drv_priv(cred_p) == EPERM) {
19640 			err = EPERM;
19641 		} else if (!un->un_f_devid_supported) {
19642 			err = ENOTTY;
19643 		} else {
19644 			err = sd_mhdioc_register_devid(dev);
19645 		}
19646 		break;
19647 
19648 	case MHIOCGRP_INKEYS:
19649 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
19650 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
19651 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19652 				err = ENOTSUP;
19653 			} else {
19654 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
19655 				    flag);
19656 			}
19657 		}
19658 		break;
19659 
19660 	case MHIOCGRP_INRESV:
19661 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
19662 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
19663 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19664 				err = ENOTSUP;
19665 			} else {
19666 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
19667 			}
19668 		}
19669 		break;
19670 
19671 	case MHIOCGRP_REGISTER:
19672 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
19673 		if ((err = drv_priv(cred_p)) != EPERM) {
19674 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19675 				err = ENOTSUP;
19676 			} else if (arg != NULL) {
19677 				mhioc_register_t reg;
19678 				if (ddi_copyin((void *)arg, &reg,
19679 				    sizeof (mhioc_register_t), flag) != 0) {
19680 					err = EFAULT;
19681 				} else {
19682 					err =
19683 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
19684 					    un, SD_SCSI3_REGISTER,
19685 					    (uchar_t *)&reg);
19686 				}
19687 			}
19688 		}
19689 		break;
19690 
19691 	case MHIOCGRP_RESERVE:
19692 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
19693 		if ((err = drv_priv(cred_p)) != EPERM) {
19694 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19695 				err = ENOTSUP;
19696 			} else if (arg != NULL) {
19697 				mhioc_resv_desc_t resv_desc;
19698 				if (ddi_copyin((void *)arg, &resv_desc,
19699 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
19700 					err = EFAULT;
19701 				} else {
19702 					err =
19703 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
19704 					    un, SD_SCSI3_RESERVE,
19705 					    (uchar_t *)&resv_desc);
19706 				}
19707 			}
19708 		}
19709 		break;
19710 
19711 	case MHIOCGRP_PREEMPTANDABORT:
19712 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
19713 		if ((err = drv_priv(cred_p)) != EPERM) {
19714 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19715 				err = ENOTSUP;
19716 			} else if (arg != NULL) {
19717 				mhioc_preemptandabort_t preempt_abort;
19718 				if (ddi_copyin((void *)arg, &preempt_abort,
19719 				    sizeof (mhioc_preemptandabort_t),
19720 				    flag) != 0) {
19721 					err = EFAULT;
19722 				} else {
19723 					err =
19724 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
19725 					    un, SD_SCSI3_PREEMPTANDABORT,
19726 					    (uchar_t *)&preempt_abort);
19727 				}
19728 			}
19729 		}
19730 		break;
19731 
19732 	case MHIOCGRP_REGISTERANDIGNOREKEY:
19733 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
19734 		if ((err = drv_priv(cred_p)) != EPERM) {
19735 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
19736 				err = ENOTSUP;
19737 			} else if (arg != NULL) {
19738 				mhioc_registerandignorekey_t r_and_i;
19739 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
19740 				    sizeof (mhioc_registerandignorekey_t),
19741 				    flag) != 0) {
19742 					err = EFAULT;
19743 				} else {
19744 					err =
19745 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
19746 					    un, SD_SCSI3_REGISTERANDIGNOREKEY,
19747 					    (uchar_t *)&r_and_i);
19748 				}
19749 			}
19750 		}
19751 		break;
19752 
19753 	case USCSICMD:
19754 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
19755 		cr = ddi_get_cred();
19756 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
19757 			err = EPERM;
19758 		} else {
19759 			enum uio_seg	uioseg;
19760 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
19761 			    UIO_USERSPACE;
19762 			if (un->un_f_format_in_progress == TRUE) {
19763 				err = EAGAIN;
19764 				break;
19765 			}
19766 			err = sd_send_scsi_cmd(dev, (struct uscsi_cmd *)arg,
19767 			    flag, uioseg, SD_PATH_STANDARD);
19768 		}
19769 		break;
19770 
19771 	case CDROMPAUSE:
19772 	case CDROMRESUME:
19773 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
19774 		if (!ISCD(un)) {
19775 			err = ENOTTY;
19776 		} else {
19777 			err = sr_pause_resume(dev, cmd);
19778 		}
19779 		break;
19780 
19781 	case CDROMPLAYMSF:
19782 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
19783 		if (!ISCD(un)) {
19784 			err = ENOTTY;
19785 		} else {
19786 			err = sr_play_msf(dev, (caddr_t)arg, flag);
19787 		}
19788 		break;
19789 
19790 	case CDROMPLAYTRKIND:
19791 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
19792 #if defined(__i386) || defined(__amd64)
19793 		/*
19794 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
19795 		 */
19796 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
19797 #else
19798 		if (!ISCD(un)) {
19799 #endif
19800 			err = ENOTTY;
19801 		} else {
19802 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
19803 		}
19804 		break;
19805 
19806 	case CDROMREADTOCHDR:
19807 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
19808 		if (!ISCD(un)) {
19809 			err = ENOTTY;
19810 		} else {
19811 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
19812 		}
19813 		break;
19814 
19815 	case CDROMREADTOCENTRY:
19816 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
19817 		if (!ISCD(un)) {
19818 			err = ENOTTY;
19819 		} else {
19820 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
19821 		}
19822 		break;
19823 
19824 	case CDROMSTOP:
19825 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
19826 		if (!ISCD(un)) {
19827 			err = ENOTTY;
19828 		} else {
19829 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_STOP,
19830 			    SD_PATH_STANDARD);
19831 		}
19832 		break;
19833 
19834 	case CDROMSTART:
19835 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
19836 		if (!ISCD(un)) {
19837 			err = ENOTTY;
19838 		} else {
19839 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
19840 			    SD_PATH_STANDARD);
19841 		}
19842 		break;
19843 
19844 	case CDROMCLOSETRAY:
19845 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
19846 		if (!ISCD(un)) {
19847 			err = ENOTTY;
19848 		} else {
19849 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_CLOSE,
19850 			    SD_PATH_STANDARD);
19851 		}
19852 		break;
19853 
19854 	case FDEJECT:	/* for eject command */
19855 	case DKIOCEJECT:
19856 	case CDROMEJECT:
19857 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
19858 		if (!un->un_f_eject_media_supported) {
19859 			err = ENOTTY;
19860 		} else {
19861 			err = sr_eject(dev);
19862 		}
19863 		break;
19864 
19865 	case CDROMVOLCTRL:
19866 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
19867 		if (!ISCD(un)) {
19868 			err = ENOTTY;
19869 		} else {
19870 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
19871 		}
19872 		break;
19873 
19874 	case CDROMSUBCHNL:
19875 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
19876 		if (!ISCD(un)) {
19877 			err = ENOTTY;
19878 		} else {
19879 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
19880 		}
19881 		break;
19882 
19883 	case CDROMREADMODE2:
19884 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
19885 		if (!ISCD(un)) {
19886 			err = ENOTTY;
19887 		} else if (un->un_f_cfg_is_atapi == TRUE) {
19888 			/*
19889 			 * If the drive supports READ CD, use that instead of
19890 			 * switching the LBA size via a MODE SELECT
19891 			 * Block Descriptor
19892 			 */
19893 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
19894 		} else {
19895 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
19896 		}
19897 		break;
19898 
19899 	case CDROMREADMODE1:
19900 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
19901 		if (!ISCD(un)) {
19902 			err = ENOTTY;
19903 		} else {
19904 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
19905 		}
19906 		break;
19907 
19908 	case CDROMREADOFFSET:
19909 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
19910 		if (!ISCD(un)) {
19911 			err = ENOTTY;
19912 		} else {
19913 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
19914 			    flag);
19915 		}
19916 		break;
19917 
19918 	case CDROMSBLKMODE:
19919 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
19920 		/*
19921 		 * There is no means of changing block size in case of atapi
19922 		 * drives, thus return ENOTTY if drive type is atapi
19923 		 */
19924 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
19925 			err = ENOTTY;
19926 		} else if (un->un_f_mmc_cap == TRUE) {
19927 
19928 			/*
19929 			 * MMC Devices do not support changing the
19930 			 * logical block size
19931 			 *
19932 			 * Note: EINVAL is being returned instead of ENOTTY to
19933 			 * maintain consistancy with the original mmc
19934 			 * driver update.
19935 			 */
19936 			err = EINVAL;
19937 		} else {
19938 			mutex_enter(SD_MUTEX(un));
19939 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
19940 			    (un->un_ncmds_in_transport > 0)) {
19941 				mutex_exit(SD_MUTEX(un));
19942 				err = EINVAL;
19943 			} else {
19944 				mutex_exit(SD_MUTEX(un));
19945 				err = sr_change_blkmode(dev, cmd, arg, flag);
19946 			}
19947 		}
19948 		break;
19949 
19950 	case CDROMGBLKMODE:
19951 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
19952 		if (!ISCD(un)) {
19953 			err = ENOTTY;
19954 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
19955 		    (un->un_f_blockcount_is_valid != FALSE)) {
19956 			/*
19957 			 * Drive is an ATAPI drive so return target block
19958 			 * size for ATAPI drives since we cannot change the
19959 			 * blocksize on ATAPI drives. Used primarily to detect
19960 			 * if an ATAPI cdrom is present.
19961 			 */
19962 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
19963 			    sizeof (int), flag) != 0) {
19964 				err = EFAULT;
19965 			} else {
19966 				err = 0;
19967 			}
19968 
19969 		} else {
19970 			/*
19971 			 * Drive supports changing block sizes via a Mode
19972 			 * Select.
19973 			 */
19974 			err = sr_change_blkmode(dev, cmd, arg, flag);
19975 		}
19976 		break;
19977 
19978 	case CDROMGDRVSPEED:
19979 	case CDROMSDRVSPEED:
19980 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
19981 		if (!ISCD(un)) {
19982 			err = ENOTTY;
19983 		} else if (un->un_f_mmc_cap == TRUE) {
19984 			/*
19985 			 * Note: In the future the driver implementation
19986 			 * for getting and
19987 			 * setting cd speed should entail:
19988 			 * 1) If non-mmc try the Toshiba mode page
19989 			 *    (sr_change_speed)
19990 			 * 2) If mmc but no support for Real Time Streaming try
19991 			 *    the SET CD SPEED (0xBB) command
19992 			 *   (sr_atapi_change_speed)
19993 			 * 3) If mmc and support for Real Time Streaming
19994 			 *    try the GET PERFORMANCE and SET STREAMING
19995 			 *    commands (not yet implemented, 4380808)
19996 			 */
19997 			/*
19998 			 * As per recent MMC spec, CD-ROM speed is variable
19999 			 * and changes with LBA. Since there is no such
20000 			 * things as drive speed now, fail this ioctl.
20001 			 *
20002 			 * Note: EINVAL is returned for consistancy of original
20003 			 * implementation which included support for getting
20004 			 * the drive speed of mmc devices but not setting
20005 			 * the drive speed. Thus EINVAL would be returned
20006 			 * if a set request was made for an mmc device.
20007 			 * We no longer support get or set speed for
20008 			 * mmc but need to remain consistent with regard
20009 			 * to the error code returned.
20010 			 */
20011 			err = EINVAL;
20012 		} else if (un->un_f_cfg_is_atapi == TRUE) {
20013 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
20014 		} else {
20015 			err = sr_change_speed(dev, cmd, arg, flag);
20016 		}
20017 		break;
20018 
20019 	case CDROMCDDA:
20020 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
20021 		if (!ISCD(un)) {
20022 			err = ENOTTY;
20023 		} else {
20024 			err = sr_read_cdda(dev, (void *)arg, flag);
20025 		}
20026 		break;
20027 
20028 	case CDROMCDXA:
20029 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
20030 		if (!ISCD(un)) {
20031 			err = ENOTTY;
20032 		} else {
20033 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
20034 		}
20035 		break;
20036 
20037 	case CDROMSUBCODE:
20038 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
20039 		if (!ISCD(un)) {
20040 			err = ENOTTY;
20041 		} else {
20042 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
20043 		}
20044 		break;
20045 
20046 
20047 #ifdef SDDEBUG
20048 /* RESET/ABORTS testing ioctls */
20049 	case DKIOCRESET: {
20050 		int	reset_level;
20051 
20052 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
20053 			err = EFAULT;
20054 		} else {
20055 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
20056 			    "reset_level = 0x%lx\n", reset_level);
20057 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
20058 				err = 0;
20059 			} else {
20060 				err = EIO;
20061 			}
20062 		}
20063 		break;
20064 	}
20065 
20066 	case DKIOCABORT:
20067 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
20068 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
20069 			err = 0;
20070 		} else {
20071 			err = EIO;
20072 		}
20073 		break;
20074 #endif
20075 
20076 #ifdef SD_FAULT_INJECTION
20077 /* SDIOC FaultInjection testing ioctls */
20078 	case SDIOCSTART:
20079 	case SDIOCSTOP:
20080 	case SDIOCINSERTPKT:
20081 	case SDIOCINSERTXB:
20082 	case SDIOCINSERTUN:
20083 	case SDIOCINSERTARQ:
20084 	case SDIOCPUSH:
20085 	case SDIOCRETRIEVE:
20086 	case SDIOCRUN:
20087 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
20088 		    "SDIOC detected cmd:0x%X:\n", cmd);
20089 		/* call error generator */
20090 		sd_faultinjection_ioctl(cmd, arg, un);
20091 		err = 0;
20092 		break;
20093 
20094 #endif /* SD_FAULT_INJECTION */
20095 
20096 	case DKIOCFLUSHWRITECACHE:
20097 		{
20098 			struct dk_callback *dkc = (struct dk_callback *)arg;
20099 
20100 			mutex_enter(SD_MUTEX(un));
20101 			if (!un->un_f_sync_cache_supported ||
20102 			    !un->un_f_write_cache_enabled) {
20103 				err = un->un_f_sync_cache_supported ?
20104 				    0 : ENOTSUP;
20105 				mutex_exit(SD_MUTEX(un));
20106 				if ((flag & FKIOCTL) && dkc != NULL &&
20107 				    dkc->dkc_callback != NULL) {
20108 					(*dkc->dkc_callback)(dkc->dkc_cookie,
20109 					    err);
20110 					/*
20111 					 * Did callback and reported error.
20112 					 * Since we did a callback, ioctl
20113 					 * should return 0.
20114 					 */
20115 					err = 0;
20116 				}
20117 				break;
20118 			}
20119 			mutex_exit(SD_MUTEX(un));
20120 
20121 			if ((flag & FKIOCTL) && dkc != NULL &&
20122 			    dkc->dkc_callback != NULL) {
20123 				/* async SYNC CACHE request */
20124 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
20125 			} else {
20126 				/* synchronous SYNC CACHE request */
20127 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
20128 			}
20129 		}
20130 		break;
20131 
20132 	case DKIOCGETWCE: {
20133 
20134 		int wce;
20135 
20136 		if ((err = sd_get_write_cache_enabled(un, &wce)) != 0) {
20137 			break;
20138 		}
20139 
20140 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
20141 			err = EFAULT;
20142 		}
20143 		break;
20144 	}
20145 
20146 	case DKIOCSETWCE: {
20147 
20148 		int wce, sync_supported;
20149 
20150 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
20151 			err = EFAULT;
20152 			break;
20153 		}
20154 
20155 		/*
20156 		 * Synchronize multiple threads trying to enable
20157 		 * or disable the cache via the un_f_wcc_cv
20158 		 * condition variable.
20159 		 */
20160 		mutex_enter(SD_MUTEX(un));
20161 
20162 		/*
20163 		 * Don't allow the cache to be enabled if the
20164 		 * config file has it disabled.
20165 		 */
20166 		if (un->un_f_opt_disable_cache && wce) {
20167 			mutex_exit(SD_MUTEX(un));
20168 			err = EINVAL;
20169 			break;
20170 		}
20171 
20172 		/*
20173 		 * Wait for write cache change in progress
20174 		 * bit to be clear before proceeding.
20175 		 */
20176 		while (un->un_f_wcc_inprog)
20177 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
20178 
20179 		un->un_f_wcc_inprog = 1;
20180 
20181 		if (un->un_f_write_cache_enabled && wce == 0) {
20182 			/*
20183 			 * Disable the write cache.  Don't clear
20184 			 * un_f_write_cache_enabled until after
20185 			 * the mode select and flush are complete.
20186 			 */
20187 			sync_supported = un->un_f_sync_cache_supported;
20188 			mutex_exit(SD_MUTEX(un));
20189 			if ((err = sd_cache_control(un, SD_CACHE_NOCHANGE,
20190 			    SD_CACHE_DISABLE)) == 0 && sync_supported) {
20191 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
20192 			}
20193 
20194 			mutex_enter(SD_MUTEX(un));
20195 			if (err == 0) {
20196 				un->un_f_write_cache_enabled = 0;
20197 			}
20198 
20199 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
20200 			/*
20201 			 * Set un_f_write_cache_enabled first, so there is
20202 			 * no window where the cache is enabled, but the
20203 			 * bit says it isn't.
20204 			 */
20205 			un->un_f_write_cache_enabled = 1;
20206 			mutex_exit(SD_MUTEX(un));
20207 
20208 			err = sd_cache_control(un, SD_CACHE_NOCHANGE,
20209 			    SD_CACHE_ENABLE);
20210 
20211 			mutex_enter(SD_MUTEX(un));
20212 
20213 			if (err) {
20214 				un->un_f_write_cache_enabled = 0;
20215 			}
20216 		}
20217 
20218 		un->un_f_wcc_inprog = 0;
20219 		cv_broadcast(&un->un_wcc_cv);
20220 		mutex_exit(SD_MUTEX(un));
20221 		break;
20222 	}
20223 
20224 	default:
20225 		err = ENOTTY;
20226 		break;
20227 	}
20228 	mutex_enter(SD_MUTEX(un));
20229 	un->un_ncmds_in_driver--;
20230 	ASSERT(un->un_ncmds_in_driver >= 0);
20231 	mutex_exit(SD_MUTEX(un));
20232 
20233 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
20234 	return (err);
20235 }
20236 
20237 
20238 /*
20239  *    Function: sd_dkio_ctrl_info
20240  *
20241  * Description: This routine is the driver entry point for handling controller
20242  *		information ioctl requests (DKIOCINFO).
20243  *
20244  *   Arguments: dev  - the device number
20245  *		arg  - pointer to user provided dk_cinfo structure
20246  *		       specifying the controller type and attributes.
20247  *		flag - this argument is a pass through to ddi_copyxxx()
20248  *		       directly from the mode argument of ioctl().
20249  *
20250  * Return Code: 0
20251  *		EFAULT
20252  *		ENXIO
20253  */
20254 
20255 static int
20256 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
20257 {
20258 	struct sd_lun	*un = NULL;
20259 	struct dk_cinfo	*info;
20260 	dev_info_t	*pdip;
20261 	int		lun, tgt;
20262 
20263 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20264 		return (ENXIO);
20265 	}
20266 
20267 	info = (struct dk_cinfo *)
20268 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
20269 
20270 	switch (un->un_ctype) {
20271 	case CTYPE_CDROM:
20272 		info->dki_ctype = DKC_CDROM;
20273 		break;
20274 	default:
20275 		info->dki_ctype = DKC_SCSI_CCS;
20276 		break;
20277 	}
20278 	pdip = ddi_get_parent(SD_DEVINFO(un));
20279 	info->dki_cnum = ddi_get_instance(pdip);
20280 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
20281 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
20282 	} else {
20283 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
20284 		    DK_DEVLEN - 1);
20285 	}
20286 
20287 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20288 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
20289 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20290 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
20291 
20292 	/* Unit Information */
20293 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
20294 	info->dki_slave = ((tgt << 3) | lun);
20295 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
20296 	    DK_DEVLEN - 1);
20297 	info->dki_flags = DKI_FMTVOL;
20298 	info->dki_partition = SDPART(dev);
20299 
20300 	/* Max Transfer size of this device in blocks */
20301 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
20302 	info->dki_addr = 0;
20303 	info->dki_space = 0;
20304 	info->dki_prio = 0;
20305 	info->dki_vec = 0;
20306 
20307 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
20308 		kmem_free(info, sizeof (struct dk_cinfo));
20309 		return (EFAULT);
20310 	} else {
20311 		kmem_free(info, sizeof (struct dk_cinfo));
20312 		return (0);
20313 	}
20314 }
20315 
20316 
20317 /*
20318  *    Function: sd_get_media_info
20319  *
20320  * Description: This routine is the driver entry point for handling ioctl
20321  *		requests for the media type or command set profile used by the
20322  *		drive to operate on the media (DKIOCGMEDIAINFO).
20323  *
20324  *   Arguments: dev	- the device number
20325  *		arg	- pointer to user provided dk_minfo structure
20326  *			  specifying the media type, logical block size and
20327  *			  drive capacity.
20328  *		flag	- this argument is a pass through to ddi_copyxxx()
20329  *			  directly from the mode argument of ioctl().
20330  *
20331  * Return Code: 0
20332  *		EACCESS
20333  *		EFAULT
20334  *		ENXIO
20335  *		EIO
20336  */
20337 
20338 static int
20339 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
20340 {
20341 	struct sd_lun		*un = NULL;
20342 	struct uscsi_cmd	com;
20343 	struct scsi_inquiry	*sinq;
20344 	struct dk_minfo		media_info;
20345 	u_longlong_t		media_capacity;
20346 	uint64_t		capacity;
20347 	uint_t			lbasize;
20348 	uchar_t			*out_data;
20349 	uchar_t			*rqbuf;
20350 	int			rval = 0;
20351 	int			rtn;
20352 
20353 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
20354 	    (un->un_state == SD_STATE_OFFLINE)) {
20355 		return (ENXIO);
20356 	}
20357 
20358 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info: entry\n");
20359 
20360 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
20361 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
20362 
20363 	/* Issue a TUR to determine if the drive is ready with media present */
20364 	rval = sd_send_scsi_TEST_UNIT_READY(un, SD_CHECK_FOR_MEDIA);
20365 	if (rval == ENXIO) {
20366 		goto done;
20367 	}
20368 
20369 	/* Now get configuration data */
20370 	if (ISCD(un)) {
20371 		media_info.dki_media_type = DK_CDROM;
20372 
20373 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
20374 		if (un->un_f_mmc_cap == TRUE) {
20375 			rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf,
20376 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
20377 			    SD_PATH_STANDARD);
20378 
20379 			if (rtn) {
20380 				/*
20381 				 * Failed for other than an illegal request
20382 				 * or command not supported
20383 				 */
20384 				if ((com.uscsi_status == STATUS_CHECK) &&
20385 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
20386 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
20387 					    (rqbuf[12] != 0x20)) {
20388 						rval = EIO;
20389 						goto done;
20390 					}
20391 				}
20392 			} else {
20393 				/*
20394 				 * The GET CONFIGURATION command succeeded
20395 				 * so set the media type according to the
20396 				 * returned data
20397 				 */
20398 				media_info.dki_media_type = out_data[6];
20399 				media_info.dki_media_type <<= 8;
20400 				media_info.dki_media_type |= out_data[7];
20401 			}
20402 		}
20403 	} else {
20404 		/*
20405 		 * The profile list is not available, so we attempt to identify
20406 		 * the media type based on the inquiry data
20407 		 */
20408 		sinq = un->un_sd->sd_inq;
20409 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
20410 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
20411 			/* This is a direct access device  or optical disk */
20412 			media_info.dki_media_type = DK_FIXED_DISK;
20413 
20414 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
20415 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
20416 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
20417 					media_info.dki_media_type = DK_ZIP;
20418 				} else if (
20419 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
20420 					media_info.dki_media_type = DK_JAZ;
20421 				}
20422 			}
20423 		} else {
20424 			/*
20425 			 * Not a CD, direct access or optical disk so return
20426 			 * unknown media
20427 			 */
20428 			media_info.dki_media_type = DK_UNKNOWN;
20429 		}
20430 	}
20431 
20432 	/* Now read the capacity so we can provide the lbasize and capacity */
20433 	switch (sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
20434 	    SD_PATH_DIRECT)) {
20435 	case 0:
20436 		break;
20437 	case EACCES:
20438 		rval = EACCES;
20439 		goto done;
20440 	default:
20441 		rval = EIO;
20442 		goto done;
20443 	}
20444 
20445 	media_info.dki_lbsize = lbasize;
20446 	media_capacity = capacity;
20447 
20448 	/*
20449 	 * sd_send_scsi_READ_CAPACITY() reports capacity in
20450 	 * un->un_sys_blocksize chunks. So we need to convert it into
20451 	 * cap.lbasize chunks.
20452 	 */
20453 	media_capacity *= un->un_sys_blocksize;
20454 	media_capacity /= lbasize;
20455 	media_info.dki_capacity = media_capacity;
20456 
20457 	if (ddi_copyout(&media_info, arg, sizeof (struct dk_minfo), flag)) {
20458 		rval = EFAULT;
20459 		/* Put goto. Anybody might add some code below in future */
20460 		goto done;
20461 	}
20462 done:
20463 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
20464 	kmem_free(rqbuf, SENSE_LENGTH);
20465 	return (rval);
20466 }
20467 
20468 
20469 /*
20470  *    Function: sd_check_media
20471  *
20472  * Description: This utility routine implements the functionality for the
20473  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
20474  *		driver state changes from that specified by the user
20475  *		(inserted or ejected). For example, if the user specifies
20476  *		DKIO_EJECTED and the current media state is inserted this
20477  *		routine will immediately return DKIO_INSERTED. However, if the
20478  *		current media state is not inserted the user thread will be
20479  *		blocked until the drive state changes. If DKIO_NONE is specified
20480  *		the user thread will block until a drive state change occurs.
20481  *
20482  *   Arguments: dev  - the device number
20483  *		state  - user pointer to a dkio_state, updated with the current
20484  *			drive state at return.
20485  *
20486  * Return Code: ENXIO
20487  *		EIO
20488  *		EAGAIN
20489  *		EINTR
20490  */
20491 
20492 static int
20493 sd_check_media(dev_t dev, enum dkio_state state)
20494 {
20495 	struct sd_lun		*un = NULL;
20496 	enum dkio_state		prev_state;
20497 	opaque_t		token = NULL;
20498 	int			rval = 0;
20499 
20500 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20501 		return (ENXIO);
20502 	}
20503 
20504 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
20505 
20506 	mutex_enter(SD_MUTEX(un));
20507 
20508 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
20509 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
20510 
20511 	prev_state = un->un_mediastate;
20512 
20513 	/* is there anything to do? */
20514 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
20515 		/*
20516 		 * submit the request to the scsi_watch service;
20517 		 * scsi_media_watch_cb() does the real work
20518 		 */
20519 		mutex_exit(SD_MUTEX(un));
20520 
20521 		/*
20522 		 * This change handles the case where a scsi watch request is
20523 		 * added to a device that is powered down. To accomplish this
20524 		 * we power up the device before adding the scsi watch request,
20525 		 * since the scsi watch sends a TUR directly to the device
20526 		 * which the device cannot handle if it is powered down.
20527 		 */
20528 		if (sd_pm_entry(un) != DDI_SUCCESS) {
20529 			mutex_enter(SD_MUTEX(un));
20530 			goto done;
20531 		}
20532 
20533 		token = scsi_watch_request_submit(SD_SCSI_DEVP(un),
20534 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
20535 		    (caddr_t)dev);
20536 
20537 		sd_pm_exit(un);
20538 
20539 		mutex_enter(SD_MUTEX(un));
20540 		if (token == NULL) {
20541 			rval = EAGAIN;
20542 			goto done;
20543 		}
20544 
20545 		/*
20546 		 * This is a special case IOCTL that doesn't return
20547 		 * until the media state changes. Routine sdpower
20548 		 * knows about and handles this so don't count it
20549 		 * as an active cmd in the driver, which would
20550 		 * keep the device busy to the pm framework.
20551 		 * If the count isn't decremented the device can't
20552 		 * be powered down.
20553 		 */
20554 		un->un_ncmds_in_driver--;
20555 		ASSERT(un->un_ncmds_in_driver >= 0);
20556 
20557 		/*
20558 		 * if a prior request had been made, this will be the same
20559 		 * token, as scsi_watch was designed that way.
20560 		 */
20561 		un->un_swr_token = token;
20562 		un->un_specified_mediastate = state;
20563 
20564 		/*
20565 		 * now wait for media change
20566 		 * we will not be signalled unless mediastate == state but it is
20567 		 * still better to test for this condition, since there is a
20568 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
20569 		 */
20570 		SD_TRACE(SD_LOG_COMMON, un,
20571 		    "sd_check_media: waiting for media state change\n");
20572 		while (un->un_mediastate == state) {
20573 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
20574 				SD_TRACE(SD_LOG_COMMON, un,
20575 				    "sd_check_media: waiting for media state "
20576 				    "was interrupted\n");
20577 				un->un_ncmds_in_driver++;
20578 				rval = EINTR;
20579 				goto done;
20580 			}
20581 			SD_TRACE(SD_LOG_COMMON, un,
20582 			    "sd_check_media: received signal, state=%x\n",
20583 			    un->un_mediastate);
20584 		}
20585 		/*
20586 		 * Inc the counter to indicate the device once again
20587 		 * has an active outstanding cmd.
20588 		 */
20589 		un->un_ncmds_in_driver++;
20590 	}
20591 
20592 	/* invalidate geometry */
20593 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
20594 		sr_ejected(un);
20595 	}
20596 
20597 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
20598 		uint64_t	capacity;
20599 		uint_t		lbasize;
20600 
20601 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
20602 		mutex_exit(SD_MUTEX(un));
20603 		/*
20604 		 * Since the following routines use SD_PATH_DIRECT, we must
20605 		 * call PM directly before the upcoming disk accesses. This
20606 		 * may cause the disk to be power/spin up.
20607 		 */
20608 
20609 		if (sd_pm_entry(un) == DDI_SUCCESS) {
20610 			rval = sd_send_scsi_READ_CAPACITY(un,
20611 			    &capacity,
20612 			    &lbasize, SD_PATH_DIRECT);
20613 			if (rval != 0) {
20614 				sd_pm_exit(un);
20615 				mutex_enter(SD_MUTEX(un));
20616 				goto done;
20617 			}
20618 		} else {
20619 			rval = EIO;
20620 			mutex_enter(SD_MUTEX(un));
20621 			goto done;
20622 		}
20623 		mutex_enter(SD_MUTEX(un));
20624 
20625 		sd_update_block_info(un, lbasize, capacity);
20626 
20627 		/*
20628 		 *  Check if the media in the device is writable or not
20629 		 */
20630 		if (ISCD(un))
20631 			sd_check_for_writable_cd(un, SD_PATH_DIRECT);
20632 
20633 		mutex_exit(SD_MUTEX(un));
20634 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
20635 		if ((cmlb_validate(un->un_cmlbhandle, 0,
20636 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
20637 			sd_set_pstats(un);
20638 			SD_TRACE(SD_LOG_IO_PARTITION, un,
20639 			    "sd_check_media: un:0x%p pstats created and "
20640 			    "set\n", un);
20641 		}
20642 
20643 		rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
20644 		    SD_PATH_DIRECT);
20645 		sd_pm_exit(un);
20646 
20647 		mutex_enter(SD_MUTEX(un));
20648 	}
20649 done:
20650 	un->un_f_watcht_stopped = FALSE;
20651 	if (un->un_swr_token) {
20652 		/*
20653 		 * Use of this local token and the mutex ensures that we avoid
20654 		 * some race conditions associated with terminating the
20655 		 * scsi watch.
20656 		 */
20657 		token = un->un_swr_token;
20658 		un->un_swr_token = (opaque_t)NULL;
20659 		mutex_exit(SD_MUTEX(un));
20660 		(void) scsi_watch_request_terminate(token,
20661 		    SCSI_WATCH_TERMINATE_WAIT);
20662 		mutex_enter(SD_MUTEX(un));
20663 	}
20664 
20665 	/*
20666 	 * Update the capacity kstat value, if no media previously
20667 	 * (capacity kstat is 0) and a media has been inserted
20668 	 * (un_f_blockcount_is_valid == TRUE)
20669 	 */
20670 	if (un->un_errstats) {
20671 		struct sd_errstats	*stp = NULL;
20672 
20673 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
20674 		if ((stp->sd_capacity.value.ui64 == 0) &&
20675 		    (un->un_f_blockcount_is_valid == TRUE)) {
20676 			stp->sd_capacity.value.ui64 =
20677 			    (uint64_t)((uint64_t)un->un_blockcount *
20678 			    un->un_sys_blocksize);
20679 		}
20680 	}
20681 	mutex_exit(SD_MUTEX(un));
20682 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
20683 	return (rval);
20684 }
20685 
20686 
20687 /*
20688  *    Function: sd_delayed_cv_broadcast
20689  *
20690  * Description: Delayed cv_broadcast to allow for target to recover from media
20691  *		insertion.
20692  *
20693  *   Arguments: arg - driver soft state (unit) structure
20694  */
20695 
20696 static void
20697 sd_delayed_cv_broadcast(void *arg)
20698 {
20699 	struct sd_lun *un = arg;
20700 
20701 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
20702 
20703 	mutex_enter(SD_MUTEX(un));
20704 	un->un_dcvb_timeid = NULL;
20705 	cv_broadcast(&un->un_state_cv);
20706 	mutex_exit(SD_MUTEX(un));
20707 }
20708 
20709 
20710 /*
20711  *    Function: sd_media_watch_cb
20712  *
20713  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
20714  *		routine processes the TUR sense data and updates the driver
20715  *		state if a transition has occurred. The user thread
20716  *		(sd_check_media) is then signalled.
20717  *
20718  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
20719  *			among multiple watches that share this callback function
20720  *		resultp - scsi watch facility result packet containing scsi
20721  *			  packet, status byte and sense data
20722  *
20723  * Return Code: 0 for success, -1 for failure
20724  */
20725 
20726 static int
20727 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
20728 {
20729 	struct sd_lun			*un;
20730 	struct scsi_status		*statusp = resultp->statusp;
20731 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
20732 	enum dkio_state			state = DKIO_NONE;
20733 	dev_t				dev = (dev_t)arg;
20734 	uchar_t				actual_sense_length;
20735 	uint8_t				skey, asc, ascq;
20736 
20737 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20738 		return (-1);
20739 	}
20740 	actual_sense_length = resultp->actual_sense_length;
20741 
20742 	mutex_enter(SD_MUTEX(un));
20743 	SD_TRACE(SD_LOG_COMMON, un,
20744 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
20745 	    *((char *)statusp), (void *)sensep, actual_sense_length);
20746 
20747 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
20748 		un->un_mediastate = DKIO_DEV_GONE;
20749 		cv_broadcast(&un->un_state_cv);
20750 		mutex_exit(SD_MUTEX(un));
20751 
20752 		return (0);
20753 	}
20754 
20755 	/*
20756 	 * If there was a check condition then sensep points to valid sense data
20757 	 * If status was not a check condition but a reservation or busy status
20758 	 * then the new state is DKIO_NONE
20759 	 */
20760 	if (sensep != NULL) {
20761 		skey = scsi_sense_key(sensep);
20762 		asc = scsi_sense_asc(sensep);
20763 		ascq = scsi_sense_ascq(sensep);
20764 
20765 		SD_INFO(SD_LOG_COMMON, un,
20766 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
20767 		    skey, asc, ascq);
20768 		/* This routine only uses up to 13 bytes of sense data. */
20769 		if (actual_sense_length >= 13) {
20770 			if (skey == KEY_UNIT_ATTENTION) {
20771 				if (asc == 0x28) {
20772 					state = DKIO_INSERTED;
20773 				}
20774 			} else if (skey == KEY_NOT_READY) {
20775 				/*
20776 				 * if 02/04/02  means that the host
20777 				 * should send start command. Explicitly
20778 				 * leave the media state as is
20779 				 * (inserted) as the media is inserted
20780 				 * and host has stopped device for PM
20781 				 * reasons. Upon next true read/write
20782 				 * to this media will bring the
20783 				 * device to the right state good for
20784 				 * media access.
20785 				 */
20786 				if (asc == 0x3a) {
20787 					state = DKIO_EJECTED;
20788 				} else {
20789 					/*
20790 					 * If the drive is busy with an
20791 					 * operation or long write, keep the
20792 					 * media in an inserted state.
20793 					 */
20794 
20795 					if ((asc == 0x04) &&
20796 					    ((ascq == 0x02) ||
20797 					    (ascq == 0x07) ||
20798 					    (ascq == 0x08))) {
20799 						state = DKIO_INSERTED;
20800 					}
20801 				}
20802 			} else if (skey == KEY_NO_SENSE) {
20803 				if ((asc == 0x00) && (ascq == 0x00)) {
20804 					/*
20805 					 * Sense Data 00/00/00 does not provide
20806 					 * any information about the state of
20807 					 * the media. Ignore it.
20808 					 */
20809 					mutex_exit(SD_MUTEX(un));
20810 					return (0);
20811 				}
20812 			}
20813 		}
20814 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
20815 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
20816 		state = DKIO_INSERTED;
20817 	}
20818 
20819 	SD_TRACE(SD_LOG_COMMON, un,
20820 	    "sd_media_watch_cb: state=%x, specified=%x\n",
20821 	    state, un->un_specified_mediastate);
20822 
20823 	/*
20824 	 * now signal the waiting thread if this is *not* the specified state;
20825 	 * delay the signal if the state is DKIO_INSERTED to allow the target
20826 	 * to recover
20827 	 */
20828 	if (state != un->un_specified_mediastate) {
20829 		un->un_mediastate = state;
20830 		if (state == DKIO_INSERTED) {
20831 			/*
20832 			 * delay the signal to give the drive a chance
20833 			 * to do what it apparently needs to do
20834 			 */
20835 			SD_TRACE(SD_LOG_COMMON, un,
20836 			    "sd_media_watch_cb: delayed cv_broadcast\n");
20837 			if (un->un_dcvb_timeid == NULL) {
20838 				un->un_dcvb_timeid =
20839 				    timeout(sd_delayed_cv_broadcast, un,
20840 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
20841 			}
20842 		} else {
20843 			SD_TRACE(SD_LOG_COMMON, un,
20844 			    "sd_media_watch_cb: immediate cv_broadcast\n");
20845 			cv_broadcast(&un->un_state_cv);
20846 		}
20847 	}
20848 	mutex_exit(SD_MUTEX(un));
20849 	return (0);
20850 }
20851 
20852 
20853 /*
20854  *    Function: sd_dkio_get_temp
20855  *
20856  * Description: This routine is the driver entry point for handling ioctl
20857  *		requests to get the disk temperature.
20858  *
20859  *   Arguments: dev  - the device number
20860  *		arg  - pointer to user provided dk_temperature structure.
20861  *		flag - this argument is a pass through to ddi_copyxxx()
20862  *		       directly from the mode argument of ioctl().
20863  *
20864  * Return Code: 0
20865  *		EFAULT
20866  *		ENXIO
20867  *		EAGAIN
20868  */
20869 
20870 static int
20871 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
20872 {
20873 	struct sd_lun		*un = NULL;
20874 	struct dk_temperature	*dktemp = NULL;
20875 	uchar_t			*temperature_page;
20876 	int			rval = 0;
20877 	int			path_flag = SD_PATH_STANDARD;
20878 
20879 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20880 		return (ENXIO);
20881 	}
20882 
20883 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
20884 
20885 	/* copyin the disk temp argument to get the user flags */
20886 	if (ddi_copyin((void *)arg, dktemp,
20887 	    sizeof (struct dk_temperature), flag) != 0) {
20888 		rval = EFAULT;
20889 		goto done;
20890 	}
20891 
20892 	/* Initialize the temperature to invalid. */
20893 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
20894 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
20895 
20896 	/*
20897 	 * Note: Investigate removing the "bypass pm" semantic.
20898 	 * Can we just bypass PM always?
20899 	 */
20900 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
20901 		path_flag = SD_PATH_DIRECT;
20902 		ASSERT(!mutex_owned(&un->un_pm_mutex));
20903 		mutex_enter(&un->un_pm_mutex);
20904 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
20905 			/*
20906 			 * If DKT_BYPASS_PM is set, and the drive happens to be
20907 			 * in low power mode, we can not wake it up, Need to
20908 			 * return EAGAIN.
20909 			 */
20910 			mutex_exit(&un->un_pm_mutex);
20911 			rval = EAGAIN;
20912 			goto done;
20913 		} else {
20914 			/*
20915 			 * Indicate to PM the device is busy. This is required
20916 			 * to avoid a race - i.e. the ioctl is issuing a
20917 			 * command and the pm framework brings down the device
20918 			 * to low power mode (possible power cut-off on some
20919 			 * platforms).
20920 			 */
20921 			mutex_exit(&un->un_pm_mutex);
20922 			if (sd_pm_entry(un) != DDI_SUCCESS) {
20923 				rval = EAGAIN;
20924 				goto done;
20925 			}
20926 		}
20927 	}
20928 
20929 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
20930 
20931 	if ((rval = sd_send_scsi_LOG_SENSE(un, temperature_page,
20932 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag)) != 0) {
20933 		goto done2;
20934 	}
20935 
20936 	/*
20937 	 * For the current temperature verify that the parameter length is 0x02
20938 	 * and the parameter code is 0x00
20939 	 */
20940 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
20941 	    (temperature_page[5] == 0x00)) {
20942 		if (temperature_page[9] == 0xFF) {
20943 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
20944 		} else {
20945 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
20946 		}
20947 	}
20948 
20949 	/*
20950 	 * For the reference temperature verify that the parameter
20951 	 * length is 0x02 and the parameter code is 0x01
20952 	 */
20953 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
20954 	    (temperature_page[11] == 0x01)) {
20955 		if (temperature_page[15] == 0xFF) {
20956 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
20957 		} else {
20958 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
20959 		}
20960 	}
20961 
20962 	/* Do the copyout regardless of the temperature commands status. */
20963 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
20964 	    flag) != 0) {
20965 		rval = EFAULT;
20966 	}
20967 
20968 done2:
20969 	if (path_flag == SD_PATH_DIRECT) {
20970 		sd_pm_exit(un);
20971 	}
20972 
20973 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
20974 done:
20975 	if (dktemp != NULL) {
20976 		kmem_free(dktemp, sizeof (struct dk_temperature));
20977 	}
20978 
20979 	return (rval);
20980 }
20981 
20982 
20983 /*
20984  *    Function: sd_log_page_supported
20985  *
20986  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
20987  *		supported log pages.
20988  *
20989  *   Arguments: un -
20990  *		log_page -
20991  *
20992  * Return Code: -1 - on error (log sense is optional and may not be supported).
20993  *		0  - log page not found.
20994  *  		1  - log page found.
20995  */
20996 
20997 static int
20998 sd_log_page_supported(struct sd_lun *un, int log_page)
20999 {
21000 	uchar_t *log_page_data;
21001 	int	i;
21002 	int	match = 0;
21003 	int	log_size;
21004 
21005 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
21006 
21007 	if (sd_send_scsi_LOG_SENSE(un, log_page_data, 0xFF, 0, 0x01, 0,
21008 	    SD_PATH_DIRECT) != 0) {
21009 		SD_ERROR(SD_LOG_COMMON, un,
21010 		    "sd_log_page_supported: failed log page retrieval\n");
21011 		kmem_free(log_page_data, 0xFF);
21012 		return (-1);
21013 	}
21014 	log_size = log_page_data[3];
21015 
21016 	/*
21017 	 * The list of supported log pages start from the fourth byte. Check
21018 	 * until we run out of log pages or a match is found.
21019 	 */
21020 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
21021 		if (log_page_data[i] == log_page) {
21022 			match++;
21023 		}
21024 	}
21025 	kmem_free(log_page_data, 0xFF);
21026 	return (match);
21027 }
21028 
21029 
21030 /*
21031  *    Function: sd_mhdioc_failfast
21032  *
21033  * Description: This routine is the driver entry point for handling ioctl
21034  *		requests to enable/disable the multihost failfast option.
21035  *		(MHIOCENFAILFAST)
21036  *
21037  *   Arguments: dev	- the device number
21038  *		arg	- user specified probing interval.
21039  *		flag	- this argument is a pass through to ddi_copyxxx()
21040  *			  directly from the mode argument of ioctl().
21041  *
21042  * Return Code: 0
21043  *		EFAULT
21044  *		ENXIO
21045  */
21046 
21047 static int
21048 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
21049 {
21050 	struct sd_lun	*un = NULL;
21051 	int		mh_time;
21052 	int		rval = 0;
21053 
21054 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21055 		return (ENXIO);
21056 	}
21057 
21058 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
21059 		return (EFAULT);
21060 
21061 	if (mh_time) {
21062 		mutex_enter(SD_MUTEX(un));
21063 		un->un_resvd_status |= SD_FAILFAST;
21064 		mutex_exit(SD_MUTEX(un));
21065 		/*
21066 		 * If mh_time is INT_MAX, then this ioctl is being used for
21067 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
21068 		 */
21069 		if (mh_time != INT_MAX) {
21070 			rval = sd_check_mhd(dev, mh_time);
21071 		}
21072 	} else {
21073 		(void) sd_check_mhd(dev, 0);
21074 		mutex_enter(SD_MUTEX(un));
21075 		un->un_resvd_status &= ~SD_FAILFAST;
21076 		mutex_exit(SD_MUTEX(un));
21077 	}
21078 	return (rval);
21079 }
21080 
21081 
21082 /*
21083  *    Function: sd_mhdioc_takeown
21084  *
21085  * Description: This routine is the driver entry point for handling ioctl
21086  *		requests to forcefully acquire exclusive access rights to the
21087  *		multihost disk (MHIOCTKOWN).
21088  *
21089  *   Arguments: dev	- the device number
21090  *		arg	- user provided structure specifying the delay
21091  *			  parameters in milliseconds
21092  *		flag	- this argument is a pass through to ddi_copyxxx()
21093  *			  directly from the mode argument of ioctl().
21094  *
21095  * Return Code: 0
21096  *		EFAULT
21097  *		ENXIO
21098  */
21099 
21100 static int
21101 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
21102 {
21103 	struct sd_lun		*un = NULL;
21104 	struct mhioctkown	*tkown = NULL;
21105 	int			rval = 0;
21106 
21107 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21108 		return (ENXIO);
21109 	}
21110 
21111 	if (arg != NULL) {
21112 		tkown = (struct mhioctkown *)
21113 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
21114 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
21115 		if (rval != 0) {
21116 			rval = EFAULT;
21117 			goto error;
21118 		}
21119 	}
21120 
21121 	rval = sd_take_ownership(dev, tkown);
21122 	mutex_enter(SD_MUTEX(un));
21123 	if (rval == 0) {
21124 		un->un_resvd_status |= SD_RESERVE;
21125 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
21126 			sd_reinstate_resv_delay =
21127 			    tkown->reinstate_resv_delay * 1000;
21128 		} else {
21129 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
21130 		}
21131 		/*
21132 		 * Give the scsi_watch routine interval set by
21133 		 * the MHIOCENFAILFAST ioctl precedence here.
21134 		 */
21135 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
21136 			mutex_exit(SD_MUTEX(un));
21137 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
21138 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
21139 			    "sd_mhdioc_takeown : %d\n",
21140 			    sd_reinstate_resv_delay);
21141 		} else {
21142 			mutex_exit(SD_MUTEX(un));
21143 		}
21144 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
21145 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21146 	} else {
21147 		un->un_resvd_status &= ~SD_RESERVE;
21148 		mutex_exit(SD_MUTEX(un));
21149 	}
21150 
21151 error:
21152 	if (tkown != NULL) {
21153 		kmem_free(tkown, sizeof (struct mhioctkown));
21154 	}
21155 	return (rval);
21156 }
21157 
21158 
21159 /*
21160  *    Function: sd_mhdioc_release
21161  *
21162  * Description: This routine is the driver entry point for handling ioctl
21163  *		requests to release exclusive access rights to the multihost
21164  *		disk (MHIOCRELEASE).
21165  *
21166  *   Arguments: dev	- the device number
21167  *
21168  * Return Code: 0
21169  *		ENXIO
21170  */
21171 
21172 static int
21173 sd_mhdioc_release(dev_t dev)
21174 {
21175 	struct sd_lun		*un = NULL;
21176 	timeout_id_t		resvd_timeid_save;
21177 	int			resvd_status_save;
21178 	int			rval = 0;
21179 
21180 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21181 		return (ENXIO);
21182 	}
21183 
21184 	mutex_enter(SD_MUTEX(un));
21185 	resvd_status_save = un->un_resvd_status;
21186 	un->un_resvd_status &=
21187 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
21188 	if (un->un_resvd_timeid) {
21189 		resvd_timeid_save = un->un_resvd_timeid;
21190 		un->un_resvd_timeid = NULL;
21191 		mutex_exit(SD_MUTEX(un));
21192 		(void) untimeout(resvd_timeid_save);
21193 	} else {
21194 		mutex_exit(SD_MUTEX(un));
21195 	}
21196 
21197 	/*
21198 	 * destroy any pending timeout thread that may be attempting to
21199 	 * reinstate reservation on this device.
21200 	 */
21201 	sd_rmv_resv_reclaim_req(dev);
21202 
21203 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
21204 		mutex_enter(SD_MUTEX(un));
21205 		if ((un->un_mhd_token) &&
21206 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
21207 			mutex_exit(SD_MUTEX(un));
21208 			(void) sd_check_mhd(dev, 0);
21209 		} else {
21210 			mutex_exit(SD_MUTEX(un));
21211 		}
21212 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
21213 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21214 	} else {
21215 		/*
21216 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
21217 		 */
21218 		mutex_enter(SD_MUTEX(un));
21219 		un->un_resvd_status = resvd_status_save;
21220 		mutex_exit(SD_MUTEX(un));
21221 	}
21222 	return (rval);
21223 }
21224 
21225 
21226 /*
21227  *    Function: sd_mhdioc_register_devid
21228  *
21229  * Description: This routine is the driver entry point for handling ioctl
21230  *		requests to register the device id (MHIOCREREGISTERDEVID).
21231  *
21232  *		Note: The implementation for this ioctl has been updated to
21233  *		be consistent with the original PSARC case (1999/357)
21234  *		(4375899, 4241671, 4220005)
21235  *
21236  *   Arguments: dev	- the device number
21237  *
21238  * Return Code: 0
21239  *		ENXIO
21240  */
21241 
21242 static int
21243 sd_mhdioc_register_devid(dev_t dev)
21244 {
21245 	struct sd_lun	*un = NULL;
21246 	int		rval = 0;
21247 
21248 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21249 		return (ENXIO);
21250 	}
21251 
21252 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21253 
21254 	mutex_enter(SD_MUTEX(un));
21255 
21256 	/* If a devid already exists, de-register it */
21257 	if (un->un_devid != NULL) {
21258 		ddi_devid_unregister(SD_DEVINFO(un));
21259 		/*
21260 		 * After unregister devid, needs to free devid memory
21261 		 */
21262 		ddi_devid_free(un->un_devid);
21263 		un->un_devid = NULL;
21264 	}
21265 
21266 	/* Check for reservation conflict */
21267 	mutex_exit(SD_MUTEX(un));
21268 	rval = sd_send_scsi_TEST_UNIT_READY(un, 0);
21269 	mutex_enter(SD_MUTEX(un));
21270 
21271 	switch (rval) {
21272 	case 0:
21273 		sd_register_devid(un, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
21274 		break;
21275 	case EACCES:
21276 		break;
21277 	default:
21278 		rval = EIO;
21279 	}
21280 
21281 	mutex_exit(SD_MUTEX(un));
21282 	return (rval);
21283 }
21284 
21285 
21286 /*
21287  *    Function: sd_mhdioc_inkeys
21288  *
21289  * Description: This routine is the driver entry point for handling ioctl
21290  *		requests to issue the SCSI-3 Persistent In Read Keys command
21291  *		to the device (MHIOCGRP_INKEYS).
21292  *
21293  *   Arguments: dev	- the device number
21294  *		arg	- user provided in_keys structure
21295  *		flag	- this argument is a pass through to ddi_copyxxx()
21296  *			  directly from the mode argument of ioctl().
21297  *
21298  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
21299  *		ENXIO
21300  *		EFAULT
21301  */
21302 
21303 static int
21304 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
21305 {
21306 	struct sd_lun		*un;
21307 	mhioc_inkeys_t		inkeys;
21308 	int			rval = 0;
21309 
21310 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21311 		return (ENXIO);
21312 	}
21313 
21314 #ifdef _MULTI_DATAMODEL
21315 	switch (ddi_model_convert_from(flag & FMODELS)) {
21316 	case DDI_MODEL_ILP32: {
21317 		struct mhioc_inkeys32	inkeys32;
21318 
21319 		if (ddi_copyin(arg, &inkeys32,
21320 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
21321 			return (EFAULT);
21322 		}
21323 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
21324 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21325 		    &inkeys, flag)) != 0) {
21326 			return (rval);
21327 		}
21328 		inkeys32.generation = inkeys.generation;
21329 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
21330 		    flag) != 0) {
21331 			return (EFAULT);
21332 		}
21333 		break;
21334 	}
21335 	case DDI_MODEL_NONE:
21336 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
21337 		    flag) != 0) {
21338 			return (EFAULT);
21339 		}
21340 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21341 		    &inkeys, flag)) != 0) {
21342 			return (rval);
21343 		}
21344 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
21345 		    flag) != 0) {
21346 			return (EFAULT);
21347 		}
21348 		break;
21349 	}
21350 
21351 #else /* ! _MULTI_DATAMODEL */
21352 
21353 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
21354 		return (EFAULT);
21355 	}
21356 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
21357 	if (rval != 0) {
21358 		return (rval);
21359 	}
21360 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
21361 		return (EFAULT);
21362 	}
21363 
21364 #endif /* _MULTI_DATAMODEL */
21365 
21366 	return (rval);
21367 }
21368 
21369 
21370 /*
21371  *    Function: sd_mhdioc_inresv
21372  *
21373  * Description: This routine is the driver entry point for handling ioctl
21374  *		requests to issue the SCSI-3 Persistent In Read Reservations
21375  *		command to the device (MHIOCGRP_INKEYS).
21376  *
21377  *   Arguments: dev	- the device number
21378  *		arg	- user provided in_resv structure
21379  *		flag	- this argument is a pass through to ddi_copyxxx()
21380  *			  directly from the mode argument of ioctl().
21381  *
21382  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
21383  *		ENXIO
21384  *		EFAULT
21385  */
21386 
21387 static int
21388 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
21389 {
21390 	struct sd_lun		*un;
21391 	mhioc_inresvs_t		inresvs;
21392 	int			rval = 0;
21393 
21394 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21395 		return (ENXIO);
21396 	}
21397 
21398 #ifdef _MULTI_DATAMODEL
21399 
21400 	switch (ddi_model_convert_from(flag & FMODELS)) {
21401 	case DDI_MODEL_ILP32: {
21402 		struct mhioc_inresvs32	inresvs32;
21403 
21404 		if (ddi_copyin(arg, &inresvs32,
21405 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21406 			return (EFAULT);
21407 		}
21408 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
21409 		if ((rval = sd_persistent_reservation_in_read_resv(un,
21410 		    &inresvs, flag)) != 0) {
21411 			return (rval);
21412 		}
21413 		inresvs32.generation = inresvs.generation;
21414 		if (ddi_copyout(&inresvs32, arg,
21415 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21416 			return (EFAULT);
21417 		}
21418 		break;
21419 	}
21420 	case DDI_MODEL_NONE:
21421 		if (ddi_copyin(arg, &inresvs,
21422 		    sizeof (mhioc_inresvs_t), flag) != 0) {
21423 			return (EFAULT);
21424 		}
21425 		if ((rval = sd_persistent_reservation_in_read_resv(un,
21426 		    &inresvs, flag)) != 0) {
21427 			return (rval);
21428 		}
21429 		if (ddi_copyout(&inresvs, arg,
21430 		    sizeof (mhioc_inresvs_t), flag) != 0) {
21431 			return (EFAULT);
21432 		}
21433 		break;
21434 	}
21435 
21436 #else /* ! _MULTI_DATAMODEL */
21437 
21438 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
21439 		return (EFAULT);
21440 	}
21441 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
21442 	if (rval != 0) {
21443 		return (rval);
21444 	}
21445 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
21446 		return (EFAULT);
21447 	}
21448 
21449 #endif /* ! _MULTI_DATAMODEL */
21450 
21451 	return (rval);
21452 }
21453 
21454 
21455 /*
21456  * The following routines support the clustering functionality described below
21457  * and implement lost reservation reclaim functionality.
21458  *
21459  * Clustering
21460  * ----------
21461  * The clustering code uses two different, independent forms of SCSI
21462  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
21463  * Persistent Group Reservations. For any particular disk, it will use either
21464  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
21465  *
21466  * SCSI-2
21467  * The cluster software takes ownership of a multi-hosted disk by issuing the
21468  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
21469  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
21470  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
21471  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
21472  * driver. The meaning of failfast is that if the driver (on this host) ever
21473  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
21474  * it should immediately panic the host. The motivation for this ioctl is that
21475  * if this host does encounter reservation conflict, the underlying cause is
21476  * that some other host of the cluster has decided that this host is no longer
21477  * in the cluster and has seized control of the disks for itself. Since this
21478  * host is no longer in the cluster, it ought to panic itself. The
21479  * MHIOCENFAILFAST ioctl does two things:
21480  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
21481  *      error to panic the host
21482  *      (b) it sets up a periodic timer to test whether this host still has
21483  *      "access" (in that no other host has reserved the device):  if the
21484  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
21485  *      purpose of that periodic timer is to handle scenarios where the host is
21486  *      otherwise temporarily quiescent, temporarily doing no real i/o.
21487  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
21488  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
21489  * the device itself.
21490  *
21491  * SCSI-3 PGR
21492  * A direct semantic implementation of the SCSI-3 Persistent Reservation
21493  * facility is supported through the shared multihost disk ioctls
21494  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
21495  * MHIOCGRP_PREEMPTANDABORT)
21496  *
21497  * Reservation Reclaim:
21498  * --------------------
21499  * To support the lost reservation reclaim operations this driver creates a
21500  * single thread to handle reinstating reservations on all devices that have
21501  * lost reservations sd_resv_reclaim_requests are logged for all devices that
21502  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
21503  * and the reservation reclaim thread loops through the requests to regain the
21504  * lost reservations.
21505  */
21506 
21507 /*
21508  *    Function: sd_check_mhd()
21509  *
21510  * Description: This function sets up and submits a scsi watch request or
21511  *		terminates an existing watch request. This routine is used in
21512  *		support of reservation reclaim.
21513  *
21514  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
21515  *			 among multiple watches that share the callback function
21516  *		interval - the number of microseconds specifying the watch
21517  *			   interval for issuing TEST UNIT READY commands. If
21518  *			   set to 0 the watch should be terminated. If the
21519  *			   interval is set to 0 and if the device is required
21520  *			   to hold reservation while disabling failfast, the
21521  *			   watch is restarted with an interval of
21522  *			   reinstate_resv_delay.
21523  *
21524  * Return Code: 0	   - Successful submit/terminate of scsi watch request
21525  *		ENXIO      - Indicates an invalid device was specified
21526  *		EAGAIN     - Unable to submit the scsi watch request
21527  */
21528 
21529 static int
21530 sd_check_mhd(dev_t dev, int interval)
21531 {
21532 	struct sd_lun	*un;
21533 	opaque_t	token;
21534 
21535 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21536 		return (ENXIO);
21537 	}
21538 
21539 	/* is this a watch termination request? */
21540 	if (interval == 0) {
21541 		mutex_enter(SD_MUTEX(un));
21542 		/* if there is an existing watch task then terminate it */
21543 		if (un->un_mhd_token) {
21544 			token = un->un_mhd_token;
21545 			un->un_mhd_token = NULL;
21546 			mutex_exit(SD_MUTEX(un));
21547 			(void) scsi_watch_request_terminate(token,
21548 			    SCSI_WATCH_TERMINATE_WAIT);
21549 			mutex_enter(SD_MUTEX(un));
21550 		} else {
21551 			mutex_exit(SD_MUTEX(un));
21552 			/*
21553 			 * Note: If we return here we don't check for the
21554 			 * failfast case. This is the original legacy
21555 			 * implementation but perhaps we should be checking
21556 			 * the failfast case.
21557 			 */
21558 			return (0);
21559 		}
21560 		/*
21561 		 * If the device is required to hold reservation while
21562 		 * disabling failfast, we need to restart the scsi_watch
21563 		 * routine with an interval of reinstate_resv_delay.
21564 		 */
21565 		if (un->un_resvd_status & SD_RESERVE) {
21566 			interval = sd_reinstate_resv_delay/1000;
21567 		} else {
21568 			/* no failfast so bail */
21569 			mutex_exit(SD_MUTEX(un));
21570 			return (0);
21571 		}
21572 		mutex_exit(SD_MUTEX(un));
21573 	}
21574 
21575 	/*
21576 	 * adjust minimum time interval to 1 second,
21577 	 * and convert from msecs to usecs
21578 	 */
21579 	if (interval > 0 && interval < 1000) {
21580 		interval = 1000;
21581 	}
21582 	interval *= 1000;
21583 
21584 	/*
21585 	 * submit the request to the scsi_watch service
21586 	 */
21587 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
21588 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
21589 	if (token == NULL) {
21590 		return (EAGAIN);
21591 	}
21592 
21593 	/*
21594 	 * save token for termination later on
21595 	 */
21596 	mutex_enter(SD_MUTEX(un));
21597 	un->un_mhd_token = token;
21598 	mutex_exit(SD_MUTEX(un));
21599 	return (0);
21600 }
21601 
21602 
21603 /*
21604  *    Function: sd_mhd_watch_cb()
21605  *
21606  * Description: This function is the call back function used by the scsi watch
21607  *		facility. The scsi watch facility sends the "Test Unit Ready"
21608  *		and processes the status. If applicable (i.e. a "Unit Attention"
21609  *		status and automatic "Request Sense" not used) the scsi watch
21610  *		facility will send a "Request Sense" and retrieve the sense data
21611  *		to be passed to this callback function. In either case the
21612  *		automatic "Request Sense" or the facility submitting one, this
21613  *		callback is passed the status and sense data.
21614  *
21615  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
21616  *			among multiple watches that share this callback function
21617  *		resultp - scsi watch facility result packet containing scsi
21618  *			  packet, status byte and sense data
21619  *
21620  * Return Code: 0 - continue the watch task
21621  *		non-zero - terminate the watch task
21622  */
21623 
21624 static int
21625 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
21626 {
21627 	struct sd_lun			*un;
21628 	struct scsi_status		*statusp;
21629 	uint8_t				*sensep;
21630 	struct scsi_pkt			*pkt;
21631 	uchar_t				actual_sense_length;
21632 	dev_t  				dev = (dev_t)arg;
21633 
21634 	ASSERT(resultp != NULL);
21635 	statusp			= resultp->statusp;
21636 	sensep			= (uint8_t *)resultp->sensep;
21637 	pkt			= resultp->pkt;
21638 	actual_sense_length	= resultp->actual_sense_length;
21639 
21640 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21641 		return (ENXIO);
21642 	}
21643 
21644 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
21645 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
21646 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
21647 
21648 	/* Begin processing of the status and/or sense data */
21649 	if (pkt->pkt_reason != CMD_CMPLT) {
21650 		/* Handle the incomplete packet */
21651 		sd_mhd_watch_incomplete(un, pkt);
21652 		return (0);
21653 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
21654 		if (*((unsigned char *)statusp)
21655 		    == STATUS_RESERVATION_CONFLICT) {
21656 			/*
21657 			 * Handle a reservation conflict by panicking if
21658 			 * configured for failfast or by logging the conflict
21659 			 * and updating the reservation status
21660 			 */
21661 			mutex_enter(SD_MUTEX(un));
21662 			if ((un->un_resvd_status & SD_FAILFAST) &&
21663 			    (sd_failfast_enable)) {
21664 				sd_panic_for_res_conflict(un);
21665 				/*NOTREACHED*/
21666 			}
21667 			SD_INFO(SD_LOG_IOCTL_MHD, un,
21668 			    "sd_mhd_watch_cb: Reservation Conflict\n");
21669 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
21670 			mutex_exit(SD_MUTEX(un));
21671 		}
21672 	}
21673 
21674 	if (sensep != NULL) {
21675 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
21676 			mutex_enter(SD_MUTEX(un));
21677 			if ((scsi_sense_asc(sensep) ==
21678 			    SD_SCSI_RESET_SENSE_CODE) &&
21679 			    (un->un_resvd_status & SD_RESERVE)) {
21680 				/*
21681 				 * The additional sense code indicates a power
21682 				 * on or bus device reset has occurred; update
21683 				 * the reservation status.
21684 				 */
21685 				un->un_resvd_status |=
21686 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
21687 				SD_INFO(SD_LOG_IOCTL_MHD, un,
21688 				    "sd_mhd_watch_cb: Lost Reservation\n");
21689 			}
21690 		} else {
21691 			return (0);
21692 		}
21693 	} else {
21694 		mutex_enter(SD_MUTEX(un));
21695 	}
21696 
21697 	if ((un->un_resvd_status & SD_RESERVE) &&
21698 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
21699 		if (un->un_resvd_status & SD_WANT_RESERVE) {
21700 			/*
21701 			 * A reset occurred in between the last probe and this
21702 			 * one so if a timeout is pending cancel it.
21703 			 */
21704 			if (un->un_resvd_timeid) {
21705 				timeout_id_t temp_id = un->un_resvd_timeid;
21706 				un->un_resvd_timeid = NULL;
21707 				mutex_exit(SD_MUTEX(un));
21708 				(void) untimeout(temp_id);
21709 				mutex_enter(SD_MUTEX(un));
21710 			}
21711 			un->un_resvd_status &= ~SD_WANT_RESERVE;
21712 		}
21713 		if (un->un_resvd_timeid == 0) {
21714 			/* Schedule a timeout to handle the lost reservation */
21715 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
21716 			    (void *)dev,
21717 			    drv_usectohz(sd_reinstate_resv_delay));
21718 		}
21719 	}
21720 	mutex_exit(SD_MUTEX(un));
21721 	return (0);
21722 }
21723 
21724 
21725 /*
21726  *    Function: sd_mhd_watch_incomplete()
21727  *
21728  * Description: This function is used to find out why a scsi pkt sent by the
21729  *		scsi watch facility was not completed. Under some scenarios this
21730  *		routine will return. Otherwise it will send a bus reset to see
21731  *		if the drive is still online.
21732  *
21733  *   Arguments: un  - driver soft state (unit) structure
21734  *		pkt - incomplete scsi pkt
21735  */
21736 
21737 static void
21738 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
21739 {
21740 	int	be_chatty;
21741 	int	perr;
21742 
21743 	ASSERT(pkt != NULL);
21744 	ASSERT(un != NULL);
21745 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
21746 	perr		= (pkt->pkt_statistics & STAT_PERR);
21747 
21748 	mutex_enter(SD_MUTEX(un));
21749 	if (un->un_state == SD_STATE_DUMPING) {
21750 		mutex_exit(SD_MUTEX(un));
21751 		return;
21752 	}
21753 
21754 	switch (pkt->pkt_reason) {
21755 	case CMD_UNX_BUS_FREE:
21756 		/*
21757 		 * If we had a parity error that caused the target to drop BSY*,
21758 		 * don't be chatty about it.
21759 		 */
21760 		if (perr && be_chatty) {
21761 			be_chatty = 0;
21762 		}
21763 		break;
21764 	case CMD_TAG_REJECT:
21765 		/*
21766 		 * The SCSI-2 spec states that a tag reject will be sent by the
21767 		 * target if tagged queuing is not supported. A tag reject may
21768 		 * also be sent during certain initialization periods or to
21769 		 * control internal resources. For the latter case the target
21770 		 * may also return Queue Full.
21771 		 *
21772 		 * If this driver receives a tag reject from a target that is
21773 		 * going through an init period or controlling internal
21774 		 * resources tagged queuing will be disabled. This is a less
21775 		 * than optimal behavior but the driver is unable to determine
21776 		 * the target state and assumes tagged queueing is not supported
21777 		 */
21778 		pkt->pkt_flags = 0;
21779 		un->un_tagflags = 0;
21780 
21781 		if (un->un_f_opt_queueing == TRUE) {
21782 			un->un_throttle = min(un->un_throttle, 3);
21783 		} else {
21784 			un->un_throttle = 1;
21785 		}
21786 		mutex_exit(SD_MUTEX(un));
21787 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
21788 		mutex_enter(SD_MUTEX(un));
21789 		break;
21790 	case CMD_INCOMPLETE:
21791 		/*
21792 		 * The transport stopped with an abnormal state, fallthrough and
21793 		 * reset the target and/or bus unless selection did not complete
21794 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
21795 		 * go through a target/bus reset
21796 		 */
21797 		if (pkt->pkt_state == STATE_GOT_BUS) {
21798 			break;
21799 		}
21800 		/*FALLTHROUGH*/
21801 
21802 	case CMD_TIMEOUT:
21803 	default:
21804 		/*
21805 		 * The lun may still be running the command, so a lun reset
21806 		 * should be attempted. If the lun reset fails or cannot be
21807 		 * issued, than try a target reset. Lastly try a bus reset.
21808 		 */
21809 		if ((pkt->pkt_statistics &
21810 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
21811 			int reset_retval = 0;
21812 			mutex_exit(SD_MUTEX(un));
21813 			if (un->un_f_allow_bus_device_reset == TRUE) {
21814 				if (un->un_f_lun_reset_enabled == TRUE) {
21815 					reset_retval =
21816 					    scsi_reset(SD_ADDRESS(un),
21817 					    RESET_LUN);
21818 				}
21819 				if (reset_retval == 0) {
21820 					reset_retval =
21821 					    scsi_reset(SD_ADDRESS(un),
21822 					    RESET_TARGET);
21823 				}
21824 			}
21825 			if (reset_retval == 0) {
21826 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
21827 			}
21828 			mutex_enter(SD_MUTEX(un));
21829 		}
21830 		break;
21831 	}
21832 
21833 	/* A device/bus reset has occurred; update the reservation status. */
21834 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
21835 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
21836 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
21837 			un->un_resvd_status |=
21838 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
21839 			SD_INFO(SD_LOG_IOCTL_MHD, un,
21840 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
21841 		}
21842 	}
21843 
21844 	/*
21845 	 * The disk has been turned off; Update the device state.
21846 	 *
21847 	 * Note: Should we be offlining the disk here?
21848 	 */
21849 	if (pkt->pkt_state == STATE_GOT_BUS) {
21850 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
21851 		    "Disk not responding to selection\n");
21852 		if (un->un_state != SD_STATE_OFFLINE) {
21853 			New_state(un, SD_STATE_OFFLINE);
21854 		}
21855 	} else if (be_chatty) {
21856 		/*
21857 		 * suppress messages if they are all the same pkt reason;
21858 		 * with TQ, many (up to 256) are returned with the same
21859 		 * pkt_reason
21860 		 */
21861 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
21862 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
21863 			    "sd_mhd_watch_incomplete: "
21864 			    "SCSI transport failed: reason '%s'\n",
21865 			    scsi_rname(pkt->pkt_reason));
21866 		}
21867 	}
21868 	un->un_last_pkt_reason = pkt->pkt_reason;
21869 	mutex_exit(SD_MUTEX(un));
21870 }
21871 
21872 
21873 /*
21874  *    Function: sd_sname()
21875  *
21876  * Description: This is a simple little routine to return a string containing
21877  *		a printable description of command status byte for use in
21878  *		logging.
21879  *
21880  *   Arguments: status - pointer to a status byte
21881  *
21882  * Return Code: char * - string containing status description.
21883  */
21884 
21885 static char *
21886 sd_sname(uchar_t status)
21887 {
21888 	switch (status & STATUS_MASK) {
21889 	case STATUS_GOOD:
21890 		return ("good status");
21891 	case STATUS_CHECK:
21892 		return ("check condition");
21893 	case STATUS_MET:
21894 		return ("condition met");
21895 	case STATUS_BUSY:
21896 		return ("busy");
21897 	case STATUS_INTERMEDIATE:
21898 		return ("intermediate");
21899 	case STATUS_INTERMEDIATE_MET:
21900 		return ("intermediate - condition met");
21901 	case STATUS_RESERVATION_CONFLICT:
21902 		return ("reservation_conflict");
21903 	case STATUS_TERMINATED:
21904 		return ("command terminated");
21905 	case STATUS_QFULL:
21906 		return ("queue full");
21907 	default:
21908 		return ("<unknown status>");
21909 	}
21910 }
21911 
21912 
21913 /*
21914  *    Function: sd_mhd_resvd_recover()
21915  *
21916  * Description: This function adds a reservation entry to the
21917  *		sd_resv_reclaim_request list and signals the reservation
21918  *		reclaim thread that there is work pending. If the reservation
21919  *		reclaim thread has not been previously created this function
21920  *		will kick it off.
21921  *
21922  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
21923  *			among multiple watches that share this callback function
21924  *
21925  *     Context: This routine is called by timeout() and is run in interrupt
21926  *		context. It must not sleep or call other functions which may
21927  *		sleep.
21928  */
21929 
21930 static void
21931 sd_mhd_resvd_recover(void *arg)
21932 {
21933 	dev_t			dev = (dev_t)arg;
21934 	struct sd_lun		*un;
21935 	struct sd_thr_request	*sd_treq = NULL;
21936 	struct sd_thr_request	*sd_cur = NULL;
21937 	struct sd_thr_request	*sd_prev = NULL;
21938 	int			already_there = 0;
21939 
21940 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21941 		return;
21942 	}
21943 
21944 	mutex_enter(SD_MUTEX(un));
21945 	un->un_resvd_timeid = NULL;
21946 	if (un->un_resvd_status & SD_WANT_RESERVE) {
21947 		/*
21948 		 * There was a reset so don't issue the reserve, allow the
21949 		 * sd_mhd_watch_cb callback function to notice this and
21950 		 * reschedule the timeout for reservation.
21951 		 */
21952 		mutex_exit(SD_MUTEX(un));
21953 		return;
21954 	}
21955 	mutex_exit(SD_MUTEX(un));
21956 
21957 	/*
21958 	 * Add this device to the sd_resv_reclaim_request list and the
21959 	 * sd_resv_reclaim_thread should take care of the rest.
21960 	 *
21961 	 * Note: We can't sleep in this context so if the memory allocation
21962 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
21963 	 * reschedule the timeout for reservation.  (4378460)
21964 	 */
21965 	sd_treq = (struct sd_thr_request *)
21966 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
21967 	if (sd_treq == NULL) {
21968 		return;
21969 	}
21970 
21971 	sd_treq->sd_thr_req_next = NULL;
21972 	sd_treq->dev = dev;
21973 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
21974 	if (sd_tr.srq_thr_req_head == NULL) {
21975 		sd_tr.srq_thr_req_head = sd_treq;
21976 	} else {
21977 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
21978 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
21979 			if (sd_cur->dev == dev) {
21980 				/*
21981 				 * already in Queue so don't log
21982 				 * another request for the device
21983 				 */
21984 				already_there = 1;
21985 				break;
21986 			}
21987 			sd_prev = sd_cur;
21988 		}
21989 		if (!already_there) {
21990 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
21991 			    "logging request for %lx\n", dev);
21992 			sd_prev->sd_thr_req_next = sd_treq;
21993 		} else {
21994 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
21995 		}
21996 	}
21997 
21998 	/*
21999 	 * Create a kernel thread to do the reservation reclaim and free up this
22000 	 * thread. We cannot block this thread while we go away to do the
22001 	 * reservation reclaim
22002 	 */
22003 	if (sd_tr.srq_resv_reclaim_thread == NULL)
22004 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
22005 		    sd_resv_reclaim_thread, NULL,
22006 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
22007 
22008 	/* Tell the reservation reclaim thread that it has work to do */
22009 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
22010 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22011 }
22012 
22013 /*
22014  *    Function: sd_resv_reclaim_thread()
22015  *
22016  * Description: This function implements the reservation reclaim operations
22017  *
22018  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
22019  *		      among multiple watches that share this callback function
22020  */
22021 
22022 static void
22023 sd_resv_reclaim_thread()
22024 {
22025 	struct sd_lun		*un;
22026 	struct sd_thr_request	*sd_mhreq;
22027 
22028 	/* Wait for work */
22029 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22030 	if (sd_tr.srq_thr_req_head == NULL) {
22031 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
22032 		    &sd_tr.srq_resv_reclaim_mutex);
22033 	}
22034 
22035 	/* Loop while we have work */
22036 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
22037 		un = ddi_get_soft_state(sd_state,
22038 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
22039 		if (un == NULL) {
22040 			/*
22041 			 * softstate structure is NULL so just
22042 			 * dequeue the request and continue
22043 			 */
22044 			sd_tr.srq_thr_req_head =
22045 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22046 			kmem_free(sd_tr.srq_thr_cur_req,
22047 			    sizeof (struct sd_thr_request));
22048 			continue;
22049 		}
22050 
22051 		/* dequeue the request */
22052 		sd_mhreq = sd_tr.srq_thr_cur_req;
22053 		sd_tr.srq_thr_req_head =
22054 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22055 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22056 
22057 		/*
22058 		 * Reclaim reservation only if SD_RESERVE is still set. There
22059 		 * may have been a call to MHIOCRELEASE before we got here.
22060 		 */
22061 		mutex_enter(SD_MUTEX(un));
22062 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22063 			/*
22064 			 * Note: The SD_LOST_RESERVE flag is cleared before
22065 			 * reclaiming the reservation. If this is done after the
22066 			 * call to sd_reserve_release a reservation loss in the
22067 			 * window between pkt completion of reserve cmd and
22068 			 * mutex_enter below may not be recognized
22069 			 */
22070 			un->un_resvd_status &= ~SD_LOST_RESERVE;
22071 			mutex_exit(SD_MUTEX(un));
22072 
22073 			if (sd_reserve_release(sd_mhreq->dev,
22074 			    SD_RESERVE) == 0) {
22075 				mutex_enter(SD_MUTEX(un));
22076 				un->un_resvd_status |= SD_RESERVE;
22077 				mutex_exit(SD_MUTEX(un));
22078 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22079 				    "sd_resv_reclaim_thread: "
22080 				    "Reservation Recovered\n");
22081 			} else {
22082 				mutex_enter(SD_MUTEX(un));
22083 				un->un_resvd_status |= SD_LOST_RESERVE;
22084 				mutex_exit(SD_MUTEX(un));
22085 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22086 				    "sd_resv_reclaim_thread: Failed "
22087 				    "Reservation Recovery\n");
22088 			}
22089 		} else {
22090 			mutex_exit(SD_MUTEX(un));
22091 		}
22092 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22093 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
22094 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22095 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
22096 		/*
22097 		 * wakeup the destroy thread if anyone is waiting on
22098 		 * us to complete.
22099 		 */
22100 		cv_signal(&sd_tr.srq_inprocess_cv);
22101 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
22102 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
22103 	}
22104 
22105 	/*
22106 	 * cleanup the sd_tr structure now that this thread will not exist
22107 	 */
22108 	ASSERT(sd_tr.srq_thr_req_head == NULL);
22109 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
22110 	sd_tr.srq_resv_reclaim_thread = NULL;
22111 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22112 	thread_exit();
22113 }
22114 
22115 
22116 /*
22117  *    Function: sd_rmv_resv_reclaim_req()
22118  *
22119  * Description: This function removes any pending reservation reclaim requests
22120  *		for the specified device.
22121  *
22122  *   Arguments: dev - the device 'dev_t'
22123  */
22124 
22125 static void
22126 sd_rmv_resv_reclaim_req(dev_t dev)
22127 {
22128 	struct sd_thr_request *sd_mhreq;
22129 	struct sd_thr_request *sd_prev;
22130 
22131 	/* Remove a reservation reclaim request from the list */
22132 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22133 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
22134 		/*
22135 		 * We are attempting to reinstate reservation for
22136 		 * this device. We wait for sd_reserve_release()
22137 		 * to return before we return.
22138 		 */
22139 		cv_wait(&sd_tr.srq_inprocess_cv,
22140 		    &sd_tr.srq_resv_reclaim_mutex);
22141 	} else {
22142 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
22143 		if (sd_mhreq && sd_mhreq->dev == dev) {
22144 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
22145 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22146 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22147 			return;
22148 		}
22149 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
22150 			if (sd_mhreq && sd_mhreq->dev == dev) {
22151 				break;
22152 			}
22153 			sd_prev = sd_mhreq;
22154 		}
22155 		if (sd_mhreq != NULL) {
22156 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
22157 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22158 		}
22159 	}
22160 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22161 }
22162 
22163 
22164 /*
22165  *    Function: sd_mhd_reset_notify_cb()
22166  *
22167  * Description: This is a call back function for scsi_reset_notify. This
22168  *		function updates the softstate reserved status and logs the
22169  *		reset. The driver scsi watch facility callback function
22170  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
22171  *		will reclaim the reservation.
22172  *
22173  *   Arguments: arg  - driver soft state (unit) structure
22174  */
22175 
22176 static void
22177 sd_mhd_reset_notify_cb(caddr_t arg)
22178 {
22179 	struct sd_lun *un = (struct sd_lun *)arg;
22180 
22181 	mutex_enter(SD_MUTEX(un));
22182 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22183 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
22184 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22185 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
22186 	}
22187 	mutex_exit(SD_MUTEX(un));
22188 }
22189 
22190 
22191 /*
22192  *    Function: sd_take_ownership()
22193  *
22194  * Description: This routine implements an algorithm to achieve a stable
22195  *		reservation on disks which don't implement priority reserve,
22196  *		and makes sure that other host lose re-reservation attempts.
22197  *		This algorithm contains of a loop that keeps issuing the RESERVE
22198  *		for some period of time (min_ownership_delay, default 6 seconds)
22199  *		During that loop, it looks to see if there has been a bus device
22200  *		reset or bus reset (both of which cause an existing reservation
22201  *		to be lost). If the reservation is lost issue RESERVE until a
22202  *		period of min_ownership_delay with no resets has gone by, or
22203  *		until max_ownership_delay has expired. This loop ensures that
22204  *		the host really did manage to reserve the device, in spite of
22205  *		resets. The looping for min_ownership_delay (default six
22206  *		seconds) is important to early generation clustering products,
22207  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
22208  *		MHIOCENFAILFAST periodic timer of two seconds. By having
22209  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
22210  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
22211  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
22212  *		have already noticed, via the MHIOCENFAILFAST polling, that it
22213  *		no longer "owns" the disk and will have panicked itself.  Thus,
22214  *		the host issuing the MHIOCTKOWN is assured (with timing
22215  *		dependencies) that by the time it actually starts to use the
22216  *		disk for real work, the old owner is no longer accessing it.
22217  *
22218  *		min_ownership_delay is the minimum amount of time for which the
22219  *		disk must be reserved continuously devoid of resets before the
22220  *		MHIOCTKOWN ioctl will return success.
22221  *
22222  *		max_ownership_delay indicates the amount of time by which the
22223  *		take ownership should succeed or timeout with an error.
22224  *
22225  *   Arguments: dev - the device 'dev_t'
22226  *		*p  - struct containing timing info.
22227  *
22228  * Return Code: 0 for success or error code
22229  */
22230 
22231 static int
22232 sd_take_ownership(dev_t dev, struct mhioctkown *p)
22233 {
22234 	struct sd_lun	*un;
22235 	int		rval;
22236 	int		err;
22237 	int		reservation_count   = 0;
22238 	int		min_ownership_delay =  6000000; /* in usec */
22239 	int		max_ownership_delay = 30000000; /* in usec */
22240 	clock_t		start_time;	/* starting time of this algorithm */
22241 	clock_t		end_time;	/* time limit for giving up */
22242 	clock_t		ownership_time;	/* time limit for stable ownership */
22243 	clock_t		current_time;
22244 	clock_t		previous_current_time;
22245 
22246 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22247 		return (ENXIO);
22248 	}
22249 
22250 	/*
22251 	 * Attempt a device reservation. A priority reservation is requested.
22252 	 */
22253 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
22254 	    != SD_SUCCESS) {
22255 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
22256 		    "sd_take_ownership: return(1)=%d\n", rval);
22257 		return (rval);
22258 	}
22259 
22260 	/* Update the softstate reserved status to indicate the reservation */
22261 	mutex_enter(SD_MUTEX(un));
22262 	un->un_resvd_status |= SD_RESERVE;
22263 	un->un_resvd_status &=
22264 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
22265 	mutex_exit(SD_MUTEX(un));
22266 
22267 	if (p != NULL) {
22268 		if (p->min_ownership_delay != 0) {
22269 			min_ownership_delay = p->min_ownership_delay * 1000;
22270 		}
22271 		if (p->max_ownership_delay != 0) {
22272 			max_ownership_delay = p->max_ownership_delay * 1000;
22273 		}
22274 	}
22275 	SD_INFO(SD_LOG_IOCTL_MHD, un,
22276 	    "sd_take_ownership: min, max delays: %d, %d\n",
22277 	    min_ownership_delay, max_ownership_delay);
22278 
22279 	start_time = ddi_get_lbolt();
22280 	current_time	= start_time;
22281 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
22282 	end_time	= start_time + drv_usectohz(max_ownership_delay);
22283 
22284 	while (current_time - end_time < 0) {
22285 		delay(drv_usectohz(500000));
22286 
22287 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
22288 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
22289 				mutex_enter(SD_MUTEX(un));
22290 				rval = (un->un_resvd_status &
22291 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
22292 				mutex_exit(SD_MUTEX(un));
22293 				break;
22294 			}
22295 		}
22296 		previous_current_time = current_time;
22297 		current_time = ddi_get_lbolt();
22298 		mutex_enter(SD_MUTEX(un));
22299 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
22300 			ownership_time = ddi_get_lbolt() +
22301 			    drv_usectohz(min_ownership_delay);
22302 			reservation_count = 0;
22303 		} else {
22304 			reservation_count++;
22305 		}
22306 		un->un_resvd_status |= SD_RESERVE;
22307 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
22308 		mutex_exit(SD_MUTEX(un));
22309 
22310 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22311 		    "sd_take_ownership: ticks for loop iteration=%ld, "
22312 		    "reservation=%s\n", (current_time - previous_current_time),
22313 		    reservation_count ? "ok" : "reclaimed");
22314 
22315 		if (current_time - ownership_time >= 0 &&
22316 		    reservation_count >= 4) {
22317 			rval = 0; /* Achieved a stable ownership */
22318 			break;
22319 		}
22320 		if (current_time - end_time >= 0) {
22321 			rval = EACCES; /* No ownership in max possible time */
22322 			break;
22323 		}
22324 	}
22325 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
22326 	    "sd_take_ownership: return(2)=%d\n", rval);
22327 	return (rval);
22328 }
22329 
22330 
22331 /*
22332  *    Function: sd_reserve_release()
22333  *
22334  * Description: This function builds and sends scsi RESERVE, RELEASE, and
22335  *		PRIORITY RESERVE commands based on a user specified command type
22336  *
22337  *   Arguments: dev - the device 'dev_t'
22338  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
22339  *		      SD_RESERVE, SD_RELEASE
22340  *
22341  * Return Code: 0 or Error Code
22342  */
22343 
22344 static int
22345 sd_reserve_release(dev_t dev, int cmd)
22346 {
22347 	struct uscsi_cmd	*com = NULL;
22348 	struct sd_lun		*un = NULL;
22349 	char			cdb[CDB_GROUP0];
22350 	int			rval;
22351 
22352 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
22353 	    (cmd == SD_PRIORITY_RESERVE));
22354 
22355 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22356 		return (ENXIO);
22357 	}
22358 
22359 	/* instantiate and initialize the command and cdb */
22360 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
22361 	bzero(cdb, CDB_GROUP0);
22362 	com->uscsi_flags   = USCSI_SILENT;
22363 	com->uscsi_timeout = un->un_reserve_release_time;
22364 	com->uscsi_cdblen  = CDB_GROUP0;
22365 	com->uscsi_cdb	   = cdb;
22366 	if (cmd == SD_RELEASE) {
22367 		cdb[0] = SCMD_RELEASE;
22368 	} else {
22369 		cdb[0] = SCMD_RESERVE;
22370 	}
22371 
22372 	/* Send the command. */
22373 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22374 	    SD_PATH_STANDARD);
22375 
22376 	/*
22377 	 * "break" a reservation that is held by another host, by issuing a
22378 	 * reset if priority reserve is desired, and we could not get the
22379 	 * device.
22380 	 */
22381 	if ((cmd == SD_PRIORITY_RESERVE) &&
22382 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22383 		/*
22384 		 * First try to reset the LUN. If we cannot, then try a target
22385 		 * reset, followed by a bus reset if the target reset fails.
22386 		 */
22387 		int reset_retval = 0;
22388 		if (un->un_f_lun_reset_enabled == TRUE) {
22389 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
22390 		}
22391 		if (reset_retval == 0) {
22392 			/* The LUN reset either failed or was not issued */
22393 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
22394 		}
22395 		if ((reset_retval == 0) &&
22396 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
22397 			rval = EIO;
22398 			kmem_free(com, sizeof (*com));
22399 			return (rval);
22400 		}
22401 
22402 		bzero(com, sizeof (struct uscsi_cmd));
22403 		com->uscsi_flags   = USCSI_SILENT;
22404 		com->uscsi_cdb	   = cdb;
22405 		com->uscsi_cdblen  = CDB_GROUP0;
22406 		com->uscsi_timeout = 5;
22407 
22408 		/*
22409 		 * Reissue the last reserve command, this time without request
22410 		 * sense.  Assume that it is just a regular reserve command.
22411 		 */
22412 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22413 		    SD_PATH_STANDARD);
22414 	}
22415 
22416 	/* Return an error if still getting a reservation conflict. */
22417 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22418 		rval = EACCES;
22419 	}
22420 
22421 	kmem_free(com, sizeof (*com));
22422 	return (rval);
22423 }
22424 
22425 
22426 #define	SD_NDUMP_RETRIES	12
22427 /*
22428  *	System Crash Dump routine
22429  */
22430 
22431 static int
22432 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
22433 {
22434 	int		instance;
22435 	int		partition;
22436 	int		i;
22437 	int		err;
22438 	struct sd_lun	*un;
22439 	struct scsi_pkt *wr_pktp;
22440 	struct buf	*wr_bp;
22441 	struct buf	wr_buf;
22442 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
22443 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
22444 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
22445 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
22446 	size_t		io_start_offset;
22447 	int		doing_rmw = FALSE;
22448 	int		rval;
22449 #if defined(__i386) || defined(__amd64)
22450 	ssize_t dma_resid;
22451 	daddr_t oblkno;
22452 #endif
22453 	diskaddr_t	nblks = 0;
22454 	diskaddr_t	start_block;
22455 
22456 	instance = SDUNIT(dev);
22457 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
22458 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
22459 		return (ENXIO);
22460 	}
22461 
22462 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
22463 
22464 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
22465 
22466 	partition = SDPART(dev);
22467 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
22468 
22469 	/* Validate blocks to dump at against partition size. */
22470 
22471 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
22472 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
22473 
22474 	if ((blkno + nblk) > nblks) {
22475 		SD_TRACE(SD_LOG_DUMP, un,
22476 		    "sddump: dump range larger than partition: "
22477 		    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
22478 		    blkno, nblk, nblks);
22479 		return (EINVAL);
22480 	}
22481 
22482 	mutex_enter(&un->un_pm_mutex);
22483 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
22484 		struct scsi_pkt *start_pktp;
22485 
22486 		mutex_exit(&un->un_pm_mutex);
22487 
22488 		/*
22489 		 * use pm framework to power on HBA 1st
22490 		 */
22491 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
22492 
22493 		/*
22494 		 * Dump no long uses sdpower to power on a device, it's
22495 		 * in-line here so it can be done in polled mode.
22496 		 */
22497 
22498 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
22499 
22500 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
22501 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
22502 
22503 		if (start_pktp == NULL) {
22504 			/* We were not given a SCSI packet, fail. */
22505 			return (EIO);
22506 		}
22507 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
22508 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
22509 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
22510 		start_pktp->pkt_flags = FLAG_NOINTR;
22511 
22512 		mutex_enter(SD_MUTEX(un));
22513 		SD_FILL_SCSI1_LUN(un, start_pktp);
22514 		mutex_exit(SD_MUTEX(un));
22515 		/*
22516 		 * Scsi_poll returns 0 (success) if the command completes and
22517 		 * the status block is STATUS_GOOD.
22518 		 */
22519 		if (sd_scsi_poll(un, start_pktp) != 0) {
22520 			scsi_destroy_pkt(start_pktp);
22521 			return (EIO);
22522 		}
22523 		scsi_destroy_pkt(start_pktp);
22524 		(void) sd_ddi_pm_resume(un);
22525 	} else {
22526 		mutex_exit(&un->un_pm_mutex);
22527 	}
22528 
22529 	mutex_enter(SD_MUTEX(un));
22530 	un->un_throttle = 0;
22531 
22532 	/*
22533 	 * The first time through, reset the specific target device.
22534 	 * However, when cpr calls sddump we know that sd is in a
22535 	 * a good state so no bus reset is required.
22536 	 * Clear sense data via Request Sense cmd.
22537 	 * In sddump we don't care about allow_bus_device_reset anymore
22538 	 */
22539 
22540 	if ((un->un_state != SD_STATE_SUSPENDED) &&
22541 	    (un->un_state != SD_STATE_DUMPING)) {
22542 
22543 		New_state(un, SD_STATE_DUMPING);
22544 
22545 		if (un->un_f_is_fibre == FALSE) {
22546 			mutex_exit(SD_MUTEX(un));
22547 			/*
22548 			 * Attempt a bus reset for parallel scsi.
22549 			 *
22550 			 * Note: A bus reset is required because on some host
22551 			 * systems (i.e. E420R) a bus device reset is
22552 			 * insufficient to reset the state of the target.
22553 			 *
22554 			 * Note: Don't issue the reset for fibre-channel,
22555 			 * because this tends to hang the bus (loop) for
22556 			 * too long while everyone is logging out and in
22557 			 * and the deadman timer for dumping will fire
22558 			 * before the dump is complete.
22559 			 */
22560 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
22561 				mutex_enter(SD_MUTEX(un));
22562 				Restore_state(un);
22563 				mutex_exit(SD_MUTEX(un));
22564 				return (EIO);
22565 			}
22566 
22567 			/* Delay to give the device some recovery time. */
22568 			drv_usecwait(10000);
22569 
22570 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
22571 				SD_INFO(SD_LOG_DUMP, un,
22572 				    "sddump: sd_send_polled_RQS failed\n");
22573 			}
22574 			mutex_enter(SD_MUTEX(un));
22575 		}
22576 	}
22577 
22578 	/*
22579 	 * Convert the partition-relative block number to a
22580 	 * disk physical block number.
22581 	 */
22582 	blkno += start_block;
22583 
22584 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
22585 
22586 
22587 	/*
22588 	 * Check if the device has a non-512 block size.
22589 	 */
22590 	wr_bp = NULL;
22591 	if (NOT_DEVBSIZE(un)) {
22592 		tgt_byte_offset = blkno * un->un_sys_blocksize;
22593 		tgt_byte_count = nblk * un->un_sys_blocksize;
22594 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
22595 		    (tgt_byte_count % un->un_tgt_blocksize)) {
22596 			doing_rmw = TRUE;
22597 			/*
22598 			 * Calculate the block number and number of block
22599 			 * in terms of the media block size.
22600 			 */
22601 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
22602 			tgt_nblk =
22603 			    ((tgt_byte_offset + tgt_byte_count +
22604 			    (un->un_tgt_blocksize - 1)) /
22605 			    un->un_tgt_blocksize) - tgt_blkno;
22606 
22607 			/*
22608 			 * Invoke the routine which is going to do read part
22609 			 * of read-modify-write.
22610 			 * Note that this routine returns a pointer to
22611 			 * a valid bp in wr_bp.
22612 			 */
22613 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
22614 			    &wr_bp);
22615 			if (err) {
22616 				mutex_exit(SD_MUTEX(un));
22617 				return (err);
22618 			}
22619 			/*
22620 			 * Offset is being calculated as -
22621 			 * (original block # * system block size) -
22622 			 * (new block # * target block size)
22623 			 */
22624 			io_start_offset =
22625 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
22626 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
22627 
22628 			ASSERT((io_start_offset >= 0) &&
22629 			    (io_start_offset < un->un_tgt_blocksize));
22630 			/*
22631 			 * Do the modify portion of read modify write.
22632 			 */
22633 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
22634 			    (size_t)nblk * un->un_sys_blocksize);
22635 		} else {
22636 			doing_rmw = FALSE;
22637 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
22638 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
22639 		}
22640 
22641 		/* Convert blkno and nblk to target blocks */
22642 		blkno = tgt_blkno;
22643 		nblk = tgt_nblk;
22644 	} else {
22645 		wr_bp = &wr_buf;
22646 		bzero(wr_bp, sizeof (struct buf));
22647 		wr_bp->b_flags		= B_BUSY;
22648 		wr_bp->b_un.b_addr	= addr;
22649 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
22650 		wr_bp->b_resid		= 0;
22651 	}
22652 
22653 	mutex_exit(SD_MUTEX(un));
22654 
22655 	/*
22656 	 * Obtain a SCSI packet for the write command.
22657 	 * It should be safe to call the allocator here without
22658 	 * worrying about being locked for DVMA mapping because
22659 	 * the address we're passed is already a DVMA mapping
22660 	 *
22661 	 * We are also not going to worry about semaphore ownership
22662 	 * in the dump buffer. Dumping is single threaded at present.
22663 	 */
22664 
22665 	wr_pktp = NULL;
22666 
22667 #if defined(__i386) || defined(__amd64)
22668 	dma_resid = wr_bp->b_bcount;
22669 	oblkno = blkno;
22670 	while (dma_resid != 0) {
22671 #endif
22672 
22673 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
22674 		wr_bp->b_flags &= ~B_ERROR;
22675 
22676 #if defined(__i386) || defined(__amd64)
22677 		blkno = oblkno +
22678 		    ((wr_bp->b_bcount - dma_resid) /
22679 		    un->un_tgt_blocksize);
22680 		nblk = dma_resid / un->un_tgt_blocksize;
22681 
22682 		if (wr_pktp) {
22683 			/* Partial DMA transfers after initial transfer */
22684 			rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
22685 			    blkno, nblk);
22686 		} else {
22687 			/* Initial transfer */
22688 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
22689 			    un->un_pkt_flags, NULL_FUNC, NULL,
22690 			    blkno, nblk);
22691 		}
22692 #else
22693 		rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
22694 		    0, NULL_FUNC, NULL, blkno, nblk);
22695 #endif
22696 
22697 		if (rval == 0) {
22698 			/* We were given a SCSI packet, continue. */
22699 			break;
22700 		}
22701 
22702 		if (i == 0) {
22703 			if (wr_bp->b_flags & B_ERROR) {
22704 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
22705 				    "no resources for dumping; "
22706 				    "error code: 0x%x, retrying",
22707 				    geterror(wr_bp));
22708 			} else {
22709 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
22710 				    "no resources for dumping; retrying");
22711 			}
22712 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
22713 			if (wr_bp->b_flags & B_ERROR) {
22714 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
22715 				    "no resources for dumping; error code: "
22716 				    "0x%x, retrying\n", geterror(wr_bp));
22717 			}
22718 		} else {
22719 			if (wr_bp->b_flags & B_ERROR) {
22720 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
22721 				    "no resources for dumping; "
22722 				    "error code: 0x%x, retries failed, "
22723 				    "giving up.\n", geterror(wr_bp));
22724 			} else {
22725 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
22726 				    "no resources for dumping; "
22727 				    "retries failed, giving up.\n");
22728 			}
22729 			mutex_enter(SD_MUTEX(un));
22730 			Restore_state(un);
22731 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
22732 				mutex_exit(SD_MUTEX(un));
22733 				scsi_free_consistent_buf(wr_bp);
22734 			} else {
22735 				mutex_exit(SD_MUTEX(un));
22736 			}
22737 			return (EIO);
22738 		}
22739 		drv_usecwait(10000);
22740 	}
22741 
22742 #if defined(__i386) || defined(__amd64)
22743 	/*
22744 	 * save the resid from PARTIAL_DMA
22745 	 */
22746 	dma_resid = wr_pktp->pkt_resid;
22747 	if (dma_resid != 0)
22748 		nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
22749 	wr_pktp->pkt_resid = 0;
22750 #endif
22751 
22752 	/* SunBug 1222170 */
22753 	wr_pktp->pkt_flags = FLAG_NOINTR;
22754 
22755 	err = EIO;
22756 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
22757 
22758 		/*
22759 		 * Scsi_poll returns 0 (success) if the command completes and
22760 		 * the status block is STATUS_GOOD.  We should only check
22761 		 * errors if this condition is not true.  Even then we should
22762 		 * send our own request sense packet only if we have a check
22763 		 * condition and auto request sense has not been performed by
22764 		 * the hba.
22765 		 */
22766 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
22767 
22768 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
22769 		    (wr_pktp->pkt_resid == 0)) {
22770 			err = SD_SUCCESS;
22771 			break;
22772 		}
22773 
22774 		/*
22775 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
22776 		 */
22777 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
22778 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
22779 			    "Device is gone\n");
22780 			break;
22781 		}
22782 
22783 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
22784 			SD_INFO(SD_LOG_DUMP, un,
22785 			    "sddump: write failed with CHECK, try # %d\n", i);
22786 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
22787 				(void) sd_send_polled_RQS(un);
22788 			}
22789 
22790 			continue;
22791 		}
22792 
22793 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
22794 			int reset_retval = 0;
22795 
22796 			SD_INFO(SD_LOG_DUMP, un,
22797 			    "sddump: write failed with BUSY, try # %d\n", i);
22798 
22799 			if (un->un_f_lun_reset_enabled == TRUE) {
22800 				reset_retval = scsi_reset(SD_ADDRESS(un),
22801 				    RESET_LUN);
22802 			}
22803 			if (reset_retval == 0) {
22804 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
22805 			}
22806 			(void) sd_send_polled_RQS(un);
22807 
22808 		} else {
22809 			SD_INFO(SD_LOG_DUMP, un,
22810 			    "sddump: write failed with 0x%x, try # %d\n",
22811 			    SD_GET_PKT_STATUS(wr_pktp), i);
22812 			mutex_enter(SD_MUTEX(un));
22813 			sd_reset_target(un, wr_pktp);
22814 			mutex_exit(SD_MUTEX(un));
22815 		}
22816 
22817 		/*
22818 		 * If we are not getting anywhere with lun/target resets,
22819 		 * let's reset the bus.
22820 		 */
22821 		if (i == SD_NDUMP_RETRIES/2) {
22822 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
22823 			(void) sd_send_polled_RQS(un);
22824 		}
22825 
22826 	}
22827 #if defined(__i386) || defined(__amd64)
22828 	}	/* dma_resid */
22829 #endif
22830 
22831 	scsi_destroy_pkt(wr_pktp);
22832 	mutex_enter(SD_MUTEX(un));
22833 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
22834 		mutex_exit(SD_MUTEX(un));
22835 		scsi_free_consistent_buf(wr_bp);
22836 	} else {
22837 		mutex_exit(SD_MUTEX(un));
22838 	}
22839 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
22840 	return (err);
22841 }
22842 
22843 /*
22844  *    Function: sd_scsi_poll()
22845  *
22846  * Description: This is a wrapper for the scsi_poll call.
22847  *
22848  *   Arguments: sd_lun - The unit structure
22849  *              scsi_pkt - The scsi packet being sent to the device.
22850  *
22851  * Return Code: 0 - Command completed successfully with good status
22852  *             -1 - Command failed.  This could indicate a check condition
22853  *                  or other status value requiring recovery action.
22854  *
22855  */
22856 
22857 static int
22858 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
22859 {
22860 	int status;
22861 
22862 	ASSERT(un != NULL);
22863 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22864 	ASSERT(pktp != NULL);
22865 
22866 	status = SD_SUCCESS;
22867 
22868 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
22869 		pktp->pkt_flags |= un->un_tagflags;
22870 		pktp->pkt_flags &= ~FLAG_NODISCON;
22871 	}
22872 
22873 	status = sd_ddi_scsi_poll(pktp);
22874 	/*
22875 	 * Scsi_poll returns 0 (success) if the command completes and the
22876 	 * status block is STATUS_GOOD.  We should only check errors if this
22877 	 * condition is not true.  Even then we should send our own request
22878 	 * sense packet only if we have a check condition and auto
22879 	 * request sense has not been performed by the hba.
22880 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
22881 	 */
22882 	if ((status != SD_SUCCESS) &&
22883 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
22884 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
22885 	    (pktp->pkt_reason != CMD_DEV_GONE))
22886 		(void) sd_send_polled_RQS(un);
22887 
22888 	return (status);
22889 }
22890 
22891 /*
22892  *    Function: sd_send_polled_RQS()
22893  *
22894  * Description: This sends the request sense command to a device.
22895  *
22896  *   Arguments: sd_lun - The unit structure
22897  *
22898  * Return Code: 0 - Command completed successfully with good status
22899  *             -1 - Command failed.
22900  *
22901  */
22902 
22903 static int
22904 sd_send_polled_RQS(struct sd_lun *un)
22905 {
22906 	int	ret_val;
22907 	struct	scsi_pkt	*rqs_pktp;
22908 	struct	buf		*rqs_bp;
22909 
22910 	ASSERT(un != NULL);
22911 	ASSERT(!mutex_owned(SD_MUTEX(un)));
22912 
22913 	ret_val = SD_SUCCESS;
22914 
22915 	rqs_pktp = un->un_rqs_pktp;
22916 	rqs_bp	 = un->un_rqs_bp;
22917 
22918 	mutex_enter(SD_MUTEX(un));
22919 
22920 	if (un->un_sense_isbusy) {
22921 		ret_val = SD_FAILURE;
22922 		mutex_exit(SD_MUTEX(un));
22923 		return (ret_val);
22924 	}
22925 
22926 	/*
22927 	 * If the request sense buffer (and packet) is not in use,
22928 	 * let's set the un_sense_isbusy and send our packet
22929 	 */
22930 	un->un_sense_isbusy 	= 1;
22931 	rqs_pktp->pkt_resid  	= 0;
22932 	rqs_pktp->pkt_reason 	= 0;
22933 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
22934 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
22935 
22936 	mutex_exit(SD_MUTEX(un));
22937 
22938 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
22939 	    " 0x%p\n", rqs_bp->b_un.b_addr);
22940 
22941 	/*
22942 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
22943 	 * axle - it has a call into us!
22944 	 */
22945 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
22946 		SD_INFO(SD_LOG_COMMON, un,
22947 		    "sd_send_polled_RQS: RQS failed\n");
22948 	}
22949 
22950 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
22951 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
22952 
22953 	mutex_enter(SD_MUTEX(un));
22954 	un->un_sense_isbusy = 0;
22955 	mutex_exit(SD_MUTEX(un));
22956 
22957 	return (ret_val);
22958 }
22959 
22960 /*
22961  * Defines needed for localized version of the scsi_poll routine.
22962  */
22963 #define	SD_CSEC		10000			/* usecs */
22964 #define	SD_SEC_TO_CSEC	(1000000/SD_CSEC)
22965 
22966 
22967 /*
22968  *    Function: sd_ddi_scsi_poll()
22969  *
22970  * Description: Localized version of the scsi_poll routine.  The purpose is to
22971  *		send a scsi_pkt to a device as a polled command.  This version
22972  *		is to ensure more robust handling of transport errors.
22973  *		Specifically this routine cures not ready, coming ready
22974  *		transition for power up and reset of sonoma's.  This can take
22975  *		up to 45 seconds for power-on and 20 seconds for reset of a
22976  * 		sonoma lun.
22977  *
22978  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
22979  *
22980  * Return Code: 0 - Command completed successfully with good status
22981  *             -1 - Command failed.
22982  *
22983  */
22984 
22985 static int
22986 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
22987 {
22988 	int busy_count;
22989 	int timeout;
22990 	int rval = SD_FAILURE;
22991 	int savef;
22992 	uint8_t *sensep;
22993 	long savet;
22994 	void (*savec)();
22995 	/*
22996 	 * The following is defined in machdep.c and is used in determining if
22997 	 * the scsi transport system will do polled I/O instead of interrupt
22998 	 * I/O when called from xx_dump().
22999 	 */
23000 	extern int do_polled_io;
23001 
23002 	/*
23003 	 * save old flags in pkt, to restore at end
23004 	 */
23005 	savef = pkt->pkt_flags;
23006 	savec = pkt->pkt_comp;
23007 	savet = pkt->pkt_time;
23008 
23009 	pkt->pkt_flags |= FLAG_NOINTR;
23010 
23011 	/*
23012 	 * XXX there is nothing in the SCSA spec that states that we should not
23013 	 * do a callback for polled cmds; however, removing this will break sd
23014 	 * and probably other target drivers
23015 	 */
23016 	pkt->pkt_comp = NULL;
23017 
23018 	/*
23019 	 * we don't like a polled command without timeout.
23020 	 * 60 seconds seems long enough.
23021 	 */
23022 	if (pkt->pkt_time == 0) {
23023 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
23024 	}
23025 
23026 	/*
23027 	 * Send polled cmd.
23028 	 *
23029 	 * We do some error recovery for various errors.  Tran_busy,
23030 	 * queue full, and non-dispatched commands are retried every 10 msec.
23031 	 * as they are typically transient failures.  Busy status and Not
23032 	 * Ready are retried every second as this status takes a while to
23033 	 * change.  Unit attention is retried for pkt_time (60) times
23034 	 * with no delay.
23035 	 */
23036 	timeout = pkt->pkt_time * SD_SEC_TO_CSEC;
23037 
23038 	for (busy_count = 0; busy_count < timeout; busy_count++) {
23039 		int rc;
23040 		int poll_delay;
23041 
23042 		/*
23043 		 * Initialize pkt status variables.
23044 		 */
23045 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
23046 
23047 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
23048 			if (rc != TRAN_BUSY) {
23049 				/* Transport failed - give up. */
23050 				break;
23051 			} else {
23052 				/* Transport busy - try again. */
23053 				poll_delay = 1 * SD_CSEC; /* 10 msec */
23054 			}
23055 		} else {
23056 			/*
23057 			 * Transport accepted - check pkt status.
23058 			 */
23059 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
23060 			if (pkt->pkt_reason == CMD_CMPLT &&
23061 			    rc == STATUS_CHECK &&
23062 			    pkt->pkt_state & STATE_ARQ_DONE) {
23063 				struct scsi_arq_status *arqstat =
23064 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
23065 
23066 				sensep = (uint8_t *)&arqstat->sts_sensedata;
23067 			} else {
23068 				sensep = NULL;
23069 			}
23070 
23071 			if ((pkt->pkt_reason == CMD_CMPLT) &&
23072 			    (rc == STATUS_GOOD)) {
23073 				/* No error - we're done */
23074 				rval = SD_SUCCESS;
23075 				break;
23076 
23077 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
23078 				/* Lost connection - give up */
23079 				break;
23080 
23081 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
23082 			    (pkt->pkt_state == 0)) {
23083 				/* Pkt not dispatched - try again. */
23084 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
23085 
23086 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23087 			    (rc == STATUS_QFULL)) {
23088 				/* Queue full - try again. */
23089 				poll_delay = 1 * SD_CSEC; /* 10 msec. */
23090 
23091 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23092 			    (rc == STATUS_BUSY)) {
23093 				/* Busy - try again. */
23094 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
23095 				busy_count += (SD_SEC_TO_CSEC - 1);
23096 
23097 			} else if ((sensep != NULL) &&
23098 			    (scsi_sense_key(sensep) ==
23099 			    KEY_UNIT_ATTENTION)) {
23100 				/* Unit Attention - try again */
23101 				busy_count += (SD_SEC_TO_CSEC - 1); /* 1 */
23102 				continue;
23103 
23104 			} else if ((sensep != NULL) &&
23105 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
23106 			    (scsi_sense_asc(sensep) == 0x04) &&
23107 			    (scsi_sense_ascq(sensep) == 0x01)) {
23108 				/* Not ready -> ready - try again. */
23109 				poll_delay = 100 * SD_CSEC; /* 1 sec. */
23110 				busy_count += (SD_SEC_TO_CSEC - 1);
23111 
23112 			} else {
23113 				/* BAD status - give up. */
23114 				break;
23115 			}
23116 		}
23117 
23118 		if ((curthread->t_flag & T_INTR_THREAD) == 0 &&
23119 		    !do_polled_io) {
23120 			delay(drv_usectohz(poll_delay));
23121 		} else {
23122 			/* we busy wait during cpr_dump or interrupt threads */
23123 			drv_usecwait(poll_delay);
23124 		}
23125 	}
23126 
23127 	pkt->pkt_flags = savef;
23128 	pkt->pkt_comp = savec;
23129 	pkt->pkt_time = savet;
23130 	return (rval);
23131 }
23132 
23133 
23134 /*
23135  *    Function: sd_persistent_reservation_in_read_keys
23136  *
23137  * Description: This routine is the driver entry point for handling CD-ROM
23138  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
23139  *		by sending the SCSI-3 PRIN commands to the device.
23140  *		Processes the read keys command response by copying the
23141  *		reservation key information into the user provided buffer.
23142  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
23143  *
23144  *   Arguments: un   -  Pointer to soft state struct for the target.
23145  *		usrp -	user provided pointer to multihost Persistent In Read
23146  *			Keys structure (mhioc_inkeys_t)
23147  *		flag -	this argument is a pass through to ddi_copyxxx()
23148  *			directly from the mode argument of ioctl().
23149  *
23150  * Return Code: 0   - Success
23151  *		EACCES
23152  *		ENOTSUP
23153  *		errno return code from sd_send_scsi_cmd()
23154  *
23155  *     Context: Can sleep. Does not return until command is completed.
23156  */
23157 
23158 static int
23159 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
23160     mhioc_inkeys_t *usrp, int flag)
23161 {
23162 #ifdef _MULTI_DATAMODEL
23163 	struct mhioc_key_list32	li32;
23164 #endif
23165 	sd_prin_readkeys_t	*in;
23166 	mhioc_inkeys_t		*ptr;
23167 	mhioc_key_list_t	li;
23168 	uchar_t			*data_bufp;
23169 	int 			data_len;
23170 	int			rval;
23171 	size_t			copysz;
23172 
23173 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
23174 		return (EINVAL);
23175 	}
23176 	bzero(&li, sizeof (mhioc_key_list_t));
23177 
23178 	/*
23179 	 * Get the listsize from user
23180 	 */
23181 #ifdef _MULTI_DATAMODEL
23182 
23183 	switch (ddi_model_convert_from(flag & FMODELS)) {
23184 	case DDI_MODEL_ILP32:
23185 		copysz = sizeof (struct mhioc_key_list32);
23186 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
23187 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23188 			    "sd_persistent_reservation_in_read_keys: "
23189 			    "failed ddi_copyin: mhioc_key_list32_t\n");
23190 			rval = EFAULT;
23191 			goto done;
23192 		}
23193 		li.listsize = li32.listsize;
23194 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
23195 		break;
23196 
23197 	case DDI_MODEL_NONE:
23198 		copysz = sizeof (mhioc_key_list_t);
23199 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23200 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23201 			    "sd_persistent_reservation_in_read_keys: "
23202 			    "failed ddi_copyin: mhioc_key_list_t\n");
23203 			rval = EFAULT;
23204 			goto done;
23205 		}
23206 		break;
23207 	}
23208 
23209 #else /* ! _MULTI_DATAMODEL */
23210 	copysz = sizeof (mhioc_key_list_t);
23211 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23212 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23213 		    "sd_persistent_reservation_in_read_keys: "
23214 		    "failed ddi_copyin: mhioc_key_list_t\n");
23215 		rval = EFAULT;
23216 		goto done;
23217 	}
23218 #endif
23219 
23220 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
23221 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
23222 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23223 
23224 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS,
23225 	    data_len, data_bufp)) != 0) {
23226 		goto done;
23227 	}
23228 	in = (sd_prin_readkeys_t *)data_bufp;
23229 	ptr->generation = BE_32(in->generation);
23230 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
23231 
23232 	/*
23233 	 * Return the min(listsize, listlen) keys
23234 	 */
23235 #ifdef _MULTI_DATAMODEL
23236 
23237 	switch (ddi_model_convert_from(flag & FMODELS)) {
23238 	case DDI_MODEL_ILP32:
23239 		li32.listlen = li.listlen;
23240 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
23241 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23242 			    "sd_persistent_reservation_in_read_keys: "
23243 			    "failed ddi_copyout: mhioc_key_list32_t\n");
23244 			rval = EFAULT;
23245 			goto done;
23246 		}
23247 		break;
23248 
23249 	case DDI_MODEL_NONE:
23250 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23251 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23252 			    "sd_persistent_reservation_in_read_keys: "
23253 			    "failed ddi_copyout: mhioc_key_list_t\n");
23254 			rval = EFAULT;
23255 			goto done;
23256 		}
23257 		break;
23258 	}
23259 
23260 #else /* ! _MULTI_DATAMODEL */
23261 
23262 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23263 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23264 		    "sd_persistent_reservation_in_read_keys: "
23265 		    "failed ddi_copyout: mhioc_key_list_t\n");
23266 		rval = EFAULT;
23267 		goto done;
23268 	}
23269 
23270 #endif /* _MULTI_DATAMODEL */
23271 
23272 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
23273 	    li.listsize * MHIOC_RESV_KEY_SIZE);
23274 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
23275 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23276 		    "sd_persistent_reservation_in_read_keys: "
23277 		    "failed ddi_copyout: keylist\n");
23278 		rval = EFAULT;
23279 	}
23280 done:
23281 	kmem_free(data_bufp, data_len);
23282 	return (rval);
23283 }
23284 
23285 
23286 /*
23287  *    Function: sd_persistent_reservation_in_read_resv
23288  *
23289  * Description: This routine is the driver entry point for handling CD-ROM
23290  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
23291  *		by sending the SCSI-3 PRIN commands to the device.
23292  *		Process the read persistent reservations command response by
23293  *		copying the reservation information into the user provided
23294  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
23295  *
23296  *   Arguments: un   -  Pointer to soft state struct for the target.
23297  *		usrp -	user provided pointer to multihost Persistent In Read
23298  *			Keys structure (mhioc_inkeys_t)
23299  *		flag -	this argument is a pass through to ddi_copyxxx()
23300  *			directly from the mode argument of ioctl().
23301  *
23302  * Return Code: 0   - Success
23303  *		EACCES
23304  *		ENOTSUP
23305  *		errno return code from sd_send_scsi_cmd()
23306  *
23307  *     Context: Can sleep. Does not return until command is completed.
23308  */
23309 
23310 static int
23311 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
23312     mhioc_inresvs_t *usrp, int flag)
23313 {
23314 #ifdef _MULTI_DATAMODEL
23315 	struct mhioc_resv_desc_list32 resvlist32;
23316 #endif
23317 	sd_prin_readresv_t	*in;
23318 	mhioc_inresvs_t		*ptr;
23319 	sd_readresv_desc_t	*readresv_ptr;
23320 	mhioc_resv_desc_list_t	resvlist;
23321 	mhioc_resv_desc_t 	resvdesc;
23322 	uchar_t			*data_bufp;
23323 	int 			data_len;
23324 	int			rval;
23325 	int			i;
23326 	size_t			copysz;
23327 	mhioc_resv_desc_t	*bufp;
23328 
23329 	if ((ptr = usrp) == NULL) {
23330 		return (EINVAL);
23331 	}
23332 
23333 	/*
23334 	 * Get the listsize from user
23335 	 */
23336 #ifdef _MULTI_DATAMODEL
23337 	switch (ddi_model_convert_from(flag & FMODELS)) {
23338 	case DDI_MODEL_ILP32:
23339 		copysz = sizeof (struct mhioc_resv_desc_list32);
23340 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
23341 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23342 			    "sd_persistent_reservation_in_read_resv: "
23343 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23344 			rval = EFAULT;
23345 			goto done;
23346 		}
23347 		resvlist.listsize = resvlist32.listsize;
23348 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
23349 		break;
23350 
23351 	case DDI_MODEL_NONE:
23352 		copysz = sizeof (mhioc_resv_desc_list_t);
23353 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23354 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23355 			    "sd_persistent_reservation_in_read_resv: "
23356 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23357 			rval = EFAULT;
23358 			goto done;
23359 		}
23360 		break;
23361 	}
23362 #else /* ! _MULTI_DATAMODEL */
23363 	copysz = sizeof (mhioc_resv_desc_list_t);
23364 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23365 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23366 		    "sd_persistent_reservation_in_read_resv: "
23367 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23368 		rval = EFAULT;
23369 		goto done;
23370 	}
23371 #endif /* ! _MULTI_DATAMODEL */
23372 
23373 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
23374 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
23375 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23376 
23377 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_RESV,
23378 	    data_len, data_bufp)) != 0) {
23379 		goto done;
23380 	}
23381 	in = (sd_prin_readresv_t *)data_bufp;
23382 	ptr->generation = BE_32(in->generation);
23383 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
23384 
23385 	/*
23386 	 * Return the min(listsize, listlen( keys
23387 	 */
23388 #ifdef _MULTI_DATAMODEL
23389 
23390 	switch (ddi_model_convert_from(flag & FMODELS)) {
23391 	case DDI_MODEL_ILP32:
23392 		resvlist32.listlen = resvlist.listlen;
23393 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
23394 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23395 			    "sd_persistent_reservation_in_read_resv: "
23396 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23397 			rval = EFAULT;
23398 			goto done;
23399 		}
23400 		break;
23401 
23402 	case DDI_MODEL_NONE:
23403 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
23404 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23405 			    "sd_persistent_reservation_in_read_resv: "
23406 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23407 			rval = EFAULT;
23408 			goto done;
23409 		}
23410 		break;
23411 	}
23412 
23413 #else /* ! _MULTI_DATAMODEL */
23414 
23415 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
23416 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23417 		    "sd_persistent_reservation_in_read_resv: "
23418 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23419 		rval = EFAULT;
23420 		goto done;
23421 	}
23422 
23423 #endif /* ! _MULTI_DATAMODEL */
23424 
23425 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
23426 	bufp = resvlist.list;
23427 	copysz = sizeof (mhioc_resv_desc_t);
23428 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
23429 	    i++, readresv_ptr++, bufp++) {
23430 
23431 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
23432 		    MHIOC_RESV_KEY_SIZE);
23433 		resvdesc.type  = readresv_ptr->type;
23434 		resvdesc.scope = readresv_ptr->scope;
23435 		resvdesc.scope_specific_addr =
23436 		    BE_32(readresv_ptr->scope_specific_addr);
23437 
23438 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
23439 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23440 			    "sd_persistent_reservation_in_read_resv: "
23441 			    "failed ddi_copyout: resvlist\n");
23442 			rval = EFAULT;
23443 			goto done;
23444 		}
23445 	}
23446 done:
23447 	kmem_free(data_bufp, data_len);
23448 	return (rval);
23449 }
23450 
23451 
23452 /*
23453  *    Function: sr_change_blkmode()
23454  *
23455  * Description: This routine is the driver entry point for handling CD-ROM
23456  *		block mode ioctl requests. Support for returning and changing
23457  *		the current block size in use by the device is implemented. The
23458  *		LBA size is changed via a MODE SELECT Block Descriptor.
23459  *
23460  *		This routine issues a mode sense with an allocation length of
23461  *		12 bytes for the mode page header and a single block descriptor.
23462  *
23463  *   Arguments: dev - the device 'dev_t'
23464  *		cmd - the request type; one of CDROMGBLKMODE (get) or
23465  *		      CDROMSBLKMODE (set)
23466  *		data - current block size or requested block size
23467  *		flag - this argument is a pass through to ddi_copyxxx() directly
23468  *		       from the mode argument of ioctl().
23469  *
23470  * Return Code: the code returned by sd_send_scsi_cmd()
23471  *		EINVAL if invalid arguments are provided
23472  *		EFAULT if ddi_copyxxx() fails
23473  *		ENXIO if fail ddi_get_soft_state
23474  *		EIO if invalid mode sense block descriptor length
23475  *
23476  */
23477 
23478 static int
23479 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
23480 {
23481 	struct sd_lun			*un = NULL;
23482 	struct mode_header		*sense_mhp, *select_mhp;
23483 	struct block_descriptor		*sense_desc, *select_desc;
23484 	int				current_bsize;
23485 	int				rval = EINVAL;
23486 	uchar_t				*sense = NULL;
23487 	uchar_t				*select = NULL;
23488 
23489 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
23490 
23491 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23492 		return (ENXIO);
23493 	}
23494 
23495 	/*
23496 	 * The block length is changed via the Mode Select block descriptor, the
23497 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
23498 	 * required as part of this routine. Therefore the mode sense allocation
23499 	 * length is specified to be the length of a mode page header and a
23500 	 * block descriptor.
23501 	 */
23502 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
23503 
23504 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
23505 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD)) != 0) {
23506 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23507 		    "sr_change_blkmode: Mode Sense Failed\n");
23508 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23509 		return (rval);
23510 	}
23511 
23512 	/* Check the block descriptor len to handle only 1 block descriptor */
23513 	sense_mhp = (struct mode_header *)sense;
23514 	if ((sense_mhp->bdesc_length == 0) ||
23515 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
23516 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23517 		    "sr_change_blkmode: Mode Sense returned invalid block"
23518 		    " descriptor length\n");
23519 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23520 		return (EIO);
23521 	}
23522 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
23523 	current_bsize = ((sense_desc->blksize_hi << 16) |
23524 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
23525 
23526 	/* Process command */
23527 	switch (cmd) {
23528 	case CDROMGBLKMODE:
23529 		/* Return the block size obtained during the mode sense */
23530 		if (ddi_copyout(&current_bsize, (void *)data,
23531 		    sizeof (int), flag) != 0)
23532 			rval = EFAULT;
23533 		break;
23534 	case CDROMSBLKMODE:
23535 		/* Validate the requested block size */
23536 		switch (data) {
23537 		case CDROM_BLK_512:
23538 		case CDROM_BLK_1024:
23539 		case CDROM_BLK_2048:
23540 		case CDROM_BLK_2056:
23541 		case CDROM_BLK_2336:
23542 		case CDROM_BLK_2340:
23543 		case CDROM_BLK_2352:
23544 		case CDROM_BLK_2368:
23545 		case CDROM_BLK_2448:
23546 		case CDROM_BLK_2646:
23547 		case CDROM_BLK_2647:
23548 			break;
23549 		default:
23550 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23551 			    "sr_change_blkmode: "
23552 			    "Block Size '%ld' Not Supported\n", data);
23553 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23554 			return (EINVAL);
23555 		}
23556 
23557 		/*
23558 		 * The current block size matches the requested block size so
23559 		 * there is no need to send the mode select to change the size
23560 		 */
23561 		if (current_bsize == data) {
23562 			break;
23563 		}
23564 
23565 		/* Build the select data for the requested block size */
23566 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
23567 		select_mhp = (struct mode_header *)select;
23568 		select_desc =
23569 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
23570 		/*
23571 		 * The LBA size is changed via the block descriptor, so the
23572 		 * descriptor is built according to the user data
23573 		 */
23574 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
23575 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
23576 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
23577 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
23578 
23579 		/* Send the mode select for the requested block size */
23580 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
23581 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
23582 		    SD_PATH_STANDARD)) != 0) {
23583 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23584 			    "sr_change_blkmode: Mode Select Failed\n");
23585 			/*
23586 			 * The mode select failed for the requested block size,
23587 			 * so reset the data for the original block size and
23588 			 * send it to the target. The error is indicated by the
23589 			 * return value for the failed mode select.
23590 			 */
23591 			select_desc->blksize_hi  = sense_desc->blksize_hi;
23592 			select_desc->blksize_mid = sense_desc->blksize_mid;
23593 			select_desc->blksize_lo  = sense_desc->blksize_lo;
23594 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
23595 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
23596 			    SD_PATH_STANDARD);
23597 		} else {
23598 			ASSERT(!mutex_owned(SD_MUTEX(un)));
23599 			mutex_enter(SD_MUTEX(un));
23600 			sd_update_block_info(un, (uint32_t)data, 0);
23601 			mutex_exit(SD_MUTEX(un));
23602 		}
23603 		break;
23604 	default:
23605 		/* should not reach here, but check anyway */
23606 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23607 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
23608 		rval = EINVAL;
23609 		break;
23610 	}
23611 
23612 	if (select) {
23613 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
23614 	}
23615 	if (sense) {
23616 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
23617 	}
23618 	return (rval);
23619 }
23620 
23621 
23622 /*
23623  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
23624  * implement driver support for getting and setting the CD speed. The command
23625  * set used will be based on the device type. If the device has not been
23626  * identified as MMC the Toshiba vendor specific mode page will be used. If
23627  * the device is MMC but does not support the Real Time Streaming feature
23628  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
23629  * be used to read the speed.
23630  */
23631 
23632 /*
23633  *    Function: sr_change_speed()
23634  *
23635  * Description: This routine is the driver entry point for handling CD-ROM
23636  *		drive speed ioctl requests for devices supporting the Toshiba
23637  *		vendor specific drive speed mode page. Support for returning
23638  *		and changing the current drive speed in use by the device is
23639  *		implemented.
23640  *
23641  *   Arguments: dev - the device 'dev_t'
23642  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
23643  *		      CDROMSDRVSPEED (set)
23644  *		data - current drive speed or requested drive speed
23645  *		flag - this argument is a pass through to ddi_copyxxx() directly
23646  *		       from the mode argument of ioctl().
23647  *
23648  * Return Code: the code returned by sd_send_scsi_cmd()
23649  *		EINVAL if invalid arguments are provided
23650  *		EFAULT if ddi_copyxxx() fails
23651  *		ENXIO if fail ddi_get_soft_state
23652  *		EIO if invalid mode sense block descriptor length
23653  */
23654 
23655 static int
23656 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
23657 {
23658 	struct sd_lun			*un = NULL;
23659 	struct mode_header		*sense_mhp, *select_mhp;
23660 	struct mode_speed		*sense_page, *select_page;
23661 	int				current_speed;
23662 	int				rval = EINVAL;
23663 	int				bd_len;
23664 	uchar_t				*sense = NULL;
23665 	uchar_t				*select = NULL;
23666 
23667 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
23668 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23669 		return (ENXIO);
23670 	}
23671 
23672 	/*
23673 	 * Note: The drive speed is being modified here according to a Toshiba
23674 	 * vendor specific mode page (0x31).
23675 	 */
23676 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
23677 
23678 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
23679 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
23680 	    SD_PATH_STANDARD)) != 0) {
23681 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23682 		    "sr_change_speed: Mode Sense Failed\n");
23683 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
23684 		return (rval);
23685 	}
23686 	sense_mhp  = (struct mode_header *)sense;
23687 
23688 	/* Check the block descriptor len to handle only 1 block descriptor */
23689 	bd_len = sense_mhp->bdesc_length;
23690 	if (bd_len > MODE_BLK_DESC_LENGTH) {
23691 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23692 		    "sr_change_speed: Mode Sense returned invalid block "
23693 		    "descriptor length\n");
23694 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
23695 		return (EIO);
23696 	}
23697 
23698 	sense_page = (struct mode_speed *)
23699 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
23700 	current_speed = sense_page->speed;
23701 
23702 	/* Process command */
23703 	switch (cmd) {
23704 	case CDROMGDRVSPEED:
23705 		/* Return the drive speed obtained during the mode sense */
23706 		if (current_speed == 0x2) {
23707 			current_speed = CDROM_TWELVE_SPEED;
23708 		}
23709 		if (ddi_copyout(&current_speed, (void *)data,
23710 		    sizeof (int), flag) != 0) {
23711 			rval = EFAULT;
23712 		}
23713 		break;
23714 	case CDROMSDRVSPEED:
23715 		/* Validate the requested drive speed */
23716 		switch ((uchar_t)data) {
23717 		case CDROM_TWELVE_SPEED:
23718 			data = 0x2;
23719 			/*FALLTHROUGH*/
23720 		case CDROM_NORMAL_SPEED:
23721 		case CDROM_DOUBLE_SPEED:
23722 		case CDROM_QUAD_SPEED:
23723 		case CDROM_MAXIMUM_SPEED:
23724 			break;
23725 		default:
23726 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23727 			    "sr_change_speed: "
23728 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
23729 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
23730 			return (EINVAL);
23731 		}
23732 
23733 		/*
23734 		 * The current drive speed matches the requested drive speed so
23735 		 * there is no need to send the mode select to change the speed
23736 		 */
23737 		if (current_speed == data) {
23738 			break;
23739 		}
23740 
23741 		/* Build the select data for the requested drive speed */
23742 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
23743 		select_mhp = (struct mode_header *)select;
23744 		select_mhp->bdesc_length = 0;
23745 		select_page =
23746 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
23747 		select_page =
23748 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
23749 		select_page->mode_page.code = CDROM_MODE_SPEED;
23750 		select_page->mode_page.length = 2;
23751 		select_page->speed = (uchar_t)data;
23752 
23753 		/* Send the mode select for the requested block size */
23754 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
23755 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
23756 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
23757 			/*
23758 			 * The mode select failed for the requested drive speed,
23759 			 * so reset the data for the original drive speed and
23760 			 * send it to the target. The error is indicated by the
23761 			 * return value for the failed mode select.
23762 			 */
23763 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23764 			    "sr_drive_speed: Mode Select Failed\n");
23765 			select_page->speed = sense_page->speed;
23766 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
23767 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
23768 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
23769 		}
23770 		break;
23771 	default:
23772 		/* should not reach here, but check anyway */
23773 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23774 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
23775 		rval = EINVAL;
23776 		break;
23777 	}
23778 
23779 	if (select) {
23780 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
23781 	}
23782 	if (sense) {
23783 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
23784 	}
23785 
23786 	return (rval);
23787 }
23788 
23789 
23790 /*
23791  *    Function: sr_atapi_change_speed()
23792  *
23793  * Description: This routine is the driver entry point for handling CD-ROM
23794  *		drive speed ioctl requests for MMC devices that do not support
23795  *		the Real Time Streaming feature (0x107).
23796  *
23797  *		Note: This routine will use the SET SPEED command which may not
23798  *		be supported by all devices.
23799  *
23800  *   Arguments: dev- the device 'dev_t'
23801  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
23802  *		     CDROMSDRVSPEED (set)
23803  *		data- current drive speed or requested drive speed
23804  *		flag- this argument is a pass through to ddi_copyxxx() directly
23805  *		      from the mode argument of ioctl().
23806  *
23807  * Return Code: the code returned by sd_send_scsi_cmd()
23808  *		EINVAL if invalid arguments are provided
23809  *		EFAULT if ddi_copyxxx() fails
23810  *		ENXIO if fail ddi_get_soft_state
23811  *		EIO if invalid mode sense block descriptor length
23812  */
23813 
23814 static int
23815 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
23816 {
23817 	struct sd_lun			*un;
23818 	struct uscsi_cmd		*com = NULL;
23819 	struct mode_header_grp2		*sense_mhp;
23820 	uchar_t				*sense_page;
23821 	uchar_t				*sense = NULL;
23822 	char				cdb[CDB_GROUP5];
23823 	int				bd_len;
23824 	int				current_speed = 0;
23825 	int				max_speed = 0;
23826 	int				rval;
23827 
23828 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
23829 
23830 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23831 		return (ENXIO);
23832 	}
23833 
23834 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
23835 
23836 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
23837 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
23838 	    SD_PATH_STANDARD)) != 0) {
23839 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23840 		    "sr_atapi_change_speed: Mode Sense Failed\n");
23841 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
23842 		return (rval);
23843 	}
23844 
23845 	/* Check the block descriptor len to handle only 1 block descriptor */
23846 	sense_mhp = (struct mode_header_grp2 *)sense;
23847 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
23848 	if (bd_len > MODE_BLK_DESC_LENGTH) {
23849 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23850 		    "sr_atapi_change_speed: Mode Sense returned invalid "
23851 		    "block descriptor length\n");
23852 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
23853 		return (EIO);
23854 	}
23855 
23856 	/* Calculate the current and maximum drive speeds */
23857 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
23858 	current_speed = (sense_page[14] << 8) | sense_page[15];
23859 	max_speed = (sense_page[8] << 8) | sense_page[9];
23860 
23861 	/* Process the command */
23862 	switch (cmd) {
23863 	case CDROMGDRVSPEED:
23864 		current_speed /= SD_SPEED_1X;
23865 		if (ddi_copyout(&current_speed, (void *)data,
23866 		    sizeof (int), flag) != 0)
23867 			rval = EFAULT;
23868 		break;
23869 	case CDROMSDRVSPEED:
23870 		/* Convert the speed code to KB/sec */
23871 		switch ((uchar_t)data) {
23872 		case CDROM_NORMAL_SPEED:
23873 			current_speed = SD_SPEED_1X;
23874 			break;
23875 		case CDROM_DOUBLE_SPEED:
23876 			current_speed = 2 * SD_SPEED_1X;
23877 			break;
23878 		case CDROM_QUAD_SPEED:
23879 			current_speed = 4 * SD_SPEED_1X;
23880 			break;
23881 		case CDROM_TWELVE_SPEED:
23882 			current_speed = 12 * SD_SPEED_1X;
23883 			break;
23884 		case CDROM_MAXIMUM_SPEED:
23885 			current_speed = 0xffff;
23886 			break;
23887 		default:
23888 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23889 			    "sr_atapi_change_speed: invalid drive speed %d\n",
23890 			    (uchar_t)data);
23891 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
23892 			return (EINVAL);
23893 		}
23894 
23895 		/* Check the request against the drive's max speed. */
23896 		if (current_speed != 0xffff) {
23897 			if (current_speed > max_speed) {
23898 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
23899 				return (EINVAL);
23900 			}
23901 		}
23902 
23903 		/*
23904 		 * Build and send the SET SPEED command
23905 		 *
23906 		 * Note: The SET SPEED (0xBB) command used in this routine is
23907 		 * obsolete per the SCSI MMC spec but still supported in the
23908 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
23909 		 * therefore the command is still implemented in this routine.
23910 		 */
23911 		bzero(cdb, sizeof (cdb));
23912 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
23913 		cdb[2] = (uchar_t)(current_speed >> 8);
23914 		cdb[3] = (uchar_t)current_speed;
23915 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
23916 		com->uscsi_cdb	   = (caddr_t)cdb;
23917 		com->uscsi_cdblen  = CDB_GROUP5;
23918 		com->uscsi_bufaddr = NULL;
23919 		com->uscsi_buflen  = 0;
23920 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
23921 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
23922 		break;
23923 	default:
23924 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23925 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
23926 		rval = EINVAL;
23927 	}
23928 
23929 	if (sense) {
23930 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
23931 	}
23932 	if (com) {
23933 		kmem_free(com, sizeof (*com));
23934 	}
23935 	return (rval);
23936 }
23937 
23938 
23939 /*
23940  *    Function: sr_pause_resume()
23941  *
23942  * Description: This routine is the driver entry point for handling CD-ROM
23943  *		pause/resume ioctl requests. This only affects the audio play
23944  *		operation.
23945  *
23946  *   Arguments: dev - the device 'dev_t'
23947  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
23948  *		      for setting the resume bit of the cdb.
23949  *
23950  * Return Code: the code returned by sd_send_scsi_cmd()
23951  *		EINVAL if invalid mode specified
23952  *
23953  */
23954 
23955 static int
23956 sr_pause_resume(dev_t dev, int cmd)
23957 {
23958 	struct sd_lun		*un;
23959 	struct uscsi_cmd	*com;
23960 	char			cdb[CDB_GROUP1];
23961 	int			rval;
23962 
23963 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
23964 		return (ENXIO);
23965 	}
23966 
23967 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
23968 	bzero(cdb, CDB_GROUP1);
23969 	cdb[0] = SCMD_PAUSE_RESUME;
23970 	switch (cmd) {
23971 	case CDROMRESUME:
23972 		cdb[8] = 1;
23973 		break;
23974 	case CDROMPAUSE:
23975 		cdb[8] = 0;
23976 		break;
23977 	default:
23978 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
23979 		    " Command '%x' Not Supported\n", cmd);
23980 		rval = EINVAL;
23981 		goto done;
23982 	}
23983 
23984 	com->uscsi_cdb    = cdb;
23985 	com->uscsi_cdblen = CDB_GROUP1;
23986 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
23987 
23988 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
23989 	    SD_PATH_STANDARD);
23990 
23991 done:
23992 	kmem_free(com, sizeof (*com));
23993 	return (rval);
23994 }
23995 
23996 
23997 /*
23998  *    Function: sr_play_msf()
23999  *
24000  * Description: This routine is the driver entry point for handling CD-ROM
24001  *		ioctl requests to output the audio signals at the specified
24002  *		starting address and continue the audio play until the specified
24003  *		ending address (CDROMPLAYMSF) The address is in Minute Second
24004  *		Frame (MSF) format.
24005  *
24006  *   Arguments: dev	- the device 'dev_t'
24007  *		data	- pointer to user provided audio msf structure,
24008  *		          specifying start/end addresses.
24009  *		flag	- this argument is a pass through to ddi_copyxxx()
24010  *		          directly from the mode argument of ioctl().
24011  *
24012  * Return Code: the code returned by sd_send_scsi_cmd()
24013  *		EFAULT if ddi_copyxxx() fails
24014  *		ENXIO if fail ddi_get_soft_state
24015  *		EINVAL if data pointer is NULL
24016  */
24017 
24018 static int
24019 sr_play_msf(dev_t dev, caddr_t data, int flag)
24020 {
24021 	struct sd_lun		*un;
24022 	struct uscsi_cmd	*com;
24023 	struct cdrom_msf	msf_struct;
24024 	struct cdrom_msf	*msf = &msf_struct;
24025 	char			cdb[CDB_GROUP1];
24026 	int			rval;
24027 
24028 	if (data == NULL) {
24029 		return (EINVAL);
24030 	}
24031 
24032 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24033 		return (ENXIO);
24034 	}
24035 
24036 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
24037 		return (EFAULT);
24038 	}
24039 
24040 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24041 	bzero(cdb, CDB_GROUP1);
24042 	cdb[0] = SCMD_PLAYAUDIO_MSF;
24043 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
24044 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
24045 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
24046 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
24047 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
24048 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
24049 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
24050 	} else {
24051 		cdb[3] = msf->cdmsf_min0;
24052 		cdb[4] = msf->cdmsf_sec0;
24053 		cdb[5] = msf->cdmsf_frame0;
24054 		cdb[6] = msf->cdmsf_min1;
24055 		cdb[7] = msf->cdmsf_sec1;
24056 		cdb[8] = msf->cdmsf_frame1;
24057 	}
24058 	com->uscsi_cdb    = cdb;
24059 	com->uscsi_cdblen = CDB_GROUP1;
24060 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24061 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24062 	    SD_PATH_STANDARD);
24063 	kmem_free(com, sizeof (*com));
24064 	return (rval);
24065 }
24066 
24067 
24068 /*
24069  *    Function: sr_play_trkind()
24070  *
24071  * Description: This routine is the driver entry point for handling CD-ROM
24072  *		ioctl requests to output the audio signals at the specified
24073  *		starting address and continue the audio play until the specified
24074  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
24075  *		format.
24076  *
24077  *   Arguments: dev	- the device 'dev_t'
24078  *		data	- pointer to user provided audio track/index structure,
24079  *		          specifying start/end addresses.
24080  *		flag	- this argument is a pass through to ddi_copyxxx()
24081  *		          directly from the mode argument of ioctl().
24082  *
24083  * Return Code: the code returned by sd_send_scsi_cmd()
24084  *		EFAULT if ddi_copyxxx() fails
24085  *		ENXIO if fail ddi_get_soft_state
24086  *		EINVAL if data pointer is NULL
24087  */
24088 
24089 static int
24090 sr_play_trkind(dev_t dev, caddr_t data, int flag)
24091 {
24092 	struct cdrom_ti		ti_struct;
24093 	struct cdrom_ti		*ti = &ti_struct;
24094 	struct uscsi_cmd	*com = NULL;
24095 	char			cdb[CDB_GROUP1];
24096 	int			rval;
24097 
24098 	if (data == NULL) {
24099 		return (EINVAL);
24100 	}
24101 
24102 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
24103 		return (EFAULT);
24104 	}
24105 
24106 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24107 	bzero(cdb, CDB_GROUP1);
24108 	cdb[0] = SCMD_PLAYAUDIO_TI;
24109 	cdb[4] = ti->cdti_trk0;
24110 	cdb[5] = ti->cdti_ind0;
24111 	cdb[7] = ti->cdti_trk1;
24112 	cdb[8] = ti->cdti_ind1;
24113 	com->uscsi_cdb    = cdb;
24114 	com->uscsi_cdblen = CDB_GROUP1;
24115 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24116 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24117 	    SD_PATH_STANDARD);
24118 	kmem_free(com, sizeof (*com));
24119 	return (rval);
24120 }
24121 
24122 
24123 /*
24124  *    Function: sr_read_all_subcodes()
24125  *
24126  * Description: This routine is the driver entry point for handling CD-ROM
24127  *		ioctl requests to return raw subcode data while the target is
24128  *		playing audio (CDROMSUBCODE).
24129  *
24130  *   Arguments: dev	- the device 'dev_t'
24131  *		data	- pointer to user provided cdrom subcode structure,
24132  *		          specifying the transfer length and address.
24133  *		flag	- this argument is a pass through to ddi_copyxxx()
24134  *		          directly from the mode argument of ioctl().
24135  *
24136  * Return Code: the code returned by sd_send_scsi_cmd()
24137  *		EFAULT if ddi_copyxxx() fails
24138  *		ENXIO if fail ddi_get_soft_state
24139  *		EINVAL if data pointer is NULL
24140  */
24141 
24142 static int
24143 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
24144 {
24145 	struct sd_lun		*un = NULL;
24146 	struct uscsi_cmd	*com = NULL;
24147 	struct cdrom_subcode	*subcode = NULL;
24148 	int			rval;
24149 	size_t			buflen;
24150 	char			cdb[CDB_GROUP5];
24151 
24152 #ifdef _MULTI_DATAMODEL
24153 	/* To support ILP32 applications in an LP64 world */
24154 	struct cdrom_subcode32		cdrom_subcode32;
24155 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
24156 #endif
24157 	if (data == NULL) {
24158 		return (EINVAL);
24159 	}
24160 
24161 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24162 		return (ENXIO);
24163 	}
24164 
24165 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
24166 
24167 #ifdef _MULTI_DATAMODEL
24168 	switch (ddi_model_convert_from(flag & FMODELS)) {
24169 	case DDI_MODEL_ILP32:
24170 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
24171 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24172 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24173 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24174 			return (EFAULT);
24175 		}
24176 		/* Convert the ILP32 uscsi data from the application to LP64 */
24177 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
24178 		break;
24179 	case DDI_MODEL_NONE:
24180 		if (ddi_copyin(data, subcode,
24181 		    sizeof (struct cdrom_subcode), flag)) {
24182 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24183 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24184 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24185 			return (EFAULT);
24186 		}
24187 		break;
24188 	}
24189 #else /* ! _MULTI_DATAMODEL */
24190 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
24191 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24192 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
24193 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24194 		return (EFAULT);
24195 	}
24196 #endif /* _MULTI_DATAMODEL */
24197 
24198 	/*
24199 	 * Since MMC-2 expects max 3 bytes for length, check if the
24200 	 * length input is greater than 3 bytes
24201 	 */
24202 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
24203 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24204 		    "sr_read_all_subcodes: "
24205 		    "cdrom transfer length too large: %d (limit %d)\n",
24206 		    subcode->cdsc_length, 0xFFFFFF);
24207 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24208 		return (EINVAL);
24209 	}
24210 
24211 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
24212 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24213 	bzero(cdb, CDB_GROUP5);
24214 
24215 	if (un->un_f_mmc_cap == TRUE) {
24216 		cdb[0] = (char)SCMD_READ_CD;
24217 		cdb[2] = (char)0xff;
24218 		cdb[3] = (char)0xff;
24219 		cdb[4] = (char)0xff;
24220 		cdb[5] = (char)0xff;
24221 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24222 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24223 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
24224 		cdb[10] = 1;
24225 	} else {
24226 		/*
24227 		 * Note: A vendor specific command (0xDF) is being used her to
24228 		 * request a read of all subcodes.
24229 		 */
24230 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
24231 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
24232 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24233 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24234 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
24235 	}
24236 	com->uscsi_cdb	   = cdb;
24237 	com->uscsi_cdblen  = CDB_GROUP5;
24238 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
24239 	com->uscsi_buflen  = buflen;
24240 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24241 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
24242 	    SD_PATH_STANDARD);
24243 	kmem_free(subcode, sizeof (struct cdrom_subcode));
24244 	kmem_free(com, sizeof (*com));
24245 	return (rval);
24246 }
24247 
24248 
24249 /*
24250  *    Function: sr_read_subchannel()
24251  *
24252  * Description: This routine is the driver entry point for handling CD-ROM
24253  *		ioctl requests to return the Q sub-channel data of the CD
24254  *		current position block. (CDROMSUBCHNL) The data includes the
24255  *		track number, index number, absolute CD-ROM address (LBA or MSF
24256  *		format per the user) , track relative CD-ROM address (LBA or MSF
24257  *		format per the user), control data and audio status.
24258  *
24259  *   Arguments: dev	- the device 'dev_t'
24260  *		data	- pointer to user provided cdrom sub-channel structure
24261  *		flag	- this argument is a pass through to ddi_copyxxx()
24262  *		          directly from the mode argument of ioctl().
24263  *
24264  * Return Code: the code returned by sd_send_scsi_cmd()
24265  *		EFAULT if ddi_copyxxx() fails
24266  *		ENXIO if fail ddi_get_soft_state
24267  *		EINVAL if data pointer is NULL
24268  */
24269 
24270 static int
24271 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
24272 {
24273 	struct sd_lun		*un;
24274 	struct uscsi_cmd	*com;
24275 	struct cdrom_subchnl	subchanel;
24276 	struct cdrom_subchnl	*subchnl = &subchanel;
24277 	char			cdb[CDB_GROUP1];
24278 	caddr_t			buffer;
24279 	int			rval;
24280 
24281 	if (data == NULL) {
24282 		return (EINVAL);
24283 	}
24284 
24285 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24286 	    (un->un_state == SD_STATE_OFFLINE)) {
24287 		return (ENXIO);
24288 	}
24289 
24290 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
24291 		return (EFAULT);
24292 	}
24293 
24294 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
24295 	bzero(cdb, CDB_GROUP1);
24296 	cdb[0] = SCMD_READ_SUBCHANNEL;
24297 	/* Set the MSF bit based on the user requested address format */
24298 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
24299 	/*
24300 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
24301 	 * returned
24302 	 */
24303 	cdb[2] = 0x40;
24304 	/*
24305 	 * Set byte 3 to specify the return data format. A value of 0x01
24306 	 * indicates that the CD-ROM current position should be returned.
24307 	 */
24308 	cdb[3] = 0x01;
24309 	cdb[8] = 0x10;
24310 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24311 	com->uscsi_cdb	   = cdb;
24312 	com->uscsi_cdblen  = CDB_GROUP1;
24313 	com->uscsi_bufaddr = buffer;
24314 	com->uscsi_buflen  = 16;
24315 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24316 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24317 	    SD_PATH_STANDARD);
24318 	if (rval != 0) {
24319 		kmem_free(buffer, 16);
24320 		kmem_free(com, sizeof (*com));
24321 		return (rval);
24322 	}
24323 
24324 	/* Process the returned Q sub-channel data */
24325 	subchnl->cdsc_audiostatus = buffer[1];
24326 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
24327 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
24328 	subchnl->cdsc_trk	= buffer[6];
24329 	subchnl->cdsc_ind	= buffer[7];
24330 	if (subchnl->cdsc_format & CDROM_LBA) {
24331 		subchnl->cdsc_absaddr.lba =
24332 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
24333 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
24334 		subchnl->cdsc_reladdr.lba =
24335 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
24336 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
24337 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
24338 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
24339 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
24340 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
24341 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
24342 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
24343 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
24344 	} else {
24345 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
24346 		subchnl->cdsc_absaddr.msf.second = buffer[10];
24347 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
24348 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
24349 		subchnl->cdsc_reladdr.msf.second = buffer[14];
24350 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
24351 	}
24352 	kmem_free(buffer, 16);
24353 	kmem_free(com, sizeof (*com));
24354 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
24355 	    != 0) {
24356 		return (EFAULT);
24357 	}
24358 	return (rval);
24359 }
24360 
24361 
24362 /*
24363  *    Function: sr_read_tocentry()
24364  *
24365  * Description: This routine is the driver entry point for handling CD-ROM
24366  *		ioctl requests to read from the Table of Contents (TOC)
24367  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
24368  *		fields, the starting address (LBA or MSF format per the user)
24369  *		and the data mode if the user specified track is a data track.
24370  *
24371  *		Note: The READ HEADER (0x44) command used in this routine is
24372  *		obsolete per the SCSI MMC spec but still supported in the
24373  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
24374  *		therefore the command is still implemented in this routine.
24375  *
24376  *   Arguments: dev	- the device 'dev_t'
24377  *		data	- pointer to user provided toc entry structure,
24378  *			  specifying the track # and the address format
24379  *			  (LBA or MSF).
24380  *		flag	- this argument is a pass through to ddi_copyxxx()
24381  *		          directly from the mode argument of ioctl().
24382  *
24383  * Return Code: the code returned by sd_send_scsi_cmd()
24384  *		EFAULT if ddi_copyxxx() fails
24385  *		ENXIO if fail ddi_get_soft_state
24386  *		EINVAL if data pointer is NULL
24387  */
24388 
24389 static int
24390 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
24391 {
24392 	struct sd_lun		*un = NULL;
24393 	struct uscsi_cmd	*com;
24394 	struct cdrom_tocentry	toc_entry;
24395 	struct cdrom_tocentry	*entry = &toc_entry;
24396 	caddr_t			buffer;
24397 	int			rval;
24398 	char			cdb[CDB_GROUP1];
24399 
24400 	if (data == NULL) {
24401 		return (EINVAL);
24402 	}
24403 
24404 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24405 	    (un->un_state == SD_STATE_OFFLINE)) {
24406 		return (ENXIO);
24407 	}
24408 
24409 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
24410 		return (EFAULT);
24411 	}
24412 
24413 	/* Validate the requested track and address format */
24414 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
24415 		return (EINVAL);
24416 	}
24417 
24418 	if (entry->cdte_track == 0) {
24419 		return (EINVAL);
24420 	}
24421 
24422 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
24423 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24424 	bzero(cdb, CDB_GROUP1);
24425 
24426 	cdb[0] = SCMD_READ_TOC;
24427 	/* Set the MSF bit based on the user requested address format  */
24428 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
24429 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
24430 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
24431 	} else {
24432 		cdb[6] = entry->cdte_track;
24433 	}
24434 
24435 	/*
24436 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
24437 	 * (4 byte TOC response header + 8 byte track descriptor)
24438 	 */
24439 	cdb[8] = 12;
24440 	com->uscsi_cdb	   = cdb;
24441 	com->uscsi_cdblen  = CDB_GROUP1;
24442 	com->uscsi_bufaddr = buffer;
24443 	com->uscsi_buflen  = 0x0C;
24444 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
24445 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24446 	    SD_PATH_STANDARD);
24447 	if (rval != 0) {
24448 		kmem_free(buffer, 12);
24449 		kmem_free(com, sizeof (*com));
24450 		return (rval);
24451 	}
24452 
24453 	/* Process the toc entry */
24454 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
24455 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
24456 	if (entry->cdte_format & CDROM_LBA) {
24457 		entry->cdte_addr.lba =
24458 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
24459 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
24460 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
24461 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
24462 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
24463 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
24464 		/*
24465 		 * Send a READ TOC command using the LBA address format to get
24466 		 * the LBA for the track requested so it can be used in the
24467 		 * READ HEADER request
24468 		 *
24469 		 * Note: The MSF bit of the READ HEADER command specifies the
24470 		 * output format. The block address specified in that command
24471 		 * must be in LBA format.
24472 		 */
24473 		cdb[1] = 0;
24474 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24475 		    SD_PATH_STANDARD);
24476 		if (rval != 0) {
24477 			kmem_free(buffer, 12);
24478 			kmem_free(com, sizeof (*com));
24479 			return (rval);
24480 		}
24481 	} else {
24482 		entry->cdte_addr.msf.minute	= buffer[9];
24483 		entry->cdte_addr.msf.second	= buffer[10];
24484 		entry->cdte_addr.msf.frame	= buffer[11];
24485 		/*
24486 		 * Send a READ TOC command using the LBA address format to get
24487 		 * the LBA for the track requested so it can be used in the
24488 		 * READ HEADER request
24489 		 *
24490 		 * Note: The MSF bit of the READ HEADER command specifies the
24491 		 * output format. The block address specified in that command
24492 		 * must be in LBA format.
24493 		 */
24494 		cdb[1] = 0;
24495 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24496 		    SD_PATH_STANDARD);
24497 		if (rval != 0) {
24498 			kmem_free(buffer, 12);
24499 			kmem_free(com, sizeof (*com));
24500 			return (rval);
24501 		}
24502 	}
24503 
24504 	/*
24505 	 * Build and send the READ HEADER command to determine the data mode of
24506 	 * the user specified track.
24507 	 */
24508 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
24509 	    (entry->cdte_track != CDROM_LEADOUT)) {
24510 		bzero(cdb, CDB_GROUP1);
24511 		cdb[0] = SCMD_READ_HEADER;
24512 		cdb[2] = buffer[8];
24513 		cdb[3] = buffer[9];
24514 		cdb[4] = buffer[10];
24515 		cdb[5] = buffer[11];
24516 		cdb[8] = 0x08;
24517 		com->uscsi_buflen = 0x08;
24518 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24519 		    SD_PATH_STANDARD);
24520 		if (rval == 0) {
24521 			entry->cdte_datamode = buffer[0];
24522 		} else {
24523 			/*
24524 			 * READ HEADER command failed, since this is
24525 			 * obsoleted in one spec, its better to return
24526 			 * -1 for an invlid track so that we can still
24527 			 * receive the rest of the TOC data.
24528 			 */
24529 			entry->cdte_datamode = (uchar_t)-1;
24530 		}
24531 	} else {
24532 		entry->cdte_datamode = (uchar_t)-1;
24533 	}
24534 
24535 	kmem_free(buffer, 12);
24536 	kmem_free(com, sizeof (*com));
24537 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
24538 		return (EFAULT);
24539 
24540 	return (rval);
24541 }
24542 
24543 
24544 /*
24545  *    Function: sr_read_tochdr()
24546  *
24547  * Description: This routine is the driver entry point for handling CD-ROM
24548  * 		ioctl requests to read the Table of Contents (TOC) header
24549  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
24550  *		and ending track numbers
24551  *
24552  *   Arguments: dev	- the device 'dev_t'
24553  *		data	- pointer to user provided toc header structure,
24554  *			  specifying the starting and ending track numbers.
24555  *		flag	- this argument is a pass through to ddi_copyxxx()
24556  *			  directly from the mode argument of ioctl().
24557  *
24558  * Return Code: the code returned by sd_send_scsi_cmd()
24559  *		EFAULT if ddi_copyxxx() fails
24560  *		ENXIO if fail ddi_get_soft_state
24561  *		EINVAL if data pointer is NULL
24562  */
24563 
24564 static int
24565 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
24566 {
24567 	struct sd_lun		*un;
24568 	struct uscsi_cmd	*com;
24569 	struct cdrom_tochdr	toc_header;
24570 	struct cdrom_tochdr	*hdr = &toc_header;
24571 	char			cdb[CDB_GROUP1];
24572 	int			rval;
24573 	caddr_t			buffer;
24574 
24575 	if (data == NULL) {
24576 		return (EINVAL);
24577 	}
24578 
24579 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24580 	    (un->un_state == SD_STATE_OFFLINE)) {
24581 		return (ENXIO);
24582 	}
24583 
24584 	buffer = kmem_zalloc(4, KM_SLEEP);
24585 	bzero(cdb, CDB_GROUP1);
24586 	cdb[0] = SCMD_READ_TOC;
24587 	/*
24588 	 * Specifying a track number of 0x00 in the READ TOC command indicates
24589 	 * that the TOC header should be returned
24590 	 */
24591 	cdb[6] = 0x00;
24592 	/*
24593 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
24594 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
24595 	 */
24596 	cdb[8] = 0x04;
24597 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24598 	com->uscsi_cdb	   = cdb;
24599 	com->uscsi_cdblen  = CDB_GROUP1;
24600 	com->uscsi_bufaddr = buffer;
24601 	com->uscsi_buflen  = 0x04;
24602 	com->uscsi_timeout = 300;
24603 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24604 
24605 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24606 	    SD_PATH_STANDARD);
24607 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
24608 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
24609 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
24610 	} else {
24611 		hdr->cdth_trk0 = buffer[2];
24612 		hdr->cdth_trk1 = buffer[3];
24613 	}
24614 	kmem_free(buffer, 4);
24615 	kmem_free(com, sizeof (*com));
24616 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
24617 		return (EFAULT);
24618 	}
24619 	return (rval);
24620 }
24621 
24622 
24623 /*
24624  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
24625  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
24626  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
24627  * digital audio and extended architecture digital audio. These modes are
24628  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
24629  * MMC specs.
24630  *
24631  * In addition to support for the various data formats these routines also
24632  * include support for devices that implement only the direct access READ
24633  * commands (0x08, 0x28), devices that implement the READ_CD commands
24634  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
24635  * READ CDXA commands (0xD8, 0xDB)
24636  */
24637 
24638 /*
24639  *    Function: sr_read_mode1()
24640  *
24641  * Description: This routine is the driver entry point for handling CD-ROM
24642  *		ioctl read mode1 requests (CDROMREADMODE1).
24643  *
24644  *   Arguments: dev	- the device 'dev_t'
24645  *		data	- pointer to user provided cd read structure specifying
24646  *			  the lba buffer address and length.
24647  *		flag	- this argument is a pass through to ddi_copyxxx()
24648  *			  directly from the mode argument of ioctl().
24649  *
24650  * Return Code: the code returned by sd_send_scsi_cmd()
24651  *		EFAULT if ddi_copyxxx() fails
24652  *		ENXIO if fail ddi_get_soft_state
24653  *		EINVAL if data pointer is NULL
24654  */
24655 
24656 static int
24657 sr_read_mode1(dev_t dev, caddr_t data, int flag)
24658 {
24659 	struct sd_lun		*un;
24660 	struct cdrom_read	mode1_struct;
24661 	struct cdrom_read	*mode1 = &mode1_struct;
24662 	int			rval;
24663 #ifdef _MULTI_DATAMODEL
24664 	/* To support ILP32 applications in an LP64 world */
24665 	struct cdrom_read32	cdrom_read32;
24666 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
24667 #endif /* _MULTI_DATAMODEL */
24668 
24669 	if (data == NULL) {
24670 		return (EINVAL);
24671 	}
24672 
24673 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24674 	    (un->un_state == SD_STATE_OFFLINE)) {
24675 		return (ENXIO);
24676 	}
24677 
24678 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
24679 	    "sd_read_mode1: entry: un:0x%p\n", un);
24680 
24681 #ifdef _MULTI_DATAMODEL
24682 	switch (ddi_model_convert_from(flag & FMODELS)) {
24683 	case DDI_MODEL_ILP32:
24684 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
24685 			return (EFAULT);
24686 		}
24687 		/* Convert the ILP32 uscsi data from the application to LP64 */
24688 		cdrom_read32tocdrom_read(cdrd32, mode1);
24689 		break;
24690 	case DDI_MODEL_NONE:
24691 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
24692 			return (EFAULT);
24693 		}
24694 	}
24695 #else /* ! _MULTI_DATAMODEL */
24696 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
24697 		return (EFAULT);
24698 	}
24699 #endif /* _MULTI_DATAMODEL */
24700 
24701 	rval = sd_send_scsi_READ(un, mode1->cdread_bufaddr,
24702 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
24703 
24704 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
24705 	    "sd_read_mode1: exit: un:0x%p\n", un);
24706 
24707 	return (rval);
24708 }
24709 
24710 
24711 /*
24712  *    Function: sr_read_cd_mode2()
24713  *
24714  * Description: This routine is the driver entry point for handling CD-ROM
24715  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
24716  *		support the READ CD (0xBE) command or the 1st generation
24717  *		READ CD (0xD4) command.
24718  *
24719  *   Arguments: dev	- the device 'dev_t'
24720  *		data	- pointer to user provided cd read structure specifying
24721  *			  the lba buffer address and length.
24722  *		flag	- this argument is a pass through to ddi_copyxxx()
24723  *			  directly from the mode argument of ioctl().
24724  *
24725  * Return Code: the code returned by sd_send_scsi_cmd()
24726  *		EFAULT if ddi_copyxxx() fails
24727  *		ENXIO if fail ddi_get_soft_state
24728  *		EINVAL if data pointer is NULL
24729  */
24730 
24731 static int
24732 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
24733 {
24734 	struct sd_lun		*un;
24735 	struct uscsi_cmd	*com;
24736 	struct cdrom_read	mode2_struct;
24737 	struct cdrom_read	*mode2 = &mode2_struct;
24738 	uchar_t			cdb[CDB_GROUP5];
24739 	int			nblocks;
24740 	int			rval;
24741 #ifdef _MULTI_DATAMODEL
24742 	/*  To support ILP32 applications in an LP64 world */
24743 	struct cdrom_read32	cdrom_read32;
24744 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
24745 #endif /* _MULTI_DATAMODEL */
24746 
24747 	if (data == NULL) {
24748 		return (EINVAL);
24749 	}
24750 
24751 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24752 	    (un->un_state == SD_STATE_OFFLINE)) {
24753 		return (ENXIO);
24754 	}
24755 
24756 #ifdef _MULTI_DATAMODEL
24757 	switch (ddi_model_convert_from(flag & FMODELS)) {
24758 	case DDI_MODEL_ILP32:
24759 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
24760 			return (EFAULT);
24761 		}
24762 		/* Convert the ILP32 uscsi data from the application to LP64 */
24763 		cdrom_read32tocdrom_read(cdrd32, mode2);
24764 		break;
24765 	case DDI_MODEL_NONE:
24766 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
24767 			return (EFAULT);
24768 		}
24769 		break;
24770 	}
24771 
24772 #else /* ! _MULTI_DATAMODEL */
24773 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
24774 		return (EFAULT);
24775 	}
24776 #endif /* _MULTI_DATAMODEL */
24777 
24778 	bzero(cdb, sizeof (cdb));
24779 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
24780 		/* Read command supported by 1st generation atapi drives */
24781 		cdb[0] = SCMD_READ_CDD4;
24782 	} else {
24783 		/* Universal CD Access Command */
24784 		cdb[0] = SCMD_READ_CD;
24785 	}
24786 
24787 	/*
24788 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
24789 	 */
24790 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
24791 
24792 	/* set the start address */
24793 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
24794 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
24795 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
24796 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
24797 
24798 	/* set the transfer length */
24799 	nblocks = mode2->cdread_buflen / 2336;
24800 	cdb[6] = (uchar_t)(nblocks >> 16);
24801 	cdb[7] = (uchar_t)(nblocks >> 8);
24802 	cdb[8] = (uchar_t)nblocks;
24803 
24804 	/* set the filter bits */
24805 	cdb[9] = CDROM_READ_CD_USERDATA;
24806 
24807 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24808 	com->uscsi_cdb = (caddr_t)cdb;
24809 	com->uscsi_cdblen = sizeof (cdb);
24810 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
24811 	com->uscsi_buflen = mode2->cdread_buflen;
24812 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24813 
24814 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
24815 	    SD_PATH_STANDARD);
24816 	kmem_free(com, sizeof (*com));
24817 	return (rval);
24818 }
24819 
24820 
24821 /*
24822  *    Function: sr_read_mode2()
24823  *
24824  * Description: This routine is the driver entry point for handling CD-ROM
24825  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
24826  *		do not support the READ CD (0xBE) command.
24827  *
24828  *   Arguments: dev	- the device 'dev_t'
24829  *		data	- pointer to user provided cd read structure specifying
24830  *			  the lba buffer address and length.
24831  *		flag	- this argument is a pass through to ddi_copyxxx()
24832  *			  directly from the mode argument of ioctl().
24833  *
24834  * Return Code: the code returned by sd_send_scsi_cmd()
24835  *		EFAULT if ddi_copyxxx() fails
24836  *		ENXIO if fail ddi_get_soft_state
24837  *		EINVAL if data pointer is NULL
24838  *		EIO if fail to reset block size
24839  *		EAGAIN if commands are in progress in the driver
24840  */
24841 
24842 static int
24843 sr_read_mode2(dev_t dev, caddr_t data, int flag)
24844 {
24845 	struct sd_lun		*un;
24846 	struct cdrom_read	mode2_struct;
24847 	struct cdrom_read	*mode2 = &mode2_struct;
24848 	int			rval;
24849 	uint32_t		restore_blksize;
24850 	struct uscsi_cmd	*com;
24851 	uchar_t			cdb[CDB_GROUP0];
24852 	int			nblocks;
24853 
24854 #ifdef _MULTI_DATAMODEL
24855 	/* To support ILP32 applications in an LP64 world */
24856 	struct cdrom_read32	cdrom_read32;
24857 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
24858 #endif /* _MULTI_DATAMODEL */
24859 
24860 	if (data == NULL) {
24861 		return (EINVAL);
24862 	}
24863 
24864 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24865 	    (un->un_state == SD_STATE_OFFLINE)) {
24866 		return (ENXIO);
24867 	}
24868 
24869 	/*
24870 	 * Because this routine will update the device and driver block size
24871 	 * being used we want to make sure there are no commands in progress.
24872 	 * If commands are in progress the user will have to try again.
24873 	 *
24874 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
24875 	 * in sdioctl to protect commands from sdioctl through to the top of
24876 	 * sd_uscsi_strategy. See sdioctl for details.
24877 	 */
24878 	mutex_enter(SD_MUTEX(un));
24879 	if (un->un_ncmds_in_driver != 1) {
24880 		mutex_exit(SD_MUTEX(un));
24881 		return (EAGAIN);
24882 	}
24883 	mutex_exit(SD_MUTEX(un));
24884 
24885 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
24886 	    "sd_read_mode2: entry: un:0x%p\n", un);
24887 
24888 #ifdef _MULTI_DATAMODEL
24889 	switch (ddi_model_convert_from(flag & FMODELS)) {
24890 	case DDI_MODEL_ILP32:
24891 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
24892 			return (EFAULT);
24893 		}
24894 		/* Convert the ILP32 uscsi data from the application to LP64 */
24895 		cdrom_read32tocdrom_read(cdrd32, mode2);
24896 		break;
24897 	case DDI_MODEL_NONE:
24898 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
24899 			return (EFAULT);
24900 		}
24901 		break;
24902 	}
24903 #else /* ! _MULTI_DATAMODEL */
24904 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
24905 		return (EFAULT);
24906 	}
24907 #endif /* _MULTI_DATAMODEL */
24908 
24909 	/* Store the current target block size for restoration later */
24910 	restore_blksize = un->un_tgt_blocksize;
24911 
24912 	/* Change the device and soft state target block size to 2336 */
24913 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
24914 		rval = EIO;
24915 		goto done;
24916 	}
24917 
24918 
24919 	bzero(cdb, sizeof (cdb));
24920 
24921 	/* set READ operation */
24922 	cdb[0] = SCMD_READ;
24923 
24924 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
24925 	mode2->cdread_lba >>= 2;
24926 
24927 	/* set the start address */
24928 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
24929 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
24930 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
24931 
24932 	/* set the transfer length */
24933 	nblocks = mode2->cdread_buflen / 2336;
24934 	cdb[4] = (uchar_t)nblocks & 0xFF;
24935 
24936 	/* build command */
24937 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24938 	com->uscsi_cdb = (caddr_t)cdb;
24939 	com->uscsi_cdblen = sizeof (cdb);
24940 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
24941 	com->uscsi_buflen = mode2->cdread_buflen;
24942 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24943 
24944 	/*
24945 	 * Issue SCSI command with user space address for read buffer.
24946 	 *
24947 	 * This sends the command through main channel in the driver.
24948 	 *
24949 	 * Since this is accessed via an IOCTL call, we go through the
24950 	 * standard path, so that if the device was powered down, then
24951 	 * it would be 'awakened' to handle the command.
24952 	 */
24953 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
24954 	    SD_PATH_STANDARD);
24955 
24956 	kmem_free(com, sizeof (*com));
24957 
24958 	/* Restore the device and soft state target block size */
24959 	if (sr_sector_mode(dev, restore_blksize) != 0) {
24960 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24961 		    "can't do switch back to mode 1\n");
24962 		/*
24963 		 * If sd_send_scsi_READ succeeded we still need to report
24964 		 * an error because we failed to reset the block size
24965 		 */
24966 		if (rval == 0) {
24967 			rval = EIO;
24968 		}
24969 	}
24970 
24971 done:
24972 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
24973 	    "sd_read_mode2: exit: un:0x%p\n", un);
24974 
24975 	return (rval);
24976 }
24977 
24978 
24979 /*
24980  *    Function: sr_sector_mode()
24981  *
24982  * Description: This utility function is used by sr_read_mode2 to set the target
24983  *		block size based on the user specified size. This is a legacy
24984  *		implementation based upon a vendor specific mode page
24985  *
24986  *   Arguments: dev	- the device 'dev_t'
24987  *		data	- flag indicating if block size is being set to 2336 or
24988  *			  512.
24989  *
24990  * Return Code: the code returned by sd_send_scsi_cmd()
24991  *		EFAULT if ddi_copyxxx() fails
24992  *		ENXIO if fail ddi_get_soft_state
24993  *		EINVAL if data pointer is NULL
24994  */
24995 
24996 static int
24997 sr_sector_mode(dev_t dev, uint32_t blksize)
24998 {
24999 	struct sd_lun	*un;
25000 	uchar_t		*sense;
25001 	uchar_t		*select;
25002 	int		rval;
25003 
25004 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25005 	    (un->un_state == SD_STATE_OFFLINE)) {
25006 		return (ENXIO);
25007 	}
25008 
25009 	sense = kmem_zalloc(20, KM_SLEEP);
25010 
25011 	/* Note: This is a vendor specific mode page (0x81) */
25012 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, 20, 0x81,
25013 	    SD_PATH_STANDARD)) != 0) {
25014 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25015 		    "sr_sector_mode: Mode Sense failed\n");
25016 		kmem_free(sense, 20);
25017 		return (rval);
25018 	}
25019 	select = kmem_zalloc(20, KM_SLEEP);
25020 	select[3] = 0x08;
25021 	select[10] = ((blksize >> 8) & 0xff);
25022 	select[11] = (blksize & 0xff);
25023 	select[12] = 0x01;
25024 	select[13] = 0x06;
25025 	select[14] = sense[14];
25026 	select[15] = sense[15];
25027 	if (blksize == SD_MODE2_BLKSIZE) {
25028 		select[14] |= 0x01;
25029 	}
25030 
25031 	if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select, 20,
25032 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
25033 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25034 		    "sr_sector_mode: Mode Select failed\n");
25035 	} else {
25036 		/*
25037 		 * Only update the softstate block size if we successfully
25038 		 * changed the device block mode.
25039 		 */
25040 		mutex_enter(SD_MUTEX(un));
25041 		sd_update_block_info(un, blksize, 0);
25042 		mutex_exit(SD_MUTEX(un));
25043 	}
25044 	kmem_free(sense, 20);
25045 	kmem_free(select, 20);
25046 	return (rval);
25047 }
25048 
25049 
25050 /*
25051  *    Function: sr_read_cdda()
25052  *
25053  * Description: This routine is the driver entry point for handling CD-ROM
25054  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
25055  *		the target supports CDDA these requests are handled via a vendor
25056  *		specific command (0xD8) If the target does not support CDDA
25057  *		these requests are handled via the READ CD command (0xBE).
25058  *
25059  *   Arguments: dev	- the device 'dev_t'
25060  *		data	- pointer to user provided CD-DA structure specifying
25061  *			  the track starting address, transfer length, and
25062  *			  subcode options.
25063  *		flag	- this argument is a pass through to ddi_copyxxx()
25064  *			  directly from the mode argument of ioctl().
25065  *
25066  * Return Code: the code returned by sd_send_scsi_cmd()
25067  *		EFAULT if ddi_copyxxx() fails
25068  *		ENXIO if fail ddi_get_soft_state
25069  *		EINVAL if invalid arguments are provided
25070  *		ENOTTY
25071  */
25072 
25073 static int
25074 sr_read_cdda(dev_t dev, caddr_t data, int flag)
25075 {
25076 	struct sd_lun			*un;
25077 	struct uscsi_cmd		*com;
25078 	struct cdrom_cdda		*cdda;
25079 	int				rval;
25080 	size_t				buflen;
25081 	char				cdb[CDB_GROUP5];
25082 
25083 #ifdef _MULTI_DATAMODEL
25084 	/* To support ILP32 applications in an LP64 world */
25085 	struct cdrom_cdda32	cdrom_cdda32;
25086 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
25087 #endif /* _MULTI_DATAMODEL */
25088 
25089 	if (data == NULL) {
25090 		return (EINVAL);
25091 	}
25092 
25093 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25094 		return (ENXIO);
25095 	}
25096 
25097 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
25098 
25099 #ifdef _MULTI_DATAMODEL
25100 	switch (ddi_model_convert_from(flag & FMODELS)) {
25101 	case DDI_MODEL_ILP32:
25102 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
25103 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25104 			    "sr_read_cdda: ddi_copyin Failed\n");
25105 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25106 			return (EFAULT);
25107 		}
25108 		/* Convert the ILP32 uscsi data from the application to LP64 */
25109 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
25110 		break;
25111 	case DDI_MODEL_NONE:
25112 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25113 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25114 			    "sr_read_cdda: ddi_copyin Failed\n");
25115 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25116 			return (EFAULT);
25117 		}
25118 		break;
25119 	}
25120 #else /* ! _MULTI_DATAMODEL */
25121 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25122 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25123 		    "sr_read_cdda: ddi_copyin Failed\n");
25124 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25125 		return (EFAULT);
25126 	}
25127 #endif /* _MULTI_DATAMODEL */
25128 
25129 	/*
25130 	 * Since MMC-2 expects max 3 bytes for length, check if the
25131 	 * length input is greater than 3 bytes
25132 	 */
25133 	if ((cdda->cdda_length & 0xFF000000) != 0) {
25134 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
25135 		    "cdrom transfer length too large: %d (limit %d)\n",
25136 		    cdda->cdda_length, 0xFFFFFF);
25137 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25138 		return (EINVAL);
25139 	}
25140 
25141 	switch (cdda->cdda_subcode) {
25142 	case CDROM_DA_NO_SUBCODE:
25143 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
25144 		break;
25145 	case CDROM_DA_SUBQ:
25146 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
25147 		break;
25148 	case CDROM_DA_ALL_SUBCODE:
25149 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
25150 		break;
25151 	case CDROM_DA_SUBCODE_ONLY:
25152 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
25153 		break;
25154 	default:
25155 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25156 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
25157 		    cdda->cdda_subcode);
25158 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25159 		return (EINVAL);
25160 	}
25161 
25162 	/* Build and send the command */
25163 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25164 	bzero(cdb, CDB_GROUP5);
25165 
25166 	if (un->un_f_cfg_cdda == TRUE) {
25167 		cdb[0] = (char)SCMD_READ_CD;
25168 		cdb[1] = 0x04;
25169 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25170 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25171 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25172 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25173 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25174 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25175 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
25176 		cdb[9] = 0x10;
25177 		switch (cdda->cdda_subcode) {
25178 		case CDROM_DA_NO_SUBCODE :
25179 			cdb[10] = 0x0;
25180 			break;
25181 		case CDROM_DA_SUBQ :
25182 			cdb[10] = 0x2;
25183 			break;
25184 		case CDROM_DA_ALL_SUBCODE :
25185 			cdb[10] = 0x1;
25186 			break;
25187 		case CDROM_DA_SUBCODE_ONLY :
25188 			/* FALLTHROUGH */
25189 		default :
25190 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25191 			kmem_free(com, sizeof (*com));
25192 			return (ENOTTY);
25193 		}
25194 	} else {
25195 		cdb[0] = (char)SCMD_READ_CDDA;
25196 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25197 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25198 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25199 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25200 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
25201 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25202 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25203 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
25204 		cdb[10] = cdda->cdda_subcode;
25205 	}
25206 
25207 	com->uscsi_cdb = cdb;
25208 	com->uscsi_cdblen = CDB_GROUP5;
25209 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
25210 	com->uscsi_buflen = buflen;
25211 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25212 
25213 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25214 	    SD_PATH_STANDARD);
25215 
25216 	kmem_free(cdda, sizeof (struct cdrom_cdda));
25217 	kmem_free(com, sizeof (*com));
25218 	return (rval);
25219 }
25220 
25221 
25222 /*
25223  *    Function: sr_read_cdxa()
25224  *
25225  * Description: This routine is the driver entry point for handling CD-ROM
25226  *		ioctl requests to return CD-XA (Extended Architecture) data.
25227  *		(CDROMCDXA).
25228  *
25229  *   Arguments: dev	- the device 'dev_t'
25230  *		data	- pointer to user provided CD-XA structure specifying
25231  *			  the data starting address, transfer length, and format
25232  *		flag	- this argument is a pass through to ddi_copyxxx()
25233  *			  directly from the mode argument of ioctl().
25234  *
25235  * Return Code: the code returned by sd_send_scsi_cmd()
25236  *		EFAULT if ddi_copyxxx() fails
25237  *		ENXIO if fail ddi_get_soft_state
25238  *		EINVAL if data pointer is NULL
25239  */
25240 
25241 static int
25242 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
25243 {
25244 	struct sd_lun		*un;
25245 	struct uscsi_cmd	*com;
25246 	struct cdrom_cdxa	*cdxa;
25247 	int			rval;
25248 	size_t			buflen;
25249 	char			cdb[CDB_GROUP5];
25250 	uchar_t			read_flags;
25251 
25252 #ifdef _MULTI_DATAMODEL
25253 	/* To support ILP32 applications in an LP64 world */
25254 	struct cdrom_cdxa32		cdrom_cdxa32;
25255 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
25256 #endif /* _MULTI_DATAMODEL */
25257 
25258 	if (data == NULL) {
25259 		return (EINVAL);
25260 	}
25261 
25262 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25263 		return (ENXIO);
25264 	}
25265 
25266 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
25267 
25268 #ifdef _MULTI_DATAMODEL
25269 	switch (ddi_model_convert_from(flag & FMODELS)) {
25270 	case DDI_MODEL_ILP32:
25271 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
25272 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25273 			return (EFAULT);
25274 		}
25275 		/*
25276 		 * Convert the ILP32 uscsi data from the
25277 		 * application to LP64 for internal use.
25278 		 */
25279 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
25280 		break;
25281 	case DDI_MODEL_NONE:
25282 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25283 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25284 			return (EFAULT);
25285 		}
25286 		break;
25287 	}
25288 #else /* ! _MULTI_DATAMODEL */
25289 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25290 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25291 		return (EFAULT);
25292 	}
25293 #endif /* _MULTI_DATAMODEL */
25294 
25295 	/*
25296 	 * Since MMC-2 expects max 3 bytes for length, check if the
25297 	 * length input is greater than 3 bytes
25298 	 */
25299 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
25300 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
25301 		    "cdrom transfer length too large: %d (limit %d)\n",
25302 		    cdxa->cdxa_length, 0xFFFFFF);
25303 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25304 		return (EINVAL);
25305 	}
25306 
25307 	switch (cdxa->cdxa_format) {
25308 	case CDROM_XA_DATA:
25309 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
25310 		read_flags = 0x10;
25311 		break;
25312 	case CDROM_XA_SECTOR_DATA:
25313 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
25314 		read_flags = 0xf8;
25315 		break;
25316 	case CDROM_XA_DATA_W_ERROR:
25317 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
25318 		read_flags = 0xfc;
25319 		break;
25320 	default:
25321 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25322 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
25323 		    cdxa->cdxa_format);
25324 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25325 		return (EINVAL);
25326 	}
25327 
25328 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25329 	bzero(cdb, CDB_GROUP5);
25330 	if (un->un_f_mmc_cap == TRUE) {
25331 		cdb[0] = (char)SCMD_READ_CD;
25332 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25333 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25334 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25335 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25336 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25337 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25338 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
25339 		cdb[9] = (char)read_flags;
25340 	} else {
25341 		/*
25342 		 * Note: A vendor specific command (0xDB) is being used her to
25343 		 * request a read of all subcodes.
25344 		 */
25345 		cdb[0] = (char)SCMD_READ_CDXA;
25346 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25347 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25348 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25349 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25350 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
25351 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25352 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25353 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
25354 		cdb[10] = cdxa->cdxa_format;
25355 	}
25356 	com->uscsi_cdb	   = cdb;
25357 	com->uscsi_cdblen  = CDB_GROUP5;
25358 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
25359 	com->uscsi_buflen  = buflen;
25360 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25361 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25362 	    SD_PATH_STANDARD);
25363 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25364 	kmem_free(com, sizeof (*com));
25365 	return (rval);
25366 }
25367 
25368 
25369 /*
25370  *    Function: sr_eject()
25371  *
25372  * Description: This routine is the driver entry point for handling CD-ROM
25373  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
25374  *
25375  *   Arguments: dev	- the device 'dev_t'
25376  *
25377  * Return Code: the code returned by sd_send_scsi_cmd()
25378  */
25379 
25380 static int
25381 sr_eject(dev_t dev)
25382 {
25383 	struct sd_lun	*un;
25384 	int		rval;
25385 
25386 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25387 	    (un->un_state == SD_STATE_OFFLINE)) {
25388 		return (ENXIO);
25389 	}
25390 
25391 	/*
25392 	 * To prevent race conditions with the eject
25393 	 * command, keep track of an eject command as
25394 	 * it progresses. If we are already handling
25395 	 * an eject command in the driver for the given
25396 	 * unit and another request to eject is received
25397 	 * immediately return EAGAIN so we don't lose
25398 	 * the command if the current eject command fails.
25399 	 */
25400 	mutex_enter(SD_MUTEX(un));
25401 	if (un->un_f_ejecting == TRUE) {
25402 		mutex_exit(SD_MUTEX(un));
25403 		return (EAGAIN);
25404 	}
25405 	un->un_f_ejecting = TRUE;
25406 	mutex_exit(SD_MUTEX(un));
25407 
25408 	if ((rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
25409 	    SD_PATH_STANDARD)) != 0) {
25410 		mutex_enter(SD_MUTEX(un));
25411 		un->un_f_ejecting = FALSE;
25412 		mutex_exit(SD_MUTEX(un));
25413 		return (rval);
25414 	}
25415 
25416 	rval = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_EJECT,
25417 	    SD_PATH_STANDARD);
25418 
25419 	if (rval == 0) {
25420 		mutex_enter(SD_MUTEX(un));
25421 		sr_ejected(un);
25422 		un->un_mediastate = DKIO_EJECTED;
25423 		un->un_f_ejecting = FALSE;
25424 		cv_broadcast(&un->un_state_cv);
25425 		mutex_exit(SD_MUTEX(un));
25426 	} else {
25427 		mutex_enter(SD_MUTEX(un));
25428 		un->un_f_ejecting = FALSE;
25429 		mutex_exit(SD_MUTEX(un));
25430 	}
25431 	return (rval);
25432 }
25433 
25434 
25435 /*
25436  *    Function: sr_ejected()
25437  *
25438  * Description: This routine updates the soft state structure to invalidate the
25439  *		geometry information after the media has been ejected or a
25440  *		media eject has been detected.
25441  *
25442  *   Arguments: un - driver soft state (unit) structure
25443  */
25444 
25445 static void
25446 sr_ejected(struct sd_lun *un)
25447 {
25448 	struct sd_errstats *stp;
25449 
25450 	ASSERT(un != NULL);
25451 	ASSERT(mutex_owned(SD_MUTEX(un)));
25452 
25453 	un->un_f_blockcount_is_valid	= FALSE;
25454 	un->un_f_tgt_blocksize_is_valid	= FALSE;
25455 	mutex_exit(SD_MUTEX(un));
25456 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
25457 	mutex_enter(SD_MUTEX(un));
25458 
25459 	if (un->un_errstats != NULL) {
25460 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
25461 		stp->sd_capacity.value.ui64 = 0;
25462 	}
25463 
25464 	/* remove "capacity-of-device" properties */
25465 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
25466 	    "device-nblocks");
25467 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
25468 	    "device-blksize");
25469 }
25470 
25471 
25472 /*
25473  *    Function: sr_check_wp()
25474  *
25475  * Description: This routine checks the write protection of a removable
25476  *      media disk and hotpluggable devices via the write protect bit of
25477  *      the Mode Page Header device specific field. Some devices choke
25478  *      on unsupported mode page. In order to workaround this issue,
25479  *      this routine has been implemented to use 0x3f mode page(request
25480  *      for all pages) for all device types.
25481  *
25482  *   Arguments: dev		- the device 'dev_t'
25483  *
25484  * Return Code: int indicating if the device is write protected (1) or not (0)
25485  *
25486  *     Context: Kernel thread.
25487  *
25488  */
25489 
25490 static int
25491 sr_check_wp(dev_t dev)
25492 {
25493 	struct sd_lun	*un;
25494 	uchar_t		device_specific;
25495 	uchar_t		*sense;
25496 	int		hdrlen;
25497 	int		rval = FALSE;
25498 
25499 	/*
25500 	 * Note: The return codes for this routine should be reworked to
25501 	 * properly handle the case of a NULL softstate.
25502 	 */
25503 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25504 		return (FALSE);
25505 	}
25506 
25507 	if (un->un_f_cfg_is_atapi == TRUE) {
25508 		/*
25509 		 * The mode page contents are not required; set the allocation
25510 		 * length for the mode page header only
25511 		 */
25512 		hdrlen = MODE_HEADER_LENGTH_GRP2;
25513 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
25514 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense, hdrlen,
25515 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
25516 			goto err_exit;
25517 		device_specific =
25518 		    ((struct mode_header_grp2 *)sense)->device_specific;
25519 	} else {
25520 		hdrlen = MODE_HEADER_LENGTH;
25521 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
25522 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, hdrlen,
25523 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
25524 			goto err_exit;
25525 		device_specific =
25526 		    ((struct mode_header *)sense)->device_specific;
25527 	}
25528 
25529 	/*
25530 	 * Write protect mode sense failed; not all disks
25531 	 * understand this query. Return FALSE assuming that
25532 	 * these devices are not writable.
25533 	 */
25534 	if (device_specific & WRITE_PROTECT) {
25535 		rval = TRUE;
25536 	}
25537 
25538 err_exit:
25539 	kmem_free(sense, hdrlen);
25540 	return (rval);
25541 }
25542 
25543 /*
25544  *    Function: sr_volume_ctrl()
25545  *
25546  * Description: This routine is the driver entry point for handling CD-ROM
25547  *		audio output volume ioctl requests. (CDROMVOLCTRL)
25548  *
25549  *   Arguments: dev	- the device 'dev_t'
25550  *		data	- pointer to user audio volume control structure
25551  *		flag	- this argument is a pass through to ddi_copyxxx()
25552  *			  directly from the mode argument of ioctl().
25553  *
25554  * Return Code: the code returned by sd_send_scsi_cmd()
25555  *		EFAULT if ddi_copyxxx() fails
25556  *		ENXIO if fail ddi_get_soft_state
25557  *		EINVAL if data pointer is NULL
25558  *
25559  */
25560 
25561 static int
25562 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
25563 {
25564 	struct sd_lun		*un;
25565 	struct cdrom_volctrl    volume;
25566 	struct cdrom_volctrl    *vol = &volume;
25567 	uchar_t			*sense_page;
25568 	uchar_t			*select_page;
25569 	uchar_t			*sense;
25570 	uchar_t			*select;
25571 	int			sense_buflen;
25572 	int			select_buflen;
25573 	int			rval;
25574 
25575 	if (data == NULL) {
25576 		return (EINVAL);
25577 	}
25578 
25579 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25580 	    (un->un_state == SD_STATE_OFFLINE)) {
25581 		return (ENXIO);
25582 	}
25583 
25584 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
25585 		return (EFAULT);
25586 	}
25587 
25588 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
25589 		struct mode_header_grp2		*sense_mhp;
25590 		struct mode_header_grp2		*select_mhp;
25591 		int				bd_len;
25592 
25593 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
25594 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
25595 		    MODEPAGE_AUDIO_CTRL_LEN;
25596 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
25597 		select = kmem_zalloc(select_buflen, KM_SLEEP);
25598 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
25599 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
25600 		    SD_PATH_STANDARD)) != 0) {
25601 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25602 			    "sr_volume_ctrl: Mode Sense Failed\n");
25603 			kmem_free(sense, sense_buflen);
25604 			kmem_free(select, select_buflen);
25605 			return (rval);
25606 		}
25607 		sense_mhp = (struct mode_header_grp2 *)sense;
25608 		select_mhp = (struct mode_header_grp2 *)select;
25609 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
25610 		    sense_mhp->bdesc_length_lo;
25611 		if (bd_len > MODE_BLK_DESC_LENGTH) {
25612 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25613 			    "sr_volume_ctrl: Mode Sense returned invalid "
25614 			    "block descriptor length\n");
25615 			kmem_free(sense, sense_buflen);
25616 			kmem_free(select, select_buflen);
25617 			return (EIO);
25618 		}
25619 		sense_page = (uchar_t *)
25620 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
25621 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
25622 		select_mhp->length_msb = 0;
25623 		select_mhp->length_lsb = 0;
25624 		select_mhp->bdesc_length_hi = 0;
25625 		select_mhp->bdesc_length_lo = 0;
25626 	} else {
25627 		struct mode_header		*sense_mhp, *select_mhp;
25628 
25629 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
25630 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
25631 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
25632 		select = kmem_zalloc(select_buflen, KM_SLEEP);
25633 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
25634 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
25635 		    SD_PATH_STANDARD)) != 0) {
25636 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25637 			    "sr_volume_ctrl: Mode Sense Failed\n");
25638 			kmem_free(sense, sense_buflen);
25639 			kmem_free(select, select_buflen);
25640 			return (rval);
25641 		}
25642 		sense_mhp  = (struct mode_header *)sense;
25643 		select_mhp = (struct mode_header *)select;
25644 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
25645 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25646 			    "sr_volume_ctrl: Mode Sense returned invalid "
25647 			    "block descriptor length\n");
25648 			kmem_free(sense, sense_buflen);
25649 			kmem_free(select, select_buflen);
25650 			return (EIO);
25651 		}
25652 		sense_page = (uchar_t *)
25653 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
25654 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
25655 		select_mhp->length = 0;
25656 		select_mhp->bdesc_length = 0;
25657 	}
25658 	/*
25659 	 * Note: An audio control data structure could be created and overlayed
25660 	 * on the following in place of the array indexing method implemented.
25661 	 */
25662 
25663 	/* Build the select data for the user volume data */
25664 	select_page[0] = MODEPAGE_AUDIO_CTRL;
25665 	select_page[1] = 0xE;
25666 	/* Set the immediate bit */
25667 	select_page[2] = 0x04;
25668 	/* Zero out reserved fields */
25669 	select_page[3] = 0x00;
25670 	select_page[4] = 0x00;
25671 	/* Return sense data for fields not to be modified */
25672 	select_page[5] = sense_page[5];
25673 	select_page[6] = sense_page[6];
25674 	select_page[7] = sense_page[7];
25675 	/* Set the user specified volume levels for channel 0 and 1 */
25676 	select_page[8] = 0x01;
25677 	select_page[9] = vol->channel0;
25678 	select_page[10] = 0x02;
25679 	select_page[11] = vol->channel1;
25680 	/* Channel 2 and 3 are currently unsupported so return the sense data */
25681 	select_page[12] = sense_page[12];
25682 	select_page[13] = sense_page[13];
25683 	select_page[14] = sense_page[14];
25684 	select_page[15] = sense_page[15];
25685 
25686 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
25687 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, select,
25688 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
25689 	} else {
25690 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
25691 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
25692 	}
25693 
25694 	kmem_free(sense, sense_buflen);
25695 	kmem_free(select, select_buflen);
25696 	return (rval);
25697 }
25698 
25699 
25700 /*
25701  *    Function: sr_read_sony_session_offset()
25702  *
25703  * Description: This routine is the driver entry point for handling CD-ROM
25704  *		ioctl requests for session offset information. (CDROMREADOFFSET)
25705  *		The address of the first track in the last session of a
25706  *		multi-session CD-ROM is returned
25707  *
25708  *		Note: This routine uses a vendor specific key value in the
25709  *		command control field without implementing any vendor check here
25710  *		or in the ioctl routine.
25711  *
25712  *   Arguments: dev	- the device 'dev_t'
25713  *		data	- pointer to an int to hold the requested address
25714  *		flag	- this argument is a pass through to ddi_copyxxx()
25715  *			  directly from the mode argument of ioctl().
25716  *
25717  * Return Code: the code returned by sd_send_scsi_cmd()
25718  *		EFAULT if ddi_copyxxx() fails
25719  *		ENXIO if fail ddi_get_soft_state
25720  *		EINVAL if data pointer is NULL
25721  */
25722 
25723 static int
25724 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
25725 {
25726 	struct sd_lun		*un;
25727 	struct uscsi_cmd	*com;
25728 	caddr_t			buffer;
25729 	char			cdb[CDB_GROUP1];
25730 	int			session_offset = 0;
25731 	int			rval;
25732 
25733 	if (data == NULL) {
25734 		return (EINVAL);
25735 	}
25736 
25737 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25738 	    (un->un_state == SD_STATE_OFFLINE)) {
25739 		return (ENXIO);
25740 	}
25741 
25742 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
25743 	bzero(cdb, CDB_GROUP1);
25744 	cdb[0] = SCMD_READ_TOC;
25745 	/*
25746 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
25747 	 * (4 byte TOC response header + 8 byte response data)
25748 	 */
25749 	cdb[8] = SONY_SESSION_OFFSET_LEN;
25750 	/* Byte 9 is the control byte. A vendor specific value is used */
25751 	cdb[9] = SONY_SESSION_OFFSET_KEY;
25752 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25753 	com->uscsi_cdb = cdb;
25754 	com->uscsi_cdblen = CDB_GROUP1;
25755 	com->uscsi_bufaddr = buffer;
25756 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
25757 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25758 
25759 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25760 	    SD_PATH_STANDARD);
25761 	if (rval != 0) {
25762 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
25763 		kmem_free(com, sizeof (*com));
25764 		return (rval);
25765 	}
25766 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
25767 		session_offset =
25768 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
25769 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
25770 		/*
25771 		 * Offset returned offset in current lbasize block's. Convert to
25772 		 * 2k block's to return to the user
25773 		 */
25774 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
25775 			session_offset >>= 2;
25776 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
25777 			session_offset >>= 1;
25778 		}
25779 	}
25780 
25781 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
25782 		rval = EFAULT;
25783 	}
25784 
25785 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
25786 	kmem_free(com, sizeof (*com));
25787 	return (rval);
25788 }
25789 
25790 
25791 /*
25792  *    Function: sd_wm_cache_constructor()
25793  *
25794  * Description: Cache Constructor for the wmap cache for the read/modify/write
25795  * 		devices.
25796  *
25797  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
25798  *		un	- sd_lun structure for the device.
25799  *		flag	- the km flags passed to constructor
25800  *
25801  * Return Code: 0 on success.
25802  *		-1 on failure.
25803  */
25804 
25805 /*ARGSUSED*/
25806 static int
25807 sd_wm_cache_constructor(void *wm, void *un, int flags)
25808 {
25809 	bzero(wm, sizeof (struct sd_w_map));
25810 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
25811 	return (0);
25812 }
25813 
25814 
25815 /*
25816  *    Function: sd_wm_cache_destructor()
25817  *
25818  * Description: Cache destructor for the wmap cache for the read/modify/write
25819  * 		devices.
25820  *
25821  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
25822  *		un	- sd_lun structure for the device.
25823  */
25824 /*ARGSUSED*/
25825 static void
25826 sd_wm_cache_destructor(void *wm, void *un)
25827 {
25828 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
25829 }
25830 
25831 
25832 /*
25833  *    Function: sd_range_lock()
25834  *
25835  * Description: Lock the range of blocks specified as parameter to ensure
25836  *		that read, modify write is atomic and no other i/o writes
25837  *		to the same location. The range is specified in terms
25838  *		of start and end blocks. Block numbers are the actual
25839  *		media block numbers and not system.
25840  *
25841  *   Arguments: un	- sd_lun structure for the device.
25842  *		startb - The starting block number
25843  *		endb - The end block number
25844  *		typ - type of i/o - simple/read_modify_write
25845  *
25846  * Return Code: wm  - pointer to the wmap structure.
25847  *
25848  *     Context: This routine can sleep.
25849  */
25850 
25851 static struct sd_w_map *
25852 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
25853 {
25854 	struct sd_w_map *wmp = NULL;
25855 	struct sd_w_map *sl_wmp = NULL;
25856 	struct sd_w_map *tmp_wmp;
25857 	wm_state state = SD_WM_CHK_LIST;
25858 
25859 
25860 	ASSERT(un != NULL);
25861 	ASSERT(!mutex_owned(SD_MUTEX(un)));
25862 
25863 	mutex_enter(SD_MUTEX(un));
25864 
25865 	while (state != SD_WM_DONE) {
25866 
25867 		switch (state) {
25868 		case SD_WM_CHK_LIST:
25869 			/*
25870 			 * This is the starting state. Check the wmap list
25871 			 * to see if the range is currently available.
25872 			 */
25873 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
25874 				/*
25875 				 * If this is a simple write and no rmw
25876 				 * i/o is pending then try to lock the
25877 				 * range as the range should be available.
25878 				 */
25879 				state = SD_WM_LOCK_RANGE;
25880 			} else {
25881 				tmp_wmp = sd_get_range(un, startb, endb);
25882 				if (tmp_wmp != NULL) {
25883 					if ((wmp != NULL) && ONLIST(un, wmp)) {
25884 						/*
25885 						 * Should not keep onlist wmps
25886 						 * while waiting this macro
25887 						 * will also do wmp = NULL;
25888 						 */
25889 						FREE_ONLIST_WMAP(un, wmp);
25890 					}
25891 					/*
25892 					 * sl_wmp is the wmap on which wait
25893 					 * is done, since the tmp_wmp points
25894 					 * to the inuse wmap, set sl_wmp to
25895 					 * tmp_wmp and change the state to sleep
25896 					 */
25897 					sl_wmp = tmp_wmp;
25898 					state = SD_WM_WAIT_MAP;
25899 				} else {
25900 					state = SD_WM_LOCK_RANGE;
25901 				}
25902 
25903 			}
25904 			break;
25905 
25906 		case SD_WM_LOCK_RANGE:
25907 			ASSERT(un->un_wm_cache);
25908 			/*
25909 			 * The range need to be locked, try to get a wmap.
25910 			 * First attempt it with NO_SLEEP, want to avoid a sleep
25911 			 * if possible as we will have to release the sd mutex
25912 			 * if we have to sleep.
25913 			 */
25914 			if (wmp == NULL)
25915 				wmp = kmem_cache_alloc(un->un_wm_cache,
25916 				    KM_NOSLEEP);
25917 			if (wmp == NULL) {
25918 				mutex_exit(SD_MUTEX(un));
25919 				_NOTE(DATA_READABLE_WITHOUT_LOCK
25920 				    (sd_lun::un_wm_cache))
25921 				wmp = kmem_cache_alloc(un->un_wm_cache,
25922 				    KM_SLEEP);
25923 				mutex_enter(SD_MUTEX(un));
25924 				/*
25925 				 * we released the mutex so recheck and go to
25926 				 * check list state.
25927 				 */
25928 				state = SD_WM_CHK_LIST;
25929 			} else {
25930 				/*
25931 				 * We exit out of state machine since we
25932 				 * have the wmap. Do the housekeeping first.
25933 				 * place the wmap on the wmap list if it is not
25934 				 * on it already and then set the state to done.
25935 				 */
25936 				wmp->wm_start = startb;
25937 				wmp->wm_end = endb;
25938 				wmp->wm_flags = typ | SD_WM_BUSY;
25939 				if (typ & SD_WTYPE_RMW) {
25940 					un->un_rmw_count++;
25941 				}
25942 				/*
25943 				 * If not already on the list then link
25944 				 */
25945 				if (!ONLIST(un, wmp)) {
25946 					wmp->wm_next = un->un_wm;
25947 					wmp->wm_prev = NULL;
25948 					if (wmp->wm_next)
25949 						wmp->wm_next->wm_prev = wmp;
25950 					un->un_wm = wmp;
25951 				}
25952 				state = SD_WM_DONE;
25953 			}
25954 			break;
25955 
25956 		case SD_WM_WAIT_MAP:
25957 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
25958 			/*
25959 			 * Wait is done on sl_wmp, which is set in the
25960 			 * check_list state.
25961 			 */
25962 			sl_wmp->wm_wanted_count++;
25963 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
25964 			sl_wmp->wm_wanted_count--;
25965 			/*
25966 			 * We can reuse the memory from the completed sl_wmp
25967 			 * lock range for our new lock, but only if noone is
25968 			 * waiting for it.
25969 			 */
25970 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
25971 			if (sl_wmp->wm_wanted_count == 0) {
25972 				if (wmp != NULL)
25973 					CHK_N_FREEWMP(un, wmp);
25974 				wmp = sl_wmp;
25975 			}
25976 			sl_wmp = NULL;
25977 			/*
25978 			 * After waking up, need to recheck for availability of
25979 			 * range.
25980 			 */
25981 			state = SD_WM_CHK_LIST;
25982 			break;
25983 
25984 		default:
25985 			panic("sd_range_lock: "
25986 			    "Unknown state %d in sd_range_lock", state);
25987 			/*NOTREACHED*/
25988 		} /* switch(state) */
25989 
25990 	} /* while(state != SD_WM_DONE) */
25991 
25992 	mutex_exit(SD_MUTEX(un));
25993 
25994 	ASSERT(wmp != NULL);
25995 
25996 	return (wmp);
25997 }
25998 
25999 
26000 /*
26001  *    Function: sd_get_range()
26002  *
26003  * Description: Find if there any overlapping I/O to this one
26004  *		Returns the write-map of 1st such I/O, NULL otherwise.
26005  *
26006  *   Arguments: un	- sd_lun structure for the device.
26007  *		startb - The starting block number
26008  *		endb - The end block number
26009  *
26010  * Return Code: wm  - pointer to the wmap structure.
26011  */
26012 
26013 static struct sd_w_map *
26014 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
26015 {
26016 	struct sd_w_map *wmp;
26017 
26018 	ASSERT(un != NULL);
26019 
26020 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
26021 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
26022 			continue;
26023 		}
26024 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
26025 			break;
26026 		}
26027 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
26028 			break;
26029 		}
26030 	}
26031 
26032 	return (wmp);
26033 }
26034 
26035 
26036 /*
26037  *    Function: sd_free_inlist_wmap()
26038  *
26039  * Description: Unlink and free a write map struct.
26040  *
26041  *   Arguments: un      - sd_lun structure for the device.
26042  *		wmp	- sd_w_map which needs to be unlinked.
26043  */
26044 
26045 static void
26046 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
26047 {
26048 	ASSERT(un != NULL);
26049 
26050 	if (un->un_wm == wmp) {
26051 		un->un_wm = wmp->wm_next;
26052 	} else {
26053 		wmp->wm_prev->wm_next = wmp->wm_next;
26054 	}
26055 
26056 	if (wmp->wm_next) {
26057 		wmp->wm_next->wm_prev = wmp->wm_prev;
26058 	}
26059 
26060 	wmp->wm_next = wmp->wm_prev = NULL;
26061 
26062 	kmem_cache_free(un->un_wm_cache, wmp);
26063 }
26064 
26065 
26066 /*
26067  *    Function: sd_range_unlock()
26068  *
26069  * Description: Unlock the range locked by wm.
26070  *		Free write map if nobody else is waiting on it.
26071  *
26072  *   Arguments: un      - sd_lun structure for the device.
26073  *              wmp     - sd_w_map which needs to be unlinked.
26074  */
26075 
26076 static void
26077 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
26078 {
26079 	ASSERT(un != NULL);
26080 	ASSERT(wm != NULL);
26081 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26082 
26083 	mutex_enter(SD_MUTEX(un));
26084 
26085 	if (wm->wm_flags & SD_WTYPE_RMW) {
26086 		un->un_rmw_count--;
26087 	}
26088 
26089 	if (wm->wm_wanted_count) {
26090 		wm->wm_flags = 0;
26091 		/*
26092 		 * Broadcast that the wmap is available now.
26093 		 */
26094 		cv_broadcast(&wm->wm_avail);
26095 	} else {
26096 		/*
26097 		 * If no one is waiting on the map, it should be free'ed.
26098 		 */
26099 		sd_free_inlist_wmap(un, wm);
26100 	}
26101 
26102 	mutex_exit(SD_MUTEX(un));
26103 }
26104 
26105 
26106 /*
26107  *    Function: sd_read_modify_write_task
26108  *
26109  * Description: Called from a taskq thread to initiate the write phase of
26110  *		a read-modify-write request.  This is used for targets where
26111  *		un->un_sys_blocksize != un->un_tgt_blocksize.
26112  *
26113  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
26114  *
26115  *     Context: Called under taskq thread context.
26116  */
26117 
26118 static void
26119 sd_read_modify_write_task(void *arg)
26120 {
26121 	struct sd_mapblocksize_info	*bsp;
26122 	struct buf	*bp;
26123 	struct sd_xbuf	*xp;
26124 	struct sd_lun	*un;
26125 
26126 	bp = arg;	/* The bp is given in arg */
26127 	ASSERT(bp != NULL);
26128 
26129 	/* Get the pointer to the layer-private data struct */
26130 	xp = SD_GET_XBUF(bp);
26131 	ASSERT(xp != NULL);
26132 	bsp = xp->xb_private;
26133 	ASSERT(bsp != NULL);
26134 
26135 	un = SD_GET_UN(bp);
26136 	ASSERT(un != NULL);
26137 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26138 
26139 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26140 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
26141 
26142 	/*
26143 	 * This is the write phase of a read-modify-write request, called
26144 	 * under the context of a taskq thread in response to the completion
26145 	 * of the read portion of the rmw request completing under interrupt
26146 	 * context. The write request must be sent from here down the iostart
26147 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
26148 	 * we use the layer index saved in the layer-private data area.
26149 	 */
26150 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
26151 
26152 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26153 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
26154 }
26155 
26156 
26157 /*
26158  *    Function: sddump_do_read_of_rmw()
26159  *
26160  * Description: This routine will be called from sddump, If sddump is called
26161  *		with an I/O which not aligned on device blocksize boundary
26162  *		then the write has to be converted to read-modify-write.
26163  *		Do the read part here in order to keep sddump simple.
26164  *		Note - That the sd_mutex is held across the call to this
26165  *		routine.
26166  *
26167  *   Arguments: un	- sd_lun
26168  *		blkno	- block number in terms of media block size.
26169  *		nblk	- number of blocks.
26170  *		bpp	- pointer to pointer to the buf structure. On return
26171  *			from this function, *bpp points to the valid buffer
26172  *			to which the write has to be done.
26173  *
26174  * Return Code: 0 for success or errno-type return code
26175  */
26176 
26177 static int
26178 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
26179 	struct buf **bpp)
26180 {
26181 	int err;
26182 	int i;
26183 	int rval;
26184 	struct buf *bp;
26185 	struct scsi_pkt *pkt = NULL;
26186 	uint32_t target_blocksize;
26187 
26188 	ASSERT(un != NULL);
26189 	ASSERT(mutex_owned(SD_MUTEX(un)));
26190 
26191 	target_blocksize = un->un_tgt_blocksize;
26192 
26193 	mutex_exit(SD_MUTEX(un));
26194 
26195 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
26196 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
26197 	if (bp == NULL) {
26198 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26199 		    "no resources for dumping; giving up");
26200 		err = ENOMEM;
26201 		goto done;
26202 	}
26203 
26204 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
26205 	    blkno, nblk);
26206 	if (rval != 0) {
26207 		scsi_free_consistent_buf(bp);
26208 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26209 		    "no resources for dumping; giving up");
26210 		err = ENOMEM;
26211 		goto done;
26212 	}
26213 
26214 	pkt->pkt_flags |= FLAG_NOINTR;
26215 
26216 	err = EIO;
26217 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26218 
26219 		/*
26220 		 * Scsi_poll returns 0 (success) if the command completes and
26221 		 * the status block is STATUS_GOOD.  We should only check
26222 		 * errors if this condition is not true.  Even then we should
26223 		 * send our own request sense packet only if we have a check
26224 		 * condition and auto request sense has not been performed by
26225 		 * the hba.
26226 		 */
26227 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
26228 
26229 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
26230 			err = 0;
26231 			break;
26232 		}
26233 
26234 		/*
26235 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
26236 		 * no need to read RQS data.
26237 		 */
26238 		if (pkt->pkt_reason == CMD_DEV_GONE) {
26239 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
26240 			    "Device is gone\n");
26241 			break;
26242 		}
26243 
26244 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
26245 			SD_INFO(SD_LOG_DUMP, un,
26246 			    "sddump: read failed with CHECK, try # %d\n", i);
26247 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
26248 				(void) sd_send_polled_RQS(un);
26249 			}
26250 
26251 			continue;
26252 		}
26253 
26254 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
26255 			int reset_retval = 0;
26256 
26257 			SD_INFO(SD_LOG_DUMP, un,
26258 			    "sddump: read failed with BUSY, try # %d\n", i);
26259 
26260 			if (un->un_f_lun_reset_enabled == TRUE) {
26261 				reset_retval = scsi_reset(SD_ADDRESS(un),
26262 				    RESET_LUN);
26263 			}
26264 			if (reset_retval == 0) {
26265 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26266 			}
26267 			(void) sd_send_polled_RQS(un);
26268 
26269 		} else {
26270 			SD_INFO(SD_LOG_DUMP, un,
26271 			    "sddump: read failed with 0x%x, try # %d\n",
26272 			    SD_GET_PKT_STATUS(pkt), i);
26273 			mutex_enter(SD_MUTEX(un));
26274 			sd_reset_target(un, pkt);
26275 			mutex_exit(SD_MUTEX(un));
26276 		}
26277 
26278 		/*
26279 		 * If we are not getting anywhere with lun/target resets,
26280 		 * let's reset the bus.
26281 		 */
26282 		if (i > SD_NDUMP_RETRIES/2) {
26283 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26284 			(void) sd_send_polled_RQS(un);
26285 		}
26286 
26287 	}
26288 	scsi_destroy_pkt(pkt);
26289 
26290 	if (err != 0) {
26291 		scsi_free_consistent_buf(bp);
26292 		*bpp = NULL;
26293 	} else {
26294 		*bpp = bp;
26295 	}
26296 
26297 done:
26298 	mutex_enter(SD_MUTEX(un));
26299 	return (err);
26300 }
26301 
26302 
26303 /*
26304  *    Function: sd_failfast_flushq
26305  *
26306  * Description: Take all bp's on the wait queue that have B_FAILFAST set
26307  *		in b_flags and move them onto the failfast queue, then kick
26308  *		off a thread to return all bp's on the failfast queue to
26309  *		their owners with an error set.
26310  *
26311  *   Arguments: un - pointer to the soft state struct for the instance.
26312  *
26313  *     Context: may execute in interrupt context.
26314  */
26315 
26316 static void
26317 sd_failfast_flushq(struct sd_lun *un)
26318 {
26319 	struct buf *bp;
26320 	struct buf *next_waitq_bp;
26321 	struct buf *prev_waitq_bp = NULL;
26322 
26323 	ASSERT(un != NULL);
26324 	ASSERT(mutex_owned(SD_MUTEX(un)));
26325 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
26326 	ASSERT(un->un_failfast_bp == NULL);
26327 
26328 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
26329 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
26330 
26331 	/*
26332 	 * Check if we should flush all bufs when entering failfast state, or
26333 	 * just those with B_FAILFAST set.
26334 	 */
26335 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
26336 		/*
26337 		 * Move *all* bp's on the wait queue to the failfast flush
26338 		 * queue, including those that do NOT have B_FAILFAST set.
26339 		 */
26340 		if (un->un_failfast_headp == NULL) {
26341 			ASSERT(un->un_failfast_tailp == NULL);
26342 			un->un_failfast_headp = un->un_waitq_headp;
26343 		} else {
26344 			ASSERT(un->un_failfast_tailp != NULL);
26345 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
26346 		}
26347 
26348 		un->un_failfast_tailp = un->un_waitq_tailp;
26349 
26350 		/* update kstat for each bp moved out of the waitq */
26351 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
26352 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
26353 		}
26354 
26355 		/* empty the waitq */
26356 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
26357 
26358 	} else {
26359 		/*
26360 		 * Go thru the wait queue, pick off all entries with
26361 		 * B_FAILFAST set, and move these onto the failfast queue.
26362 		 */
26363 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
26364 			/*
26365 			 * Save the pointer to the next bp on the wait queue,
26366 			 * so we get to it on the next iteration of this loop.
26367 			 */
26368 			next_waitq_bp = bp->av_forw;
26369 
26370 			/*
26371 			 * If this bp from the wait queue does NOT have
26372 			 * B_FAILFAST set, just move on to the next element
26373 			 * in the wait queue. Note, this is the only place
26374 			 * where it is correct to set prev_waitq_bp.
26375 			 */
26376 			if ((bp->b_flags & B_FAILFAST) == 0) {
26377 				prev_waitq_bp = bp;
26378 				continue;
26379 			}
26380 
26381 			/*
26382 			 * Remove the bp from the wait queue.
26383 			 */
26384 			if (bp == un->un_waitq_headp) {
26385 				/* The bp is the first element of the waitq. */
26386 				un->un_waitq_headp = next_waitq_bp;
26387 				if (un->un_waitq_headp == NULL) {
26388 					/* The wait queue is now empty */
26389 					un->un_waitq_tailp = NULL;
26390 				}
26391 			} else {
26392 				/*
26393 				 * The bp is either somewhere in the middle
26394 				 * or at the end of the wait queue.
26395 				 */
26396 				ASSERT(un->un_waitq_headp != NULL);
26397 				ASSERT(prev_waitq_bp != NULL);
26398 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
26399 				    == 0);
26400 				if (bp == un->un_waitq_tailp) {
26401 					/* bp is the last entry on the waitq. */
26402 					ASSERT(next_waitq_bp == NULL);
26403 					un->un_waitq_tailp = prev_waitq_bp;
26404 				}
26405 				prev_waitq_bp->av_forw = next_waitq_bp;
26406 			}
26407 			bp->av_forw = NULL;
26408 
26409 			/*
26410 			 * update kstat since the bp is moved out of
26411 			 * the waitq
26412 			 */
26413 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
26414 
26415 			/*
26416 			 * Now put the bp onto the failfast queue.
26417 			 */
26418 			if (un->un_failfast_headp == NULL) {
26419 				/* failfast queue is currently empty */
26420 				ASSERT(un->un_failfast_tailp == NULL);
26421 				un->un_failfast_headp =
26422 				    un->un_failfast_tailp = bp;
26423 			} else {
26424 				/* Add the bp to the end of the failfast q */
26425 				ASSERT(un->un_failfast_tailp != NULL);
26426 				ASSERT(un->un_failfast_tailp->b_flags &
26427 				    B_FAILFAST);
26428 				un->un_failfast_tailp->av_forw = bp;
26429 				un->un_failfast_tailp = bp;
26430 			}
26431 		}
26432 	}
26433 
26434 	/*
26435 	 * Now return all bp's on the failfast queue to their owners.
26436 	 */
26437 	while ((bp = un->un_failfast_headp) != NULL) {
26438 
26439 		un->un_failfast_headp = bp->av_forw;
26440 		if (un->un_failfast_headp == NULL) {
26441 			un->un_failfast_tailp = NULL;
26442 		}
26443 
26444 		/*
26445 		 * We want to return the bp with a failure error code, but
26446 		 * we do not want a call to sd_start_cmds() to occur here,
26447 		 * so use sd_return_failed_command_no_restart() instead of
26448 		 * sd_return_failed_command().
26449 		 */
26450 		sd_return_failed_command_no_restart(un, bp, EIO);
26451 	}
26452 
26453 	/* Flush the xbuf queues if required. */
26454 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
26455 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
26456 	}
26457 
26458 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
26459 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
26460 }
26461 
26462 
26463 /*
26464  *    Function: sd_failfast_flushq_callback
26465  *
26466  * Description: Return TRUE if the given bp meets the criteria for failfast
26467  *		flushing. Used with ddi_xbuf_flushq(9F).
26468  *
26469  *   Arguments: bp - ptr to buf struct to be examined.
26470  *
26471  *     Context: Any
26472  */
26473 
26474 static int
26475 sd_failfast_flushq_callback(struct buf *bp)
26476 {
26477 	/*
26478 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
26479 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
26480 	 */
26481 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
26482 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
26483 }
26484 
26485 
26486 
26487 #if defined(__i386) || defined(__amd64)
26488 /*
26489  * Function: sd_setup_next_xfer
26490  *
26491  * Description: Prepare next I/O operation using DMA_PARTIAL
26492  *
26493  */
26494 
26495 static int
26496 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
26497     struct scsi_pkt *pkt, struct sd_xbuf *xp)
26498 {
26499 	ssize_t	num_blks_not_xfered;
26500 	daddr_t	strt_blk_num;
26501 	ssize_t	bytes_not_xfered;
26502 	int	rval;
26503 
26504 	ASSERT(pkt->pkt_resid == 0);
26505 
26506 	/*
26507 	 * Calculate next block number and amount to be transferred.
26508 	 *
26509 	 * How much data NOT transfered to the HBA yet.
26510 	 */
26511 	bytes_not_xfered = xp->xb_dma_resid;
26512 
26513 	/*
26514 	 * figure how many blocks NOT transfered to the HBA yet.
26515 	 */
26516 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
26517 
26518 	/*
26519 	 * set starting block number to the end of what WAS transfered.
26520 	 */
26521 	strt_blk_num = xp->xb_blkno +
26522 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
26523 
26524 	/*
26525 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
26526 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
26527 	 * the disk mutex here.
26528 	 */
26529 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
26530 	    strt_blk_num, num_blks_not_xfered);
26531 
26532 	if (rval == 0) {
26533 
26534 		/*
26535 		 * Success.
26536 		 *
26537 		 * Adjust things if there are still more blocks to be
26538 		 * transfered.
26539 		 */
26540 		xp->xb_dma_resid = pkt->pkt_resid;
26541 		pkt->pkt_resid = 0;
26542 
26543 		return (1);
26544 	}
26545 
26546 	/*
26547 	 * There's really only one possible return value from
26548 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
26549 	 * returns NULL.
26550 	 */
26551 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
26552 
26553 	bp->b_resid = bp->b_bcount;
26554 	bp->b_flags |= B_ERROR;
26555 
26556 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26557 	    "Error setting up next portion of DMA transfer\n");
26558 
26559 	return (0);
26560 }
26561 #endif
26562 
26563 /*
26564  *    Function: sd_panic_for_res_conflict
26565  *
26566  * Description: Call panic with a string formatted with "Reservation Conflict"
26567  *		and a human readable identifier indicating the SD instance
26568  *		that experienced the reservation conflict.
26569  *
26570  *   Arguments: un - pointer to the soft state struct for the instance.
26571  *
26572  *     Context: may execute in interrupt context.
26573  */
26574 
26575 #define	SD_RESV_CONFLICT_FMT_LEN 40
26576 void
26577 sd_panic_for_res_conflict(struct sd_lun *un)
26578 {
26579 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
26580 	char path_str[MAXPATHLEN];
26581 
26582 	(void) snprintf(panic_str, sizeof (panic_str),
26583 	    "Reservation Conflict\nDisk: %s",
26584 	    ddi_pathname(SD_DEVINFO(un), path_str));
26585 
26586 	panic(panic_str);
26587 }
26588 
26589 /*
26590  * Note: The following sd_faultinjection_ioctl( ) routines implement
26591  * driver support for handling fault injection for error analysis
26592  * causing faults in multiple layers of the driver.
26593  *
26594  */
26595 
26596 #ifdef SD_FAULT_INJECTION
26597 static uint_t   sd_fault_injection_on = 0;
26598 
26599 /*
26600  *    Function: sd_faultinjection_ioctl()
26601  *
26602  * Description: This routine is the driver entry point for handling
26603  *              faultinjection ioctls to inject errors into the
26604  *              layer model
26605  *
26606  *   Arguments: cmd	- the ioctl cmd received
26607  *		arg	- the arguments from user and returns
26608  */
26609 
26610 static void
26611 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
26612 
26613 	uint_t i;
26614 	uint_t rval;
26615 
26616 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
26617 
26618 	mutex_enter(SD_MUTEX(un));
26619 
26620 	switch (cmd) {
26621 	case SDIOCRUN:
26622 		/* Allow pushed faults to be injected */
26623 		SD_INFO(SD_LOG_SDTEST, un,
26624 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
26625 
26626 		sd_fault_injection_on = 1;
26627 
26628 		SD_INFO(SD_LOG_IOERR, un,
26629 		    "sd_faultinjection_ioctl: run finished\n");
26630 		break;
26631 
26632 	case SDIOCSTART:
26633 		/* Start Injection Session */
26634 		SD_INFO(SD_LOG_SDTEST, un,
26635 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
26636 
26637 		sd_fault_injection_on = 0;
26638 		un->sd_injection_mask = 0xFFFFFFFF;
26639 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
26640 			un->sd_fi_fifo_pkt[i] = NULL;
26641 			un->sd_fi_fifo_xb[i] = NULL;
26642 			un->sd_fi_fifo_un[i] = NULL;
26643 			un->sd_fi_fifo_arq[i] = NULL;
26644 		}
26645 		un->sd_fi_fifo_start = 0;
26646 		un->sd_fi_fifo_end = 0;
26647 
26648 		mutex_enter(&(un->un_fi_mutex));
26649 		un->sd_fi_log[0] = '\0';
26650 		un->sd_fi_buf_len = 0;
26651 		mutex_exit(&(un->un_fi_mutex));
26652 
26653 		SD_INFO(SD_LOG_IOERR, un,
26654 		    "sd_faultinjection_ioctl: start finished\n");
26655 		break;
26656 
26657 	case SDIOCSTOP:
26658 		/* Stop Injection Session */
26659 		SD_INFO(SD_LOG_SDTEST, un,
26660 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
26661 		sd_fault_injection_on = 0;
26662 		un->sd_injection_mask = 0x0;
26663 
26664 		/* Empty stray or unuseds structs from fifo */
26665 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
26666 			if (un->sd_fi_fifo_pkt[i] != NULL) {
26667 				kmem_free(un->sd_fi_fifo_pkt[i],
26668 				    sizeof (struct sd_fi_pkt));
26669 			}
26670 			if (un->sd_fi_fifo_xb[i] != NULL) {
26671 				kmem_free(un->sd_fi_fifo_xb[i],
26672 				    sizeof (struct sd_fi_xb));
26673 			}
26674 			if (un->sd_fi_fifo_un[i] != NULL) {
26675 				kmem_free(un->sd_fi_fifo_un[i],
26676 				    sizeof (struct sd_fi_un));
26677 			}
26678 			if (un->sd_fi_fifo_arq[i] != NULL) {
26679 				kmem_free(un->sd_fi_fifo_arq[i],
26680 				    sizeof (struct sd_fi_arq));
26681 			}
26682 			un->sd_fi_fifo_pkt[i] = NULL;
26683 			un->sd_fi_fifo_un[i] = NULL;
26684 			un->sd_fi_fifo_xb[i] = NULL;
26685 			un->sd_fi_fifo_arq[i] = NULL;
26686 		}
26687 		un->sd_fi_fifo_start = 0;
26688 		un->sd_fi_fifo_end = 0;
26689 
26690 		SD_INFO(SD_LOG_IOERR, un,
26691 		    "sd_faultinjection_ioctl: stop finished\n");
26692 		break;
26693 
26694 	case SDIOCINSERTPKT:
26695 		/* Store a packet struct to be pushed onto fifo */
26696 		SD_INFO(SD_LOG_SDTEST, un,
26697 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
26698 
26699 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
26700 
26701 		sd_fault_injection_on = 0;
26702 
26703 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
26704 		if (un->sd_fi_fifo_pkt[i] != NULL) {
26705 			kmem_free(un->sd_fi_fifo_pkt[i],
26706 			    sizeof (struct sd_fi_pkt));
26707 		}
26708 		if (arg != NULL) {
26709 			un->sd_fi_fifo_pkt[i] =
26710 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
26711 			if (un->sd_fi_fifo_pkt[i] == NULL) {
26712 				/* Alloc failed don't store anything */
26713 				break;
26714 			}
26715 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
26716 			    sizeof (struct sd_fi_pkt), 0);
26717 			if (rval == -1) {
26718 				kmem_free(un->sd_fi_fifo_pkt[i],
26719 				    sizeof (struct sd_fi_pkt));
26720 				un->sd_fi_fifo_pkt[i] = NULL;
26721 			}
26722 		} else {
26723 			SD_INFO(SD_LOG_IOERR, un,
26724 			    "sd_faultinjection_ioctl: pkt null\n");
26725 		}
26726 		break;
26727 
26728 	case SDIOCINSERTXB:
26729 		/* Store a xb struct to be pushed onto fifo */
26730 		SD_INFO(SD_LOG_SDTEST, un,
26731 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
26732 
26733 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
26734 
26735 		sd_fault_injection_on = 0;
26736 
26737 		if (un->sd_fi_fifo_xb[i] != NULL) {
26738 			kmem_free(un->sd_fi_fifo_xb[i],
26739 			    sizeof (struct sd_fi_xb));
26740 			un->sd_fi_fifo_xb[i] = NULL;
26741 		}
26742 		if (arg != NULL) {
26743 			un->sd_fi_fifo_xb[i] =
26744 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
26745 			if (un->sd_fi_fifo_xb[i] == NULL) {
26746 				/* Alloc failed don't store anything */
26747 				break;
26748 			}
26749 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
26750 			    sizeof (struct sd_fi_xb), 0);
26751 
26752 			if (rval == -1) {
26753 				kmem_free(un->sd_fi_fifo_xb[i],
26754 				    sizeof (struct sd_fi_xb));
26755 				un->sd_fi_fifo_xb[i] = NULL;
26756 			}
26757 		} else {
26758 			SD_INFO(SD_LOG_IOERR, un,
26759 			    "sd_faultinjection_ioctl: xb null\n");
26760 		}
26761 		break;
26762 
26763 	case SDIOCINSERTUN:
26764 		/* Store a un struct to be pushed onto fifo */
26765 		SD_INFO(SD_LOG_SDTEST, un,
26766 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
26767 
26768 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
26769 
26770 		sd_fault_injection_on = 0;
26771 
26772 		if (un->sd_fi_fifo_un[i] != NULL) {
26773 			kmem_free(un->sd_fi_fifo_un[i],
26774 			    sizeof (struct sd_fi_un));
26775 			un->sd_fi_fifo_un[i] = NULL;
26776 		}
26777 		if (arg != NULL) {
26778 			un->sd_fi_fifo_un[i] =
26779 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
26780 			if (un->sd_fi_fifo_un[i] == NULL) {
26781 				/* Alloc failed don't store anything */
26782 				break;
26783 			}
26784 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
26785 			    sizeof (struct sd_fi_un), 0);
26786 			if (rval == -1) {
26787 				kmem_free(un->sd_fi_fifo_un[i],
26788 				    sizeof (struct sd_fi_un));
26789 				un->sd_fi_fifo_un[i] = NULL;
26790 			}
26791 
26792 		} else {
26793 			SD_INFO(SD_LOG_IOERR, un,
26794 			    "sd_faultinjection_ioctl: un null\n");
26795 		}
26796 
26797 		break;
26798 
26799 	case SDIOCINSERTARQ:
26800 		/* Store a arq struct to be pushed onto fifo */
26801 		SD_INFO(SD_LOG_SDTEST, un,
26802 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
26803 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
26804 
26805 		sd_fault_injection_on = 0;
26806 
26807 		if (un->sd_fi_fifo_arq[i] != NULL) {
26808 			kmem_free(un->sd_fi_fifo_arq[i],
26809 			    sizeof (struct sd_fi_arq));
26810 			un->sd_fi_fifo_arq[i] = NULL;
26811 		}
26812 		if (arg != NULL) {
26813 			un->sd_fi_fifo_arq[i] =
26814 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
26815 			if (un->sd_fi_fifo_arq[i] == NULL) {
26816 				/* Alloc failed don't store anything */
26817 				break;
26818 			}
26819 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
26820 			    sizeof (struct sd_fi_arq), 0);
26821 			if (rval == -1) {
26822 				kmem_free(un->sd_fi_fifo_arq[i],
26823 				    sizeof (struct sd_fi_arq));
26824 				un->sd_fi_fifo_arq[i] = NULL;
26825 			}
26826 
26827 		} else {
26828 			SD_INFO(SD_LOG_IOERR, un,
26829 			    "sd_faultinjection_ioctl: arq null\n");
26830 		}
26831 
26832 		break;
26833 
26834 	case SDIOCPUSH:
26835 		/* Push stored xb, pkt, un, and arq onto fifo */
26836 		sd_fault_injection_on = 0;
26837 
26838 		if (arg != NULL) {
26839 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
26840 			if (rval != -1 &&
26841 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
26842 				un->sd_fi_fifo_end += i;
26843 			}
26844 		} else {
26845 			SD_INFO(SD_LOG_IOERR, un,
26846 			    "sd_faultinjection_ioctl: push arg null\n");
26847 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
26848 				un->sd_fi_fifo_end++;
26849 			}
26850 		}
26851 		SD_INFO(SD_LOG_IOERR, un,
26852 		    "sd_faultinjection_ioctl: push to end=%d\n",
26853 		    un->sd_fi_fifo_end);
26854 		break;
26855 
26856 	case SDIOCRETRIEVE:
26857 		/* Return buffer of log from Injection session */
26858 		SD_INFO(SD_LOG_SDTEST, un,
26859 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
26860 
26861 		sd_fault_injection_on = 0;
26862 
26863 		mutex_enter(&(un->un_fi_mutex));
26864 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
26865 		    un->sd_fi_buf_len+1, 0);
26866 		mutex_exit(&(un->un_fi_mutex));
26867 
26868 		if (rval == -1) {
26869 			/*
26870 			 * arg is possibly invalid setting
26871 			 * it to NULL for return
26872 			 */
26873 			arg = NULL;
26874 		}
26875 		break;
26876 	}
26877 
26878 	mutex_exit(SD_MUTEX(un));
26879 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
26880 			    " exit\n");
26881 }
26882 
26883 
26884 /*
26885  *    Function: sd_injection_log()
26886  *
26887  * Description: This routine adds buff to the already existing injection log
26888  *              for retrieval via faultinjection_ioctl for use in fault
26889  *              detection and recovery
26890  *
26891  *   Arguments: buf - the string to add to the log
26892  */
26893 
26894 static void
26895 sd_injection_log(char *buf, struct sd_lun *un)
26896 {
26897 	uint_t len;
26898 
26899 	ASSERT(un != NULL);
26900 	ASSERT(buf != NULL);
26901 
26902 	mutex_enter(&(un->un_fi_mutex));
26903 
26904 	len = min(strlen(buf), 255);
26905 	/* Add logged value to Injection log to be returned later */
26906 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
26907 		uint_t	offset = strlen((char *)un->sd_fi_log);
26908 		char *destp = (char *)un->sd_fi_log + offset;
26909 		int i;
26910 		for (i = 0; i < len; i++) {
26911 			*destp++ = *buf++;
26912 		}
26913 		un->sd_fi_buf_len += len;
26914 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
26915 	}
26916 
26917 	mutex_exit(&(un->un_fi_mutex));
26918 }
26919 
26920 
26921 /*
26922  *    Function: sd_faultinjection()
26923  *
26924  * Description: This routine takes the pkt and changes its
26925  *		content based on error injection scenerio.
26926  *
26927  *   Arguments: pktp	- packet to be changed
26928  */
26929 
26930 static void
26931 sd_faultinjection(struct scsi_pkt *pktp)
26932 {
26933 	uint_t i;
26934 	struct sd_fi_pkt *fi_pkt;
26935 	struct sd_fi_xb *fi_xb;
26936 	struct sd_fi_un *fi_un;
26937 	struct sd_fi_arq *fi_arq;
26938 	struct buf *bp;
26939 	struct sd_xbuf *xb;
26940 	struct sd_lun *un;
26941 
26942 	ASSERT(pktp != NULL);
26943 
26944 	/* pull bp xb and un from pktp */
26945 	bp = (struct buf *)pktp->pkt_private;
26946 	xb = SD_GET_XBUF(bp);
26947 	un = SD_GET_UN(bp);
26948 
26949 	ASSERT(un != NULL);
26950 
26951 	mutex_enter(SD_MUTEX(un));
26952 
26953 	SD_TRACE(SD_LOG_SDTEST, un,
26954 	    "sd_faultinjection: entry Injection from sdintr\n");
26955 
26956 	/* if injection is off return */
26957 	if (sd_fault_injection_on == 0 ||
26958 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
26959 		mutex_exit(SD_MUTEX(un));
26960 		return;
26961 	}
26962 
26963 
26964 	/* take next set off fifo */
26965 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
26966 
26967 	fi_pkt = un->sd_fi_fifo_pkt[i];
26968 	fi_xb = un->sd_fi_fifo_xb[i];
26969 	fi_un = un->sd_fi_fifo_un[i];
26970 	fi_arq = un->sd_fi_fifo_arq[i];
26971 
26972 
26973 	/* set variables accordingly */
26974 	/* set pkt if it was on fifo */
26975 	if (fi_pkt != NULL) {
26976 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
26977 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
26978 		SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
26979 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
26980 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
26981 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
26982 
26983 	}
26984 
26985 	/* set xb if it was on fifo */
26986 	if (fi_xb != NULL) {
26987 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
26988 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
26989 		SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
26990 		SD_CONDSET(xb, xb, xb_victim_retry_count,
26991 		    "xb_victim_retry_count");
26992 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
26993 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
26994 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
26995 
26996 		/* copy in block data from sense */
26997 		if (fi_xb->xb_sense_data[0] != -1) {
26998 			bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
26999 			    SENSE_LENGTH);
27000 		}
27001 
27002 		/* copy in extended sense codes */
27003 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_code,
27004 		    "es_code");
27005 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_key,
27006 		    "es_key");
27007 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_add_code,
27008 		    "es_add_code");
27009 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb,
27010 		    es_qual_code, "es_qual_code");
27011 	}
27012 
27013 	/* set un if it was on fifo */
27014 	if (fi_un != NULL) {
27015 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
27016 		SD_CONDSET(un, un, un_ctype, "un_ctype");
27017 		SD_CONDSET(un, un, un_reset_retry_count,
27018 		    "un_reset_retry_count");
27019 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
27020 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
27021 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
27022 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
27023 		    "un_f_allow_bus_device_reset");
27024 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
27025 
27026 	}
27027 
27028 	/* copy in auto request sense if it was on fifo */
27029 	if (fi_arq != NULL) {
27030 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
27031 	}
27032 
27033 	/* free structs */
27034 	if (un->sd_fi_fifo_pkt[i] != NULL) {
27035 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
27036 	}
27037 	if (un->sd_fi_fifo_xb[i] != NULL) {
27038 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
27039 	}
27040 	if (un->sd_fi_fifo_un[i] != NULL) {
27041 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
27042 	}
27043 	if (un->sd_fi_fifo_arq[i] != NULL) {
27044 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
27045 	}
27046 
27047 	/*
27048 	 * kmem_free does not gurantee to set to NULL
27049 	 * since we uses these to determine if we set
27050 	 * values or not lets confirm they are always
27051 	 * NULL after free
27052 	 */
27053 	un->sd_fi_fifo_pkt[i] = NULL;
27054 	un->sd_fi_fifo_un[i] = NULL;
27055 	un->sd_fi_fifo_xb[i] = NULL;
27056 	un->sd_fi_fifo_arq[i] = NULL;
27057 
27058 	un->sd_fi_fifo_start++;
27059 
27060 	mutex_exit(SD_MUTEX(un));
27061 
27062 	SD_TRACE(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
27063 }
27064 
27065 #endif /* SD_FAULT_INJECTION */
27066 
27067 /*
27068  * This routine is invoked in sd_unit_attach(). Before calling it, the
27069  * properties in conf file should be processed already, and "hotpluggable"
27070  * property was processed also.
27071  *
27072  * The sd driver distinguishes 3 different type of devices: removable media,
27073  * non-removable media, and hotpluggable. Below the differences are defined:
27074  *
27075  * 1. Device ID
27076  *
27077  *     The device ID of a device is used to identify this device. Refer to
27078  *     ddi_devid_register(9F).
27079  *
27080  *     For a non-removable media disk device which can provide 0x80 or 0x83
27081  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
27082  *     device ID is created to identify this device. For other non-removable
27083  *     media devices, a default device ID is created only if this device has
27084  *     at least 2 alter cylinders. Otherwise, this device has no devid.
27085  *
27086  *     -------------------------------------------------------
27087  *     removable media   hotpluggable  | Can Have Device ID
27088  *     -------------------------------------------------------
27089  *         false             false     |     Yes
27090  *         false             true      |     Yes
27091  *         true                x       |     No
27092  *     ------------------------------------------------------
27093  *
27094  *
27095  * 2. SCSI group 4 commands
27096  *
27097  *     In SCSI specs, only some commands in group 4 command set can use
27098  *     8-byte addresses that can be used to access >2TB storage spaces.
27099  *     Other commands have no such capability. Without supporting group4,
27100  *     it is impossible to make full use of storage spaces of a disk with
27101  *     capacity larger than 2TB.
27102  *
27103  *     -----------------------------------------------
27104  *     removable media   hotpluggable   LP64  |  Group
27105  *     -----------------------------------------------
27106  *           false          false       false |   1
27107  *           false          false       true  |   4
27108  *           false          true        false |   1
27109  *           false          true        true  |   4
27110  *           true             x           x   |   5
27111  *     -----------------------------------------------
27112  *
27113  *
27114  * 3. Check for VTOC Label
27115  *
27116  *     If a direct-access disk has no EFI label, sd will check if it has a
27117  *     valid VTOC label. Now, sd also does that check for removable media
27118  *     and hotpluggable devices.
27119  *
27120  *     --------------------------------------------------------------
27121  *     Direct-Access   removable media    hotpluggable |  Check Label
27122  *     -------------------------------------------------------------
27123  *         false          false           false        |   No
27124  *         false          false           true         |   No
27125  *         false          true            false        |   Yes
27126  *         false          true            true         |   Yes
27127  *         true            x                x          |   Yes
27128  *     --------------------------------------------------------------
27129  *
27130  *
27131  * 4. Building default VTOC label
27132  *
27133  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
27134  *     If those devices have no valid VTOC label, sd(7d) will attempt to
27135  *     create default VTOC for them. Currently sd creates default VTOC label
27136  *     for all devices on x86 platform (VTOC_16), but only for removable
27137  *     media devices on SPARC (VTOC_8).
27138  *
27139  *     -----------------------------------------------------------
27140  *       removable media hotpluggable platform   |   Default Label
27141  *     -----------------------------------------------------------
27142  *             false          false    sparc     |     No
27143  *             false          true      x86      |     Yes
27144  *             false          true     sparc     |     Yes
27145  *             true             x        x       |     Yes
27146  *     ----------------------------------------------------------
27147  *
27148  *
27149  * 5. Supported blocksizes of target devices
27150  *
27151  *     Sd supports non-512-byte blocksize for removable media devices only.
27152  *     For other devices, only 512-byte blocksize is supported. This may be
27153  *     changed in near future because some RAID devices require non-512-byte
27154  *     blocksize
27155  *
27156  *     -----------------------------------------------------------
27157  *     removable media    hotpluggable    | non-512-byte blocksize
27158  *     -----------------------------------------------------------
27159  *           false          false         |   No
27160  *           false          true          |   No
27161  *           true             x           |   Yes
27162  *     -----------------------------------------------------------
27163  *
27164  *
27165  * 6. Automatic mount & unmount
27166  *
27167  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
27168  *     if a device is removable media device. It return 1 for removable media
27169  *     devices, and 0 for others.
27170  *
27171  *     The automatic mounting subsystem should distinguish between the types
27172  *     of devices and apply automounting policies to each.
27173  *
27174  *
27175  * 7. fdisk partition management
27176  *
27177  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
27178  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
27179  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
27180  *     fdisk partitions on both x86 and SPARC platform.
27181  *
27182  *     -----------------------------------------------------------
27183  *       platform   removable media  USB/1394  |  fdisk supported
27184  *     -----------------------------------------------------------
27185  *        x86         X               X        |       true
27186  *     ------------------------------------------------------------
27187  *        sparc       X               X        |       false
27188  *     ------------------------------------------------------------
27189  *
27190  *
27191  * 8. MBOOT/MBR
27192  *
27193  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
27194  *     read/write mboot for removable media devices on sparc platform.
27195  *
27196  *     -----------------------------------------------------------
27197  *       platform   removable media  USB/1394  |  mboot supported
27198  *     -----------------------------------------------------------
27199  *        x86         X               X        |       true
27200  *     ------------------------------------------------------------
27201  *        sparc      false           false     |       false
27202  *        sparc      false           true      |       true
27203  *        sparc      true            false     |       true
27204  *        sparc      true            true      |       true
27205  *     ------------------------------------------------------------
27206  *
27207  *
27208  * 9.  error handling during opening device
27209  *
27210  *     If failed to open a disk device, an errno is returned. For some kinds
27211  *     of errors, different errno is returned depending on if this device is
27212  *     a removable media device. This brings USB/1394 hard disks in line with
27213  *     expected hard disk behavior. It is not expected that this breaks any
27214  *     application.
27215  *
27216  *     ------------------------------------------------------
27217  *       removable media    hotpluggable   |  errno
27218  *     ------------------------------------------------------
27219  *             false          false        |   EIO
27220  *             false          true         |   EIO
27221  *             true             x          |   ENXIO
27222  *     ------------------------------------------------------
27223  *
27224  *
27225  * 11. ioctls: DKIOCEJECT, CDROMEJECT
27226  *
27227  *     These IOCTLs are applicable only to removable media devices.
27228  *
27229  *     -----------------------------------------------------------
27230  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
27231  *     -----------------------------------------------------------
27232  *             false          false        |     No
27233  *             false          true         |     No
27234  *             true            x           |     Yes
27235  *     -----------------------------------------------------------
27236  *
27237  *
27238  * 12. Kstats for partitions
27239  *
27240  *     sd creates partition kstat for non-removable media devices. USB and
27241  *     Firewire hard disks now have partition kstats
27242  *
27243  *      ------------------------------------------------------
27244  *       removable media    hotpluggable   |   kstat
27245  *      ------------------------------------------------------
27246  *             false          false        |    Yes
27247  *             false          true         |    Yes
27248  *             true             x          |    No
27249  *       ------------------------------------------------------
27250  *
27251  *
27252  * 13. Removable media & hotpluggable properties
27253  *
27254  *     Sd driver creates a "removable-media" property for removable media
27255  *     devices. Parent nexus drivers create a "hotpluggable" property if
27256  *     it supports hotplugging.
27257  *
27258  *     ---------------------------------------------------------------------
27259  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
27260  *     ---------------------------------------------------------------------
27261  *       false            false       |    No                   No
27262  *       false            true        |    No                   Yes
27263  *       true             false       |    Yes                  No
27264  *       true             true        |    Yes                  Yes
27265  *     ---------------------------------------------------------------------
27266  *
27267  *
27268  * 14. Power Management
27269  *
27270  *     sd only power manages removable media devices or devices that support
27271  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
27272  *
27273  *     A parent nexus that supports hotplugging can also set "pm-capable"
27274  *     if the disk can be power managed.
27275  *
27276  *     ------------------------------------------------------------
27277  *       removable media hotpluggable pm-capable  |   power manage
27278  *     ------------------------------------------------------------
27279  *             false          false     false     |     No
27280  *             false          false     true      |     Yes
27281  *             false          true      false     |     No
27282  *             false          true      true      |     Yes
27283  *             true             x        x        |     Yes
27284  *     ------------------------------------------------------------
27285  *
27286  *      USB and firewire hard disks can now be power managed independently
27287  *      of the framebuffer
27288  *
27289  *
27290  * 15. Support for USB disks with capacity larger than 1TB
27291  *
27292  *     Currently, sd doesn't permit a fixed disk device with capacity
27293  *     larger than 1TB to be used in a 32-bit operating system environment.
27294  *     However, sd doesn't do that for removable media devices. Instead, it
27295  *     assumes that removable media devices cannot have a capacity larger
27296  *     than 1TB. Therefore, using those devices on 32-bit system is partially
27297  *     supported, which can cause some unexpected results.
27298  *
27299  *     ---------------------------------------------------------------------
27300  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
27301  *     ---------------------------------------------------------------------
27302  *             false          false  |   true         |     no
27303  *             false          true   |   true         |     no
27304  *             true           false  |   true         |     Yes
27305  *             true           true   |   true         |     Yes
27306  *     ---------------------------------------------------------------------
27307  *
27308  *
27309  * 16. Check write-protection at open time
27310  *
27311  *     When a removable media device is being opened for writing without NDELAY
27312  *     flag, sd will check if this device is writable. If attempting to open
27313  *     without NDELAY flag a write-protected device, this operation will abort.
27314  *
27315  *     ------------------------------------------------------------
27316  *       removable media    USB/1394   |   WP Check
27317  *     ------------------------------------------------------------
27318  *             false          false    |     No
27319  *             false          true     |     No
27320  *             true           false    |     Yes
27321  *             true           true     |     Yes
27322  *     ------------------------------------------------------------
27323  *
27324  *
27325  * 17. syslog when corrupted VTOC is encountered
27326  *
27327  *      Currently, if an invalid VTOC is encountered, sd only print syslog
27328  *      for fixed SCSI disks.
27329  *     ------------------------------------------------------------
27330  *       removable media    USB/1394   |   print syslog
27331  *     ------------------------------------------------------------
27332  *             false          false    |     Yes
27333  *             false          true     |     No
27334  *             true           false    |     No
27335  *             true           true     |     No
27336  *     ------------------------------------------------------------
27337  */
27338 static void
27339 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
27340 {
27341 	int	pm_capable_prop;
27342 
27343 	ASSERT(un->un_sd);
27344 	ASSERT(un->un_sd->sd_inq);
27345 
27346 	/*
27347 	 * Enable SYNC CACHE support for all devices.
27348 	 */
27349 	un->un_f_sync_cache_supported = TRUE;
27350 
27351 	if (un->un_sd->sd_inq->inq_rmb) {
27352 		/*
27353 		 * The media of this device is removable. And for this kind
27354 		 * of devices, it is possible to change medium after opening
27355 		 * devices. Thus we should support this operation.
27356 		 */
27357 		un->un_f_has_removable_media = TRUE;
27358 
27359 		/*
27360 		 * support non-512-byte blocksize of removable media devices
27361 		 */
27362 		un->un_f_non_devbsize_supported = TRUE;
27363 
27364 		/*
27365 		 * Assume that all removable media devices support DOOR_LOCK
27366 		 */
27367 		un->un_f_doorlock_supported = TRUE;
27368 
27369 		/*
27370 		 * For a removable media device, it is possible to be opened
27371 		 * with NDELAY flag when there is no media in drive, in this
27372 		 * case we don't care if device is writable. But if without
27373 		 * NDELAY flag, we need to check if media is write-protected.
27374 		 */
27375 		un->un_f_chk_wp_open = TRUE;
27376 
27377 		/*
27378 		 * need to start a SCSI watch thread to monitor media state,
27379 		 * when media is being inserted or ejected, notify syseventd.
27380 		 */
27381 		un->un_f_monitor_media_state = TRUE;
27382 
27383 		/*
27384 		 * Some devices don't support START_STOP_UNIT command.
27385 		 * Therefore, we'd better check if a device supports it
27386 		 * before sending it.
27387 		 */
27388 		un->un_f_check_start_stop = TRUE;
27389 
27390 		/*
27391 		 * support eject media ioctl:
27392 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
27393 		 */
27394 		un->un_f_eject_media_supported = TRUE;
27395 
27396 		/*
27397 		 * Because many removable-media devices don't support
27398 		 * LOG_SENSE, we couldn't use this command to check if
27399 		 * a removable media device support power-management.
27400 		 * We assume that they support power-management via
27401 		 * START_STOP_UNIT command and can be spun up and down
27402 		 * without limitations.
27403 		 */
27404 		un->un_f_pm_supported = TRUE;
27405 
27406 		/*
27407 		 * Need to create a zero length (Boolean) property
27408 		 * removable-media for the removable media devices.
27409 		 * Note that the return value of the property is not being
27410 		 * checked, since if unable to create the property
27411 		 * then do not want the attach to fail altogether. Consistent
27412 		 * with other property creation in attach.
27413 		 */
27414 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
27415 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
27416 
27417 	} else {
27418 		/*
27419 		 * create device ID for device
27420 		 */
27421 		un->un_f_devid_supported = TRUE;
27422 
27423 		/*
27424 		 * Spin up non-removable-media devices once it is attached
27425 		 */
27426 		un->un_f_attach_spinup = TRUE;
27427 
27428 		/*
27429 		 * According to SCSI specification, Sense data has two kinds of
27430 		 * format: fixed format, and descriptor format. At present, we
27431 		 * don't support descriptor format sense data for removable
27432 		 * media.
27433 		 */
27434 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
27435 			un->un_f_descr_format_supported = TRUE;
27436 		}
27437 
27438 		/*
27439 		 * kstats are created only for non-removable media devices.
27440 		 *
27441 		 * Set this in sd.conf to 0 in order to disable kstats.  The
27442 		 * default is 1, so they are enabled by default.
27443 		 */
27444 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
27445 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
27446 		    "enable-partition-kstats", 1));
27447 
27448 		/*
27449 		 * Check if HBA has set the "pm-capable" property.
27450 		 * If "pm-capable" exists and is non-zero then we can
27451 		 * power manage the device without checking the start/stop
27452 		 * cycle count log sense page.
27453 		 *
27454 		 * If "pm-capable" exists and is SD_PM_CAPABLE_FALSE (0)
27455 		 * then we should not power manage the device.
27456 		 *
27457 		 * If "pm-capable" doesn't exist then pm_capable_prop will
27458 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
27459 		 * sd will check the start/stop cycle count log sense page
27460 		 * and power manage the device if the cycle count limit has
27461 		 * not been exceeded.
27462 		 */
27463 		pm_capable_prop = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
27464 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
27465 		if (pm_capable_prop == SD_PM_CAPABLE_UNDEFINED) {
27466 			un->un_f_log_sense_supported = TRUE;
27467 		} else {
27468 			/*
27469 			 * pm-capable property exists.
27470 			 *
27471 			 * Convert "TRUE" values for pm_capable_prop to
27472 			 * SD_PM_CAPABLE_TRUE (1) to make it easier to check
27473 			 * later. "TRUE" values are any values except
27474 			 * SD_PM_CAPABLE_FALSE (0) and
27475 			 * SD_PM_CAPABLE_UNDEFINED (-1)
27476 			 */
27477 			if (pm_capable_prop == SD_PM_CAPABLE_FALSE) {
27478 				un->un_f_log_sense_supported = FALSE;
27479 			} else {
27480 				un->un_f_pm_supported = TRUE;
27481 			}
27482 
27483 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
27484 			    "sd_unit_attach: un:0x%p pm-capable "
27485 			    "property set to %d.\n", un, un->un_f_pm_supported);
27486 		}
27487 	}
27488 
27489 	if (un->un_f_is_hotpluggable) {
27490 
27491 		/*
27492 		 * Have to watch hotpluggable devices as well, since
27493 		 * that's the only way for userland applications to
27494 		 * detect hot removal while device is busy/mounted.
27495 		 */
27496 		un->un_f_monitor_media_state = TRUE;
27497 
27498 		un->un_f_check_start_stop = TRUE;
27499 
27500 	}
27501 }
27502 
27503 /*
27504  * sd_tg_rdwr:
27505  * Provides rdwr access for cmlb via sd_tgops. The start_block is
27506  * in sys block size, req_length in bytes.
27507  *
27508  */
27509 static int
27510 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
27511     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
27512 {
27513 	struct sd_lun *un;
27514 	int path_flag = (int)(uintptr_t)tg_cookie;
27515 	char *dkl = NULL;
27516 	diskaddr_t real_addr = start_block;
27517 	diskaddr_t first_byte, end_block;
27518 
27519 	size_t	buffer_size = reqlength;
27520 	int rval;
27521 	diskaddr_t	cap;
27522 	uint32_t	lbasize;
27523 
27524 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
27525 	if (un == NULL)
27526 		return (ENXIO);
27527 
27528 	if (cmd != TG_READ && cmd != TG_WRITE)
27529 		return (EINVAL);
27530 
27531 	mutex_enter(SD_MUTEX(un));
27532 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
27533 		mutex_exit(SD_MUTEX(un));
27534 		rval = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
27535 		    &lbasize, path_flag);
27536 		if (rval != 0)
27537 			return (rval);
27538 		mutex_enter(SD_MUTEX(un));
27539 		sd_update_block_info(un, lbasize, cap);
27540 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
27541 			mutex_exit(SD_MUTEX(un));
27542 			return (EIO);
27543 		}
27544 	}
27545 
27546 	if (NOT_DEVBSIZE(un)) {
27547 		/*
27548 		 * sys_blocksize != tgt_blocksize, need to re-adjust
27549 		 * blkno and save the index to beginning of dk_label
27550 		 */
27551 		first_byte  = SD_SYSBLOCKS2BYTES(un, start_block);
27552 		real_addr = first_byte / un->un_tgt_blocksize;
27553 
27554 		end_block = (first_byte + reqlength +
27555 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
27556 
27557 		/* round up buffer size to multiple of target block size */
27558 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
27559 
27560 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
27561 		    "label_addr: 0x%x allocation size: 0x%x\n",
27562 		    real_addr, buffer_size);
27563 
27564 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
27565 		    (reqlength % un->un_tgt_blocksize) != 0)
27566 			/* the request is not aligned */
27567 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
27568 	}
27569 
27570 	/*
27571 	 * The MMC standard allows READ CAPACITY to be
27572 	 * inaccurate by a bounded amount (in the interest of
27573 	 * response latency).  As a result, failed READs are
27574 	 * commonplace (due to the reading of metadata and not
27575 	 * data). Depending on the per-Vendor/drive Sense data,
27576 	 * the failed READ can cause many (unnecessary) retries.
27577 	 */
27578 
27579 	if (ISCD(un) && (cmd == TG_READ) &&
27580 	    (un->un_f_blockcount_is_valid == TRUE) &&
27581 	    ((start_block == (un->un_blockcount - 1))||
27582 	    (start_block == (un->un_blockcount - 2)))) {
27583 			path_flag = SD_PATH_DIRECT_PRIORITY;
27584 	}
27585 
27586 	mutex_exit(SD_MUTEX(un));
27587 	if (cmd == TG_READ) {
27588 		rval = sd_send_scsi_READ(un, (dkl != NULL)? dkl: bufaddr,
27589 		    buffer_size, real_addr, path_flag);
27590 		if (dkl != NULL)
27591 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
27592 			    real_addr), bufaddr, reqlength);
27593 	} else {
27594 		if (dkl) {
27595 			rval = sd_send_scsi_READ(un, dkl, buffer_size,
27596 			    real_addr, path_flag);
27597 			if (rval) {
27598 				kmem_free(dkl, buffer_size);
27599 				return (rval);
27600 			}
27601 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
27602 			    real_addr), reqlength);
27603 		}
27604 		rval = sd_send_scsi_WRITE(un, (dkl != NULL)? dkl: bufaddr,
27605 		    buffer_size, real_addr, path_flag);
27606 	}
27607 
27608 	if (dkl != NULL)
27609 		kmem_free(dkl, buffer_size);
27610 
27611 	return (rval);
27612 }
27613 
27614 
27615 static int
27616 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
27617 {
27618 
27619 	struct sd_lun *un;
27620 	diskaddr_t	cap;
27621 	uint32_t	lbasize;
27622 	int		path_flag = (int)(uintptr_t)tg_cookie;
27623 	int		ret = 0;
27624 
27625 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
27626 	if (un == NULL)
27627 		return (ENXIO);
27628 
27629 	switch (cmd) {
27630 	case TG_GETPHYGEOM:
27631 	case TG_GETVIRTGEOM:
27632 	case TG_GETCAPACITY:
27633 	case  TG_GETBLOCKSIZE:
27634 		mutex_enter(SD_MUTEX(un));
27635 
27636 		if ((un->un_f_blockcount_is_valid == TRUE) &&
27637 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
27638 			cap = un->un_blockcount;
27639 			lbasize = un->un_tgt_blocksize;
27640 			mutex_exit(SD_MUTEX(un));
27641 		} else {
27642 			mutex_exit(SD_MUTEX(un));
27643 			ret = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
27644 			    &lbasize, path_flag);
27645 			if (ret != 0)
27646 				return (ret);
27647 			mutex_enter(SD_MUTEX(un));
27648 			sd_update_block_info(un, lbasize, cap);
27649 			if ((un->un_f_blockcount_is_valid == FALSE) ||
27650 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
27651 				mutex_exit(SD_MUTEX(un));
27652 				return (EIO);
27653 			}
27654 			mutex_exit(SD_MUTEX(un));
27655 		}
27656 
27657 		if (cmd == TG_GETCAPACITY) {
27658 			*(diskaddr_t *)arg = cap;
27659 			return (0);
27660 		}
27661 
27662 		if (cmd == TG_GETBLOCKSIZE) {
27663 			*(uint32_t *)arg = lbasize;
27664 			return (0);
27665 		}
27666 
27667 		if (cmd == TG_GETPHYGEOM)
27668 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
27669 			    cap, lbasize, path_flag);
27670 		else
27671 			/* TG_GETVIRTGEOM */
27672 			ret = sd_get_virtual_geometry(un,
27673 			    (cmlb_geom_t *)arg, cap, lbasize);
27674 
27675 		return (ret);
27676 
27677 	case TG_GETATTR:
27678 		mutex_enter(SD_MUTEX(un));
27679 		((tg_attribute_t *)arg)->media_is_writable =
27680 		    un->un_f_mmc_writable_media;
27681 		mutex_exit(SD_MUTEX(un));
27682 		return (0);
27683 	default:
27684 		return (ENOTTY);
27685 
27686 	}
27687 
27688 }
27689