xref: /titanic_50/usr/src/uts/common/io/scsi/targets/sd.c (revision e6beb20cc8b2b323c3efa99bffc570d547089a7c)
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 2008 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 #include <sys/sysevent/eventdefs.h>
68 #include <sys/sysevent/dev.h>
69 
70 
71 /*
72  * Loadable module info.
73  */
74 #if (defined(__fibre))
75 #define	SD_MODULE_NAME	"SCSI SSA/FCAL Disk Driver %I%"
76 char _depends_on[]	= "misc/scsi misc/cmlb drv/fcp";
77 #else
78 #define	SD_MODULE_NAME	"SCSI Disk Driver %I%"
79 char _depends_on[]	= "misc/scsi misc/cmlb";
80 #endif
81 
82 /*
83  * Define the interconnect type, to allow the driver to distinguish
84  * between parallel SCSI (sd) and fibre channel (ssd) behaviors.
85  *
86  * This is really for backward compatibility. In the future, the driver
87  * should actually check the "interconnect-type" property as reported by
88  * the HBA; however at present this property is not defined by all HBAs,
89  * so we will use this #define (1) to permit the driver to run in
90  * backward-compatibility mode; and (2) to print a notification message
91  * if an FC HBA does not support the "interconnect-type" property.  The
92  * behavior of the driver will be to assume parallel SCSI behaviors unless
93  * the "interconnect-type" property is defined by the HBA **AND** has a
94  * value of either INTERCONNECT_FIBRE, INTERCONNECT_SSA, or
95  * INTERCONNECT_FABRIC, in which case the driver will assume Fibre
96  * Channel behaviors (as per the old ssd).  (Note that the
97  * INTERCONNECT_1394 and INTERCONNECT_USB types are not supported and
98  * will result in the driver assuming parallel SCSI behaviors.)
99  *
100  * (see common/sys/scsi/impl/services.h)
101  *
102  * Note: For ssd semantics, don't use INTERCONNECT_FABRIC as the default
103  * since some FC HBAs may already support that, and there is some code in
104  * the driver that already looks for it.  Using INTERCONNECT_FABRIC as the
105  * default would confuse that code, and besides things should work fine
106  * anyways if the FC HBA already reports INTERCONNECT_FABRIC for the
107  * "interconnect_type" property.
108  *
109  */
110 #if (defined(__fibre))
111 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_FIBRE
112 #else
113 #define	SD_DEFAULT_INTERCONNECT_TYPE	SD_INTERCONNECT_PARALLEL
114 #endif
115 
116 /*
117  * The name of the driver, established from the module name in _init.
118  */
119 static	char *sd_label			= NULL;
120 
121 /*
122  * Driver name is unfortunately prefixed on some driver.conf properties.
123  */
124 #if (defined(__fibre))
125 #define	sd_max_xfer_size		ssd_max_xfer_size
126 #define	sd_config_list			ssd_config_list
127 static	char *sd_max_xfer_size		= "ssd_max_xfer_size";
128 static	char *sd_config_list		= "ssd-config-list";
129 #else
130 static	char *sd_max_xfer_size		= "sd_max_xfer_size";
131 static	char *sd_config_list		= "sd-config-list";
132 #endif
133 
134 /*
135  * Driver global variables
136  */
137 
138 #if (defined(__fibre))
139 /*
140  * These #defines are to avoid namespace collisions that occur because this
141  * code is currently used to compile two separate driver modules: sd and ssd.
142  * All global variables need to be treated this way (even if declared static)
143  * in order to allow the debugger to resolve the names properly.
144  * It is anticipated that in the near future the ssd module will be obsoleted,
145  * at which time this namespace issue should go away.
146  */
147 #define	sd_state			ssd_state
148 #define	sd_io_time			ssd_io_time
149 #define	sd_failfast_enable		ssd_failfast_enable
150 #define	sd_ua_retry_count		ssd_ua_retry_count
151 #define	sd_report_pfa			ssd_report_pfa
152 #define	sd_max_throttle			ssd_max_throttle
153 #define	sd_min_throttle			ssd_min_throttle
154 #define	sd_rot_delay			ssd_rot_delay
155 
156 #define	sd_retry_on_reservation_conflict	\
157 					ssd_retry_on_reservation_conflict
158 #define	sd_reinstate_resv_delay		ssd_reinstate_resv_delay
159 #define	sd_resv_conflict_name		ssd_resv_conflict_name
160 
161 #define	sd_component_mask		ssd_component_mask
162 #define	sd_level_mask			ssd_level_mask
163 #define	sd_debug_un			ssd_debug_un
164 #define	sd_error_level			ssd_error_level
165 
166 #define	sd_xbuf_active_limit		ssd_xbuf_active_limit
167 #define	sd_xbuf_reserve_limit		ssd_xbuf_reserve_limit
168 
169 #define	sd_tr				ssd_tr
170 #define	sd_reset_throttle_timeout	ssd_reset_throttle_timeout
171 #define	sd_qfull_throttle_timeout	ssd_qfull_throttle_timeout
172 #define	sd_qfull_throttle_enable	ssd_qfull_throttle_enable
173 #define	sd_check_media_time		ssd_check_media_time
174 #define	sd_wait_cmds_complete		ssd_wait_cmds_complete
175 #define	sd_label_mutex			ssd_label_mutex
176 #define	sd_detach_mutex			ssd_detach_mutex
177 #define	sd_log_buf			ssd_log_buf
178 #define	sd_log_mutex			ssd_log_mutex
179 
180 #define	sd_disk_table			ssd_disk_table
181 #define	sd_disk_table_size		ssd_disk_table_size
182 #define	sd_sense_mutex			ssd_sense_mutex
183 #define	sd_cdbtab			ssd_cdbtab
184 
185 #define	sd_cb_ops			ssd_cb_ops
186 #define	sd_ops				ssd_ops
187 #define	sd_additional_codes		ssd_additional_codes
188 #define	sd_tgops			ssd_tgops
189 
190 #define	sd_minor_data			ssd_minor_data
191 #define	sd_minor_data_efi		ssd_minor_data_efi
192 
193 #define	sd_tq				ssd_tq
194 #define	sd_wmr_tq			ssd_wmr_tq
195 #define	sd_taskq_name			ssd_taskq_name
196 #define	sd_wmr_taskq_name		ssd_wmr_taskq_name
197 #define	sd_taskq_minalloc		ssd_taskq_minalloc
198 #define	sd_taskq_maxalloc		ssd_taskq_maxalloc
199 
200 #define	sd_dump_format_string		ssd_dump_format_string
201 
202 #define	sd_iostart_chain		ssd_iostart_chain
203 #define	sd_iodone_chain			ssd_iodone_chain
204 
205 #define	sd_pm_idletime			ssd_pm_idletime
206 
207 #define	sd_force_pm_supported		ssd_force_pm_supported
208 
209 #define	sd_dtype_optical_bind		ssd_dtype_optical_bind
210 
211 #endif
212 
213 
214 #ifdef	SDDEBUG
215 int	sd_force_pm_supported		= 0;
216 #endif	/* SDDEBUG */
217 
218 void *sd_state				= NULL;
219 int sd_io_time				= SD_IO_TIME;
220 int sd_failfast_enable			= 1;
221 int sd_ua_retry_count			= SD_UA_RETRY_COUNT;
222 int sd_report_pfa			= 1;
223 int sd_max_throttle			= SD_MAX_THROTTLE;
224 int sd_min_throttle			= SD_MIN_THROTTLE;
225 int sd_rot_delay			= 4; /* Default 4ms Rotation delay */
226 int sd_qfull_throttle_enable		= TRUE;
227 
228 int sd_retry_on_reservation_conflict	= 1;
229 int sd_reinstate_resv_delay		= SD_REINSTATE_RESV_DELAY;
230 _NOTE(SCHEME_PROTECTS_DATA("safe sharing", sd_reinstate_resv_delay))
231 
232 static int sd_dtype_optical_bind	= -1;
233 
234 /* Note: the following is not a bug, it really is "sd_" and not "ssd_" */
235 static	char *sd_resv_conflict_name	= "sd_retry_on_reservation_conflict";
236 
237 /*
238  * Global data for debug logging. To enable debug printing, sd_component_mask
239  * and sd_level_mask should be set to the desired bit patterns as outlined in
240  * sddef.h.
241  */
242 uint_t	sd_component_mask		= 0x0;
243 uint_t	sd_level_mask			= 0x0;
244 struct	sd_lun *sd_debug_un		= NULL;
245 uint_t	sd_error_level			= SCSI_ERR_RETRYABLE;
246 
247 /* Note: these may go away in the future... */
248 static uint32_t	sd_xbuf_active_limit	= 512;
249 static uint32_t sd_xbuf_reserve_limit	= 16;
250 
251 static struct sd_resv_reclaim_request	sd_tr = { NULL, NULL, NULL, 0, 0, 0 };
252 
253 /*
254  * Timer value used to reset the throttle after it has been reduced
255  * (typically in response to TRAN_BUSY or STATUS_QFULL)
256  */
257 static int sd_reset_throttle_timeout	= SD_RESET_THROTTLE_TIMEOUT;
258 static int sd_qfull_throttle_timeout	= SD_QFULL_THROTTLE_TIMEOUT;
259 
260 /*
261  * Interval value associated with the media change scsi watch.
262  */
263 static int sd_check_media_time		= 3000000;
264 
265 /*
266  * Wait value used for in progress operations during a DDI_SUSPEND
267  */
268 static int sd_wait_cmds_complete	= SD_WAIT_CMDS_COMPLETE;
269 
270 /*
271  * sd_label_mutex protects a static buffer used in the disk label
272  * component of the driver
273  */
274 static kmutex_t sd_label_mutex;
275 
276 /*
277  * sd_detach_mutex protects un_layer_count, un_detach_count, and
278  * un_opens_in_progress in the sd_lun structure.
279  */
280 static kmutex_t sd_detach_mutex;
281 
282 _NOTE(MUTEX_PROTECTS_DATA(sd_detach_mutex,
283 	sd_lun::{un_layer_count un_detach_count un_opens_in_progress}))
284 
285 /*
286  * Global buffer and mutex for debug logging
287  */
288 static char	sd_log_buf[1024];
289 static kmutex_t	sd_log_mutex;
290 
291 /*
292  * Structs and globals for recording attached lun information.
293  * This maintains a chain. Each node in the chain represents a SCSI controller.
294  * The structure records the number of luns attached to each target connected
295  * with the controller.
296  * For parallel scsi device only.
297  */
298 struct sd_scsi_hba_tgt_lun {
299 	struct sd_scsi_hba_tgt_lun	*next;
300 	dev_info_t			*pdip;
301 	int				nlun[NTARGETS_WIDE];
302 };
303 
304 /*
305  * Flag to indicate the lun is attached or detached
306  */
307 #define	SD_SCSI_LUN_ATTACH	0
308 #define	SD_SCSI_LUN_DETACH	1
309 
310 static kmutex_t	sd_scsi_target_lun_mutex;
311 static struct sd_scsi_hba_tgt_lun	*sd_scsi_target_lun_head = NULL;
312 
313 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
314     sd_scsi_hba_tgt_lun::next sd_scsi_hba_tgt_lun::pdip))
315 
316 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_target_lun_mutex,
317     sd_scsi_target_lun_head))
318 
319 /*
320  * "Smart" Probe Caching structs, globals, #defines, etc.
321  * For parallel scsi and non-self-identify device only.
322  */
323 
324 /*
325  * The following resources and routines are implemented to support
326  * "smart" probing, which caches the scsi_probe() results in an array,
327  * in order to help avoid long probe times.
328  */
329 struct sd_scsi_probe_cache {
330 	struct	sd_scsi_probe_cache	*next;
331 	dev_info_t	*pdip;
332 	int		cache[NTARGETS_WIDE];
333 };
334 
335 static kmutex_t	sd_scsi_probe_cache_mutex;
336 static struct	sd_scsi_probe_cache *sd_scsi_probe_cache_head = NULL;
337 
338 /*
339  * Really we only need protection on the head of the linked list, but
340  * better safe than sorry.
341  */
342 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
343     sd_scsi_probe_cache::next sd_scsi_probe_cache::pdip))
344 
345 _NOTE(MUTEX_PROTECTS_DATA(sd_scsi_probe_cache_mutex,
346     sd_scsi_probe_cache_head))
347 
348 
349 /*
350  * Vendor specific data name property declarations
351  */
352 
353 #if defined(__fibre) || defined(__i386) ||defined(__amd64)
354 
355 static sd_tunables seagate_properties = {
356 	SEAGATE_THROTTLE_VALUE,
357 	0,
358 	0,
359 	0,
360 	0,
361 	0,
362 	0,
363 	0,
364 	0
365 };
366 
367 
368 static sd_tunables fujitsu_properties = {
369 	FUJITSU_THROTTLE_VALUE,
370 	0,
371 	0,
372 	0,
373 	0,
374 	0,
375 	0,
376 	0,
377 	0
378 };
379 
380 static sd_tunables ibm_properties = {
381 	IBM_THROTTLE_VALUE,
382 	0,
383 	0,
384 	0,
385 	0,
386 	0,
387 	0,
388 	0,
389 	0
390 };
391 
392 static sd_tunables purple_properties = {
393 	PURPLE_THROTTLE_VALUE,
394 	0,
395 	0,
396 	PURPLE_BUSY_RETRIES,
397 	PURPLE_RESET_RETRY_COUNT,
398 	PURPLE_RESERVE_RELEASE_TIME,
399 	0,
400 	0,
401 	0
402 };
403 
404 static sd_tunables sve_properties = {
405 	SVE_THROTTLE_VALUE,
406 	0,
407 	0,
408 	SVE_BUSY_RETRIES,
409 	SVE_RESET_RETRY_COUNT,
410 	SVE_RESERVE_RELEASE_TIME,
411 	SVE_MIN_THROTTLE_VALUE,
412 	SVE_DISKSORT_DISABLED_FLAG,
413 	0
414 };
415 
416 static sd_tunables maserati_properties = {
417 	0,
418 	0,
419 	0,
420 	0,
421 	0,
422 	0,
423 	0,
424 	MASERATI_DISKSORT_DISABLED_FLAG,
425 	MASERATI_LUN_RESET_ENABLED_FLAG
426 };
427 
428 static sd_tunables pirus_properties = {
429 	PIRUS_THROTTLE_VALUE,
430 	0,
431 	PIRUS_NRR_COUNT,
432 	PIRUS_BUSY_RETRIES,
433 	PIRUS_RESET_RETRY_COUNT,
434 	0,
435 	PIRUS_MIN_THROTTLE_VALUE,
436 	PIRUS_DISKSORT_DISABLED_FLAG,
437 	PIRUS_LUN_RESET_ENABLED_FLAG
438 };
439 
440 #endif
441 
442 #if (defined(__sparc) && !defined(__fibre)) || \
443 	(defined(__i386) || defined(__amd64))
444 
445 
446 static sd_tunables elite_properties = {
447 	ELITE_THROTTLE_VALUE,
448 	0,
449 	0,
450 	0,
451 	0,
452 	0,
453 	0,
454 	0,
455 	0
456 };
457 
458 static sd_tunables st31200n_properties = {
459 	ST31200N_THROTTLE_VALUE,
460 	0,
461 	0,
462 	0,
463 	0,
464 	0,
465 	0,
466 	0,
467 	0
468 };
469 
470 #endif /* Fibre or not */
471 
472 static sd_tunables lsi_properties_scsi = {
473 	LSI_THROTTLE_VALUE,
474 	0,
475 	LSI_NOTREADY_RETRIES,
476 	0,
477 	0,
478 	0,
479 	0,
480 	0,
481 	0
482 };
483 
484 static sd_tunables symbios_properties = {
485 	SYMBIOS_THROTTLE_VALUE,
486 	0,
487 	SYMBIOS_NOTREADY_RETRIES,
488 	0,
489 	0,
490 	0,
491 	0,
492 	0,
493 	0
494 };
495 
496 static sd_tunables lsi_properties = {
497 	0,
498 	0,
499 	LSI_NOTREADY_RETRIES,
500 	0,
501 	0,
502 	0,
503 	0,
504 	0,
505 	0
506 };
507 
508 static sd_tunables lsi_oem_properties = {
509 	0,
510 	0,
511 	LSI_OEM_NOTREADY_RETRIES,
512 	0,
513 	0,
514 	0,
515 	0,
516 	0,
517 	0,
518 	1
519 };
520 
521 
522 
523 #if (defined(SD_PROP_TST))
524 
525 #define	SD_TST_CTYPE_VAL	CTYPE_CDROM
526 #define	SD_TST_THROTTLE_VAL	16
527 #define	SD_TST_NOTREADY_VAL	12
528 #define	SD_TST_BUSY_VAL		60
529 #define	SD_TST_RST_RETRY_VAL	36
530 #define	SD_TST_RSV_REL_TIME	60
531 
532 static sd_tunables tst_properties = {
533 	SD_TST_THROTTLE_VAL,
534 	SD_TST_CTYPE_VAL,
535 	SD_TST_NOTREADY_VAL,
536 	SD_TST_BUSY_VAL,
537 	SD_TST_RST_RETRY_VAL,
538 	SD_TST_RSV_REL_TIME,
539 	0,
540 	0,
541 	0
542 };
543 #endif
544 
545 /* This is similar to the ANSI toupper implementation */
546 #define	SD_TOUPPER(C)	(((C) >= 'a' && (C) <= 'z') ? (C) - 'a' + 'A' : (C))
547 
548 /*
549  * Static Driver Configuration Table
550  *
551  * This is the table of disks which need throttle adjustment (or, perhaps
552  * something else as defined by the flags at a future time.)  device_id
553  * is a string consisting of concatenated vid (vendor), pid (product/model)
554  * and revision strings as defined in the scsi_inquiry structure.  Offsets of
555  * the parts of the string are as defined by the sizes in the scsi_inquiry
556  * structure.  Device type is searched as far as the device_id string is
557  * defined.  Flags defines which values are to be set in the driver from the
558  * properties list.
559  *
560  * Entries below which begin and end with a "*" are a special case.
561  * These do not have a specific vendor, and the string which follows
562  * can appear anywhere in the 16 byte PID portion of the inquiry data.
563  *
564  * Entries below which begin and end with a " " (blank) are a special
565  * case. The comparison function will treat multiple consecutive blanks
566  * as equivalent to a single blank. For example, this causes a
567  * sd_disk_table entry of " NEC CDROM " to match a device's id string
568  * of  "NEC       CDROM".
569  *
570  * Note: The MD21 controller type has been obsoleted.
571  *	 ST318202F is a Legacy device
572  *	 MAM3182FC, MAM3364FC, MAM3738FC do not appear to have ever been
573  *	 made with an FC connection. The entries here are a legacy.
574  */
575 static sd_disk_config_t sd_disk_table[] = {
576 #if defined(__fibre) || defined(__i386) || defined(__amd64)
577 	{ "SEAGATE ST34371FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
578 	{ "SEAGATE ST19171FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
579 	{ "SEAGATE ST39102FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
580 	{ "SEAGATE ST39103FC", SD_CONF_BSET_THROTTLE, &seagate_properties },
581 	{ "SEAGATE ST118273F", SD_CONF_BSET_THROTTLE, &seagate_properties },
582 	{ "SEAGATE ST318202F", SD_CONF_BSET_THROTTLE, &seagate_properties },
583 	{ "SEAGATE ST318203F", SD_CONF_BSET_THROTTLE, &seagate_properties },
584 	{ "SEAGATE ST136403F", SD_CONF_BSET_THROTTLE, &seagate_properties },
585 	{ "SEAGATE ST318304F", SD_CONF_BSET_THROTTLE, &seagate_properties },
586 	{ "SEAGATE ST336704F", SD_CONF_BSET_THROTTLE, &seagate_properties },
587 	{ "SEAGATE ST373405F", SD_CONF_BSET_THROTTLE, &seagate_properties },
588 	{ "SEAGATE ST336605F", SD_CONF_BSET_THROTTLE, &seagate_properties },
589 	{ "SEAGATE ST336752F", SD_CONF_BSET_THROTTLE, &seagate_properties },
590 	{ "SEAGATE ST318452F", SD_CONF_BSET_THROTTLE, &seagate_properties },
591 	{ "FUJITSU MAG3091F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
592 	{ "FUJITSU MAG3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
593 	{ "FUJITSU MAA3182F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
594 	{ "FUJITSU MAF3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
595 	{ "FUJITSU MAL3364F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
596 	{ "FUJITSU MAL3738F",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
597 	{ "FUJITSU MAM3182FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
598 	{ "FUJITSU MAM3364FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
599 	{ "FUJITSU MAM3738FC",  SD_CONF_BSET_THROTTLE, &fujitsu_properties },
600 	{ "IBM     DDYFT1835",  SD_CONF_BSET_THROTTLE, &ibm_properties },
601 	{ "IBM     DDYFT3695",  SD_CONF_BSET_THROTTLE, &ibm_properties },
602 	{ "IBM     IC35LF2D2",  SD_CONF_BSET_THROTTLE, &ibm_properties },
603 	{ "IBM     IC35LF2PR",  SD_CONF_BSET_THROTTLE, &ibm_properties },
604 	{ "IBM     1724-100",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
605 	{ "IBM     1726-2xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
606 	{ "IBM     1726-22x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
607 	{ "IBM     1726-4xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
608 	{ "IBM     1726-42x",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
609 	{ "IBM     1726-3xx",   SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
610 	{ "IBM     3526",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
611 	{ "IBM     3542",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
612 	{ "IBM     3552",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
613 	{ "IBM     1722",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
614 	{ "IBM     1742",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
615 	{ "IBM     1815",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
616 	{ "IBM     FAStT",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
617 	{ "IBM     1814",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
618 	{ "IBM     1814-200",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
619 	{ "IBM     1818",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
620 	{ "DELL    MD3000",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
621 	{ "DELL    MD3000i",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
622 	{ "LSI     INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
623 	{ "ENGENIO INF",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
624 	{ "SGI     TP",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
625 	{ "SGI     IS",		SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
626 	{ "*CSM100_*",		SD_CONF_BSET_NRR_COUNT |
627 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
628 	{ "*CSM200_*",		SD_CONF_BSET_NRR_COUNT |
629 			SD_CONF_BSET_CACHE_IS_NV, &lsi_oem_properties },
630 	{ "Fujitsu SX300",	SD_CONF_BSET_THROTTLE,  &lsi_oem_properties },
631 	{ "LSI",		SD_CONF_BSET_NRR_COUNT, &lsi_properties },
632 	{ "SUN     T3", SD_CONF_BSET_THROTTLE |
633 			SD_CONF_BSET_BSY_RETRY_COUNT|
634 			SD_CONF_BSET_RST_RETRIES|
635 			SD_CONF_BSET_RSV_REL_TIME,
636 		&purple_properties },
637 	{ "SUN     SESS01", SD_CONF_BSET_THROTTLE |
638 		SD_CONF_BSET_BSY_RETRY_COUNT|
639 		SD_CONF_BSET_RST_RETRIES|
640 		SD_CONF_BSET_RSV_REL_TIME|
641 		SD_CONF_BSET_MIN_THROTTLE|
642 		SD_CONF_BSET_DISKSORT_DISABLED,
643 		&sve_properties },
644 	{ "SUN     T4", SD_CONF_BSET_THROTTLE |
645 			SD_CONF_BSET_BSY_RETRY_COUNT|
646 			SD_CONF_BSET_RST_RETRIES|
647 			SD_CONF_BSET_RSV_REL_TIME,
648 		&purple_properties },
649 	{ "SUN     SVE01", SD_CONF_BSET_DISKSORT_DISABLED |
650 		SD_CONF_BSET_LUN_RESET_ENABLED,
651 		&maserati_properties },
652 	{ "SUN     SE6920", 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     SE6940", 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 6920", SD_CONF_BSET_THROTTLE |
669 		SD_CONF_BSET_NRR_COUNT|
670 		SD_CONF_BSET_BSY_RETRY_COUNT|
671 		SD_CONF_BSET_RST_RETRIES|
672 		SD_CONF_BSET_MIN_THROTTLE|
673 		SD_CONF_BSET_DISKSORT_DISABLED|
674 		SD_CONF_BSET_LUN_RESET_ENABLED,
675 		&pirus_properties },
676 	{ "SUN     StorageTek 6940", 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     PSX1000", SD_CONF_BSET_THROTTLE |
685 		SD_CONF_BSET_NRR_COUNT|
686 		SD_CONF_BSET_BSY_RETRY_COUNT|
687 		SD_CONF_BSET_RST_RETRIES|
688 		SD_CONF_BSET_MIN_THROTTLE|
689 		SD_CONF_BSET_DISKSORT_DISABLED|
690 		SD_CONF_BSET_LUN_RESET_ENABLED,
691 		&pirus_properties },
692 	{ "SUN     SE6330", SD_CONF_BSET_THROTTLE |
693 		SD_CONF_BSET_NRR_COUNT|
694 		SD_CONF_BSET_BSY_RETRY_COUNT|
695 		SD_CONF_BSET_RST_RETRIES|
696 		SD_CONF_BSET_MIN_THROTTLE|
697 		SD_CONF_BSET_DISKSORT_DISABLED|
698 		SD_CONF_BSET_LUN_RESET_ENABLED,
699 		&pirus_properties },
700 	{ "SUN     STK6580_6780", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
701 	{ "STK     OPENstorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
702 	{ "STK     OpenStorage", SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
703 	{ "STK     BladeCtlr",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
704 	{ "STK     FLEXLINE",	SD_CONF_BSET_NRR_COUNT, &lsi_oem_properties },
705 	{ "SYMBIOS", SD_CONF_BSET_NRR_COUNT, &symbios_properties },
706 #endif /* fibre or NON-sparc platforms */
707 #if ((defined(__sparc) && !defined(__fibre)) ||\
708 	(defined(__i386) || defined(__amd64)))
709 	{ "SEAGATE ST42400N", SD_CONF_BSET_THROTTLE, &elite_properties },
710 	{ "SEAGATE ST31200N", SD_CONF_BSET_THROTTLE, &st31200n_properties },
711 	{ "SEAGATE ST41600N", SD_CONF_BSET_TUR_CHECK, NULL },
712 	{ "CONNER  CP30540",  SD_CONF_BSET_NOCACHE,  NULL },
713 	{ "*SUN0104*", SD_CONF_BSET_FAB_DEVID, NULL },
714 	{ "*SUN0207*", SD_CONF_BSET_FAB_DEVID, NULL },
715 	{ "*SUN0327*", SD_CONF_BSET_FAB_DEVID, NULL },
716 	{ "*SUN0340*", SD_CONF_BSET_FAB_DEVID, NULL },
717 	{ "*SUN0424*", SD_CONF_BSET_FAB_DEVID, NULL },
718 	{ "*SUN0669*", SD_CONF_BSET_FAB_DEVID, NULL },
719 	{ "*SUN1.0G*", SD_CONF_BSET_FAB_DEVID, NULL },
720 	{ "SYMBIOS INF-01-00       ", SD_CONF_BSET_FAB_DEVID, NULL },
721 	{ "SYMBIOS", SD_CONF_BSET_THROTTLE|SD_CONF_BSET_NRR_COUNT,
722 	    &symbios_properties },
723 	{ "LSI", SD_CONF_BSET_THROTTLE | SD_CONF_BSET_NRR_COUNT,
724 	    &lsi_properties_scsi },
725 #if defined(__i386) || defined(__amd64)
726 	{ " NEC CD-ROM DRIVE:260 ", (SD_CONF_BSET_PLAYMSF_BCD
727 				    | SD_CONF_BSET_READSUB_BCD
728 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
729 				    | SD_CONF_BSET_NO_READ_HEADER
730 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
731 
732 	{ " NEC CD-ROM DRIVE:270 ", (SD_CONF_BSET_PLAYMSF_BCD
733 				    | SD_CONF_BSET_READSUB_BCD
734 				    | SD_CONF_BSET_READ_TOC_ADDR_BCD
735 				    | SD_CONF_BSET_NO_READ_HEADER
736 				    | SD_CONF_BSET_READ_CD_XD4), NULL },
737 #endif /* __i386 || __amd64 */
738 #endif /* sparc NON-fibre or NON-sparc platforms */
739 
740 #if (defined(SD_PROP_TST))
741 	{ "VENDOR  PRODUCT ", (SD_CONF_BSET_THROTTLE
742 				| SD_CONF_BSET_CTYPE
743 				| SD_CONF_BSET_NRR_COUNT
744 				| SD_CONF_BSET_FAB_DEVID
745 				| SD_CONF_BSET_NOCACHE
746 				| SD_CONF_BSET_BSY_RETRY_COUNT
747 				| SD_CONF_BSET_PLAYMSF_BCD
748 				| SD_CONF_BSET_READSUB_BCD
749 				| SD_CONF_BSET_READ_TOC_TRK_BCD
750 				| SD_CONF_BSET_READ_TOC_ADDR_BCD
751 				| SD_CONF_BSET_NO_READ_HEADER
752 				| SD_CONF_BSET_READ_CD_XD4
753 				| SD_CONF_BSET_RST_RETRIES
754 				| SD_CONF_BSET_RSV_REL_TIME
755 				| SD_CONF_BSET_TUR_CHECK), &tst_properties},
756 #endif
757 };
758 
759 static const int sd_disk_table_size =
760 	sizeof (sd_disk_table)/ sizeof (sd_disk_config_t);
761 
762 
763 
764 #define	SD_INTERCONNECT_PARALLEL	0
765 #define	SD_INTERCONNECT_FABRIC		1
766 #define	SD_INTERCONNECT_FIBRE		2
767 #define	SD_INTERCONNECT_SSA		3
768 #define	SD_INTERCONNECT_SATA		4
769 #define	SD_IS_PARALLEL_SCSI(un)		\
770 	((un)->un_interconnect_type == SD_INTERCONNECT_PARALLEL)
771 #define	SD_IS_SERIAL(un)		\
772 	((un)->un_interconnect_type == SD_INTERCONNECT_SATA)
773 
774 /*
775  * Definitions used by device id registration routines
776  */
777 #define	VPD_HEAD_OFFSET		3	/* size of head for vpd page */
778 #define	VPD_PAGE_LENGTH		3	/* offset for pge length data */
779 #define	VPD_MODE_PAGE		1	/* offset into vpd pg for "page code" */
780 
781 static kmutex_t sd_sense_mutex = {0};
782 
783 /*
784  * Macros for updates of the driver state
785  */
786 #define	New_state(un, s)        \
787 	(un)->un_last_state = (un)->un_state, (un)->un_state = (s)
788 #define	Restore_state(un)	\
789 	{ uchar_t tmp = (un)->un_last_state; New_state((un), tmp); }
790 
791 static struct sd_cdbinfo sd_cdbtab[] = {
792 	{ CDB_GROUP0, 0x00,	   0x1FFFFF,   0xFF,	    },
793 	{ CDB_GROUP1, SCMD_GROUP1, 0xFFFFFFFF, 0xFFFF,	    },
794 	{ CDB_GROUP5, SCMD_GROUP5, 0xFFFFFFFF, 0xFFFFFFFF,  },
795 	{ CDB_GROUP4, SCMD_GROUP4, 0xFFFFFFFFFFFFFFFF, 0xFFFFFFFF, },
796 };
797 
798 /*
799  * Specifies the number of seconds that must have elapsed since the last
800  * cmd. has completed for a device to be declared idle to the PM framework.
801  */
802 static int sd_pm_idletime = 1;
803 
804 /*
805  * Internal function prototypes
806  */
807 
808 #if (defined(__fibre))
809 /*
810  * These #defines are to avoid namespace collisions that occur because this
811  * code is currently used to compile two separate driver modules: sd and ssd.
812  * All function names need to be treated this way (even if declared static)
813  * in order to allow the debugger to resolve the names properly.
814  * It is anticipated that in the near future the ssd module will be obsoleted,
815  * at which time this ugliness should go away.
816  */
817 #define	sd_log_trace			ssd_log_trace
818 #define	sd_log_info			ssd_log_info
819 #define	sd_log_err			ssd_log_err
820 #define	sdprobe				ssdprobe
821 #define	sdinfo				ssdinfo
822 #define	sd_prop_op			ssd_prop_op
823 #define	sd_scsi_probe_cache_init	ssd_scsi_probe_cache_init
824 #define	sd_scsi_probe_cache_fini	ssd_scsi_probe_cache_fini
825 #define	sd_scsi_clear_probe_cache	ssd_scsi_clear_probe_cache
826 #define	sd_scsi_probe_with_cache	ssd_scsi_probe_with_cache
827 #define	sd_scsi_target_lun_init		ssd_scsi_target_lun_init
828 #define	sd_scsi_target_lun_fini		ssd_scsi_target_lun_fini
829 #define	sd_scsi_get_target_lun_count	ssd_scsi_get_target_lun_count
830 #define	sd_scsi_update_lun_on_target	ssd_scsi_update_lun_on_target
831 #define	sd_spin_up_unit			ssd_spin_up_unit
832 #define	sd_enable_descr_sense		ssd_enable_descr_sense
833 #define	sd_reenable_dsense_task		ssd_reenable_dsense_task
834 #define	sd_set_mmc_caps			ssd_set_mmc_caps
835 #define	sd_read_unit_properties		ssd_read_unit_properties
836 #define	sd_process_sdconf_file		ssd_process_sdconf_file
837 #define	sd_process_sdconf_table		ssd_process_sdconf_table
838 #define	sd_sdconf_id_match		ssd_sdconf_id_match
839 #define	sd_blank_cmp			ssd_blank_cmp
840 #define	sd_chk_vers1_data		ssd_chk_vers1_data
841 #define	sd_set_vers1_properties		ssd_set_vers1_properties
842 
843 #define	sd_get_physical_geometry	ssd_get_physical_geometry
844 #define	sd_get_virtual_geometry		ssd_get_virtual_geometry
845 #define	sd_update_block_info		ssd_update_block_info
846 #define	sd_register_devid		ssd_register_devid
847 #define	sd_get_devid			ssd_get_devid
848 #define	sd_create_devid			ssd_create_devid
849 #define	sd_write_deviceid		ssd_write_deviceid
850 #define	sd_check_vpd_page_support	ssd_check_vpd_page_support
851 #define	sd_setup_pm			ssd_setup_pm
852 #define	sd_create_pm_components		ssd_create_pm_components
853 #define	sd_ddi_suspend			ssd_ddi_suspend
854 #define	sd_ddi_pm_suspend		ssd_ddi_pm_suspend
855 #define	sd_ddi_resume			ssd_ddi_resume
856 #define	sd_ddi_pm_resume		ssd_ddi_pm_resume
857 #define	sdpower				ssdpower
858 #define	sdattach			ssdattach
859 #define	sddetach			ssddetach
860 #define	sd_unit_attach			ssd_unit_attach
861 #define	sd_unit_detach			ssd_unit_detach
862 #define	sd_set_unit_attributes		ssd_set_unit_attributes
863 #define	sd_create_errstats		ssd_create_errstats
864 #define	sd_set_errstats			ssd_set_errstats
865 #define	sd_set_pstats			ssd_set_pstats
866 #define	sddump				ssddump
867 #define	sd_scsi_poll			ssd_scsi_poll
868 #define	sd_send_polled_RQS		ssd_send_polled_RQS
869 #define	sd_ddi_scsi_poll		ssd_ddi_scsi_poll
870 #define	sd_init_event_callbacks		ssd_init_event_callbacks
871 #define	sd_event_callback		ssd_event_callback
872 #define	sd_cache_control		ssd_cache_control
873 #define	sd_get_write_cache_enabled	ssd_get_write_cache_enabled
874 #define	sd_get_nv_sup			ssd_get_nv_sup
875 #define	sd_make_device			ssd_make_device
876 #define	sdopen				ssdopen
877 #define	sdclose				ssdclose
878 #define	sd_ready_and_valid		ssd_ready_and_valid
879 #define	sdmin				ssdmin
880 #define	sdread				ssdread
881 #define	sdwrite				ssdwrite
882 #define	sdaread				ssdaread
883 #define	sdawrite			ssdawrite
884 #define	sdstrategy			ssdstrategy
885 #define	sdioctl				ssdioctl
886 #define	sd_mapblockaddr_iostart		ssd_mapblockaddr_iostart
887 #define	sd_mapblocksize_iostart		ssd_mapblocksize_iostart
888 #define	sd_checksum_iostart		ssd_checksum_iostart
889 #define	sd_checksum_uscsi_iostart	ssd_checksum_uscsi_iostart
890 #define	sd_pm_iostart			ssd_pm_iostart
891 #define	sd_core_iostart			ssd_core_iostart
892 #define	sd_mapblockaddr_iodone		ssd_mapblockaddr_iodone
893 #define	sd_mapblocksize_iodone		ssd_mapblocksize_iodone
894 #define	sd_checksum_iodone		ssd_checksum_iodone
895 #define	sd_checksum_uscsi_iodone	ssd_checksum_uscsi_iodone
896 #define	sd_pm_iodone			ssd_pm_iodone
897 #define	sd_initpkt_for_buf		ssd_initpkt_for_buf
898 #define	sd_destroypkt_for_buf		ssd_destroypkt_for_buf
899 #define	sd_setup_rw_pkt			ssd_setup_rw_pkt
900 #define	sd_setup_next_rw_pkt		ssd_setup_next_rw_pkt
901 #define	sd_buf_iodone			ssd_buf_iodone
902 #define	sd_uscsi_strategy		ssd_uscsi_strategy
903 #define	sd_initpkt_for_uscsi		ssd_initpkt_for_uscsi
904 #define	sd_destroypkt_for_uscsi		ssd_destroypkt_for_uscsi
905 #define	sd_uscsi_iodone			ssd_uscsi_iodone
906 #define	sd_xbuf_strategy		ssd_xbuf_strategy
907 #define	sd_xbuf_init			ssd_xbuf_init
908 #define	sd_pm_entry			ssd_pm_entry
909 #define	sd_pm_exit			ssd_pm_exit
910 
911 #define	sd_pm_idletimeout_handler	ssd_pm_idletimeout_handler
912 #define	sd_pm_timeout_handler		ssd_pm_timeout_handler
913 
914 #define	sd_add_buf_to_waitq		ssd_add_buf_to_waitq
915 #define	sdintr				ssdintr
916 #define	sd_start_cmds			ssd_start_cmds
917 #define	sd_send_scsi_cmd		ssd_send_scsi_cmd
918 #define	sd_bioclone_alloc		ssd_bioclone_alloc
919 #define	sd_bioclone_free		ssd_bioclone_free
920 #define	sd_shadow_buf_alloc		ssd_shadow_buf_alloc
921 #define	sd_shadow_buf_free		ssd_shadow_buf_free
922 #define	sd_print_transport_rejected_message	\
923 					ssd_print_transport_rejected_message
924 #define	sd_retry_command		ssd_retry_command
925 #define	sd_set_retry_bp			ssd_set_retry_bp
926 #define	sd_send_request_sense_command	ssd_send_request_sense_command
927 #define	sd_start_retry_command		ssd_start_retry_command
928 #define	sd_start_direct_priority_command	\
929 					ssd_start_direct_priority_command
930 #define	sd_return_failed_command	ssd_return_failed_command
931 #define	sd_return_failed_command_no_restart	\
932 					ssd_return_failed_command_no_restart
933 #define	sd_return_command		ssd_return_command
934 #define	sd_sync_with_callback		ssd_sync_with_callback
935 #define	sdrunout			ssdrunout
936 #define	sd_mark_rqs_busy		ssd_mark_rqs_busy
937 #define	sd_mark_rqs_idle		ssd_mark_rqs_idle
938 #define	sd_reduce_throttle		ssd_reduce_throttle
939 #define	sd_restore_throttle		ssd_restore_throttle
940 #define	sd_print_incomplete_msg		ssd_print_incomplete_msg
941 #define	sd_init_cdb_limits		ssd_init_cdb_limits
942 #define	sd_pkt_status_good		ssd_pkt_status_good
943 #define	sd_pkt_status_check_condition	ssd_pkt_status_check_condition
944 #define	sd_pkt_status_busy		ssd_pkt_status_busy
945 #define	sd_pkt_status_reservation_conflict	\
946 					ssd_pkt_status_reservation_conflict
947 #define	sd_pkt_status_qfull		ssd_pkt_status_qfull
948 #define	sd_handle_request_sense		ssd_handle_request_sense
949 #define	sd_handle_auto_request_sense	ssd_handle_auto_request_sense
950 #define	sd_print_sense_failed_msg	ssd_print_sense_failed_msg
951 #define	sd_validate_sense_data		ssd_validate_sense_data
952 #define	sd_decode_sense			ssd_decode_sense
953 #define	sd_print_sense_msg		ssd_print_sense_msg
954 #define	sd_sense_key_no_sense		ssd_sense_key_no_sense
955 #define	sd_sense_key_recoverable_error	ssd_sense_key_recoverable_error
956 #define	sd_sense_key_not_ready		ssd_sense_key_not_ready
957 #define	sd_sense_key_medium_or_hardware_error	\
958 					ssd_sense_key_medium_or_hardware_error
959 #define	sd_sense_key_illegal_request	ssd_sense_key_illegal_request
960 #define	sd_sense_key_unit_attention	ssd_sense_key_unit_attention
961 #define	sd_sense_key_fail_command	ssd_sense_key_fail_command
962 #define	sd_sense_key_blank_check	ssd_sense_key_blank_check
963 #define	sd_sense_key_aborted_command	ssd_sense_key_aborted_command
964 #define	sd_sense_key_default		ssd_sense_key_default
965 #define	sd_print_retry_msg		ssd_print_retry_msg
966 #define	sd_print_cmd_incomplete_msg	ssd_print_cmd_incomplete_msg
967 #define	sd_pkt_reason_cmd_incomplete	ssd_pkt_reason_cmd_incomplete
968 #define	sd_pkt_reason_cmd_tran_err	ssd_pkt_reason_cmd_tran_err
969 #define	sd_pkt_reason_cmd_reset		ssd_pkt_reason_cmd_reset
970 #define	sd_pkt_reason_cmd_aborted	ssd_pkt_reason_cmd_aborted
971 #define	sd_pkt_reason_cmd_timeout	ssd_pkt_reason_cmd_timeout
972 #define	sd_pkt_reason_cmd_unx_bus_free	ssd_pkt_reason_cmd_unx_bus_free
973 #define	sd_pkt_reason_cmd_tag_reject	ssd_pkt_reason_cmd_tag_reject
974 #define	sd_pkt_reason_default		ssd_pkt_reason_default
975 #define	sd_reset_target			ssd_reset_target
976 #define	sd_start_stop_unit_callback	ssd_start_stop_unit_callback
977 #define	sd_start_stop_unit_task		ssd_start_stop_unit_task
978 #define	sd_taskq_create			ssd_taskq_create
979 #define	sd_taskq_delete			ssd_taskq_delete
980 #define	sd_target_change_task		ssd_target_change_task
981 #define	sd_log_lun_expansion_event	ssd_log_lun_expansion_event
982 #define	sd_media_change_task		ssd_media_change_task
983 #define	sd_handle_mchange		ssd_handle_mchange
984 #define	sd_send_scsi_DOORLOCK		ssd_send_scsi_DOORLOCK
985 #define	sd_send_scsi_READ_CAPACITY	ssd_send_scsi_READ_CAPACITY
986 #define	sd_send_scsi_READ_CAPACITY_16	ssd_send_scsi_READ_CAPACITY_16
987 #define	sd_send_scsi_GET_CONFIGURATION	ssd_send_scsi_GET_CONFIGURATION
988 #define	sd_send_scsi_feature_GET_CONFIGURATION	\
989 					sd_send_scsi_feature_GET_CONFIGURATION
990 #define	sd_send_scsi_START_STOP_UNIT	ssd_send_scsi_START_STOP_UNIT
991 #define	sd_send_scsi_INQUIRY		ssd_send_scsi_INQUIRY
992 #define	sd_send_scsi_TEST_UNIT_READY	ssd_send_scsi_TEST_UNIT_READY
993 #define	sd_send_scsi_PERSISTENT_RESERVE_IN	\
994 					ssd_send_scsi_PERSISTENT_RESERVE_IN
995 #define	sd_send_scsi_PERSISTENT_RESERVE_OUT	\
996 					ssd_send_scsi_PERSISTENT_RESERVE_OUT
997 #define	sd_send_scsi_SYNCHRONIZE_CACHE	ssd_send_scsi_SYNCHRONIZE_CACHE
998 #define	sd_send_scsi_SYNCHRONIZE_CACHE_biodone	\
999 					ssd_send_scsi_SYNCHRONIZE_CACHE_biodone
1000 #define	sd_send_scsi_MODE_SENSE		ssd_send_scsi_MODE_SENSE
1001 #define	sd_send_scsi_MODE_SELECT	ssd_send_scsi_MODE_SELECT
1002 #define	sd_send_scsi_RDWR		ssd_send_scsi_RDWR
1003 #define	sd_send_scsi_LOG_SENSE		ssd_send_scsi_LOG_SENSE
1004 #define	sd_alloc_rqs			ssd_alloc_rqs
1005 #define	sd_free_rqs			ssd_free_rqs
1006 #define	sd_dump_memory			ssd_dump_memory
1007 #define	sd_get_media_info		ssd_get_media_info
1008 #define	sd_dkio_ctrl_info		ssd_dkio_ctrl_info
1009 #define	sd_get_tunables_from_conf	ssd_get_tunables_from_conf
1010 #define	sd_setup_next_xfer		ssd_setup_next_xfer
1011 #define	sd_dkio_get_temp		ssd_dkio_get_temp
1012 #define	sd_check_mhd			ssd_check_mhd
1013 #define	sd_mhd_watch_cb			ssd_mhd_watch_cb
1014 #define	sd_mhd_watch_incomplete		ssd_mhd_watch_incomplete
1015 #define	sd_sname			ssd_sname
1016 #define	sd_mhd_resvd_recover		ssd_mhd_resvd_recover
1017 #define	sd_resv_reclaim_thread		ssd_resv_reclaim_thread
1018 #define	sd_take_ownership		ssd_take_ownership
1019 #define	sd_reserve_release		ssd_reserve_release
1020 #define	sd_rmv_resv_reclaim_req		ssd_rmv_resv_reclaim_req
1021 #define	sd_mhd_reset_notify_cb		ssd_mhd_reset_notify_cb
1022 #define	sd_persistent_reservation_in_read_keys	\
1023 					ssd_persistent_reservation_in_read_keys
1024 #define	sd_persistent_reservation_in_read_resv	\
1025 					ssd_persistent_reservation_in_read_resv
1026 #define	sd_mhdioc_takeown		ssd_mhdioc_takeown
1027 #define	sd_mhdioc_failfast		ssd_mhdioc_failfast
1028 #define	sd_mhdioc_release		ssd_mhdioc_release
1029 #define	sd_mhdioc_register_devid	ssd_mhdioc_register_devid
1030 #define	sd_mhdioc_inkeys		ssd_mhdioc_inkeys
1031 #define	sd_mhdioc_inresv		ssd_mhdioc_inresv
1032 #define	sr_change_blkmode		ssr_change_blkmode
1033 #define	sr_change_speed			ssr_change_speed
1034 #define	sr_atapi_change_speed		ssr_atapi_change_speed
1035 #define	sr_pause_resume			ssr_pause_resume
1036 #define	sr_play_msf			ssr_play_msf
1037 #define	sr_play_trkind			ssr_play_trkind
1038 #define	sr_read_all_subcodes		ssr_read_all_subcodes
1039 #define	sr_read_subchannel		ssr_read_subchannel
1040 #define	sr_read_tocentry		ssr_read_tocentry
1041 #define	sr_read_tochdr			ssr_read_tochdr
1042 #define	sr_read_cdda			ssr_read_cdda
1043 #define	sr_read_cdxa			ssr_read_cdxa
1044 #define	sr_read_mode1			ssr_read_mode1
1045 #define	sr_read_mode2			ssr_read_mode2
1046 #define	sr_read_cd_mode2		ssr_read_cd_mode2
1047 #define	sr_sector_mode			ssr_sector_mode
1048 #define	sr_eject			ssr_eject
1049 #define	sr_ejected			ssr_ejected
1050 #define	sr_check_wp			ssr_check_wp
1051 #define	sd_check_media			ssd_check_media
1052 #define	sd_media_watch_cb		ssd_media_watch_cb
1053 #define	sd_delayed_cv_broadcast		ssd_delayed_cv_broadcast
1054 #define	sr_volume_ctrl			ssr_volume_ctrl
1055 #define	sr_read_sony_session_offset	ssr_read_sony_session_offset
1056 #define	sd_log_page_supported		ssd_log_page_supported
1057 #define	sd_check_for_writable_cd	ssd_check_for_writable_cd
1058 #define	sd_wm_cache_constructor		ssd_wm_cache_constructor
1059 #define	sd_wm_cache_destructor		ssd_wm_cache_destructor
1060 #define	sd_range_lock			ssd_range_lock
1061 #define	sd_get_range			ssd_get_range
1062 #define	sd_free_inlist_wmap		ssd_free_inlist_wmap
1063 #define	sd_range_unlock			ssd_range_unlock
1064 #define	sd_read_modify_write_task	ssd_read_modify_write_task
1065 #define	sddump_do_read_of_rmw		ssddump_do_read_of_rmw
1066 
1067 #define	sd_iostart_chain		ssd_iostart_chain
1068 #define	sd_iodone_chain			ssd_iodone_chain
1069 #define	sd_initpkt_map			ssd_initpkt_map
1070 #define	sd_destroypkt_map		ssd_destroypkt_map
1071 #define	sd_chain_type_map		ssd_chain_type_map
1072 #define	sd_chain_index_map		ssd_chain_index_map
1073 
1074 #define	sd_failfast_flushctl		ssd_failfast_flushctl
1075 #define	sd_failfast_flushq		ssd_failfast_flushq
1076 #define	sd_failfast_flushq_callback	ssd_failfast_flushq_callback
1077 
1078 #define	sd_is_lsi			ssd_is_lsi
1079 #define	sd_tg_rdwr			ssd_tg_rdwr
1080 #define	sd_tg_getinfo			ssd_tg_getinfo
1081 
1082 #endif	/* #if (defined(__fibre)) */
1083 
1084 
1085 int _init(void);
1086 int _fini(void);
1087 int _info(struct modinfo *modinfop);
1088 
1089 /*PRINTFLIKE3*/
1090 static void sd_log_trace(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1091 /*PRINTFLIKE3*/
1092 static void sd_log_info(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1093 /*PRINTFLIKE3*/
1094 static void sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...);
1095 
1096 static int sdprobe(dev_info_t *devi);
1097 static int sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg,
1098     void **result);
1099 static int sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op,
1100     int mod_flags, char *name, caddr_t valuep, int *lengthp);
1101 
1102 /*
1103  * Smart probe for parallel scsi
1104  */
1105 static void sd_scsi_probe_cache_init(void);
1106 static void sd_scsi_probe_cache_fini(void);
1107 static void sd_scsi_clear_probe_cache(void);
1108 static int  sd_scsi_probe_with_cache(struct scsi_device *devp, int (*fn)());
1109 
1110 /*
1111  * Attached luns on target for parallel scsi
1112  */
1113 static void sd_scsi_target_lun_init(void);
1114 static void sd_scsi_target_lun_fini(void);
1115 static int  sd_scsi_get_target_lun_count(dev_info_t *dip, int target);
1116 static void sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag);
1117 
1118 static int	sd_spin_up_unit(struct sd_lun *un);
1119 #ifdef _LP64
1120 static void	sd_enable_descr_sense(struct sd_lun *un);
1121 static void	sd_reenable_dsense_task(void *arg);
1122 #endif /* _LP64 */
1123 
1124 static void	sd_set_mmc_caps(struct sd_lun *un);
1125 
1126 static void sd_read_unit_properties(struct sd_lun *un);
1127 static int  sd_process_sdconf_file(struct sd_lun *un);
1128 static void sd_get_tunables_from_conf(struct sd_lun *un, int flags,
1129     int *data_list, sd_tunables *values);
1130 static void sd_process_sdconf_table(struct sd_lun *un);
1131 static int  sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen);
1132 static int  sd_blank_cmp(struct sd_lun *un, char *id, int idlen);
1133 static int  sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
1134 	int list_len, char *dataname_ptr);
1135 static void sd_set_vers1_properties(struct sd_lun *un, int flags,
1136     sd_tunables *prop_list);
1137 
1138 static void sd_register_devid(struct sd_lun *un, dev_info_t *devi,
1139     int reservation_flag);
1140 static int  sd_get_devid(struct sd_lun *un);
1141 static ddi_devid_t sd_create_devid(struct sd_lun *un);
1142 static int  sd_write_deviceid(struct sd_lun *un);
1143 static int  sd_get_devid_page(struct sd_lun *un, uchar_t *wwn, int *len);
1144 static int  sd_check_vpd_page_support(struct sd_lun *un);
1145 
1146 static void sd_setup_pm(struct sd_lun *un, dev_info_t *devi);
1147 static void sd_create_pm_components(dev_info_t *devi, struct sd_lun *un);
1148 
1149 static int  sd_ddi_suspend(dev_info_t *devi);
1150 static int  sd_ddi_pm_suspend(struct sd_lun *un);
1151 static int  sd_ddi_resume(dev_info_t *devi);
1152 static int  sd_ddi_pm_resume(struct sd_lun *un);
1153 static int  sdpower(dev_info_t *devi, int component, int level);
1154 
1155 static int  sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd);
1156 static int  sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd);
1157 static int  sd_unit_attach(dev_info_t *devi);
1158 static int  sd_unit_detach(dev_info_t *devi);
1159 
1160 static void sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi);
1161 static void sd_create_errstats(struct sd_lun *un, int instance);
1162 static void sd_set_errstats(struct sd_lun *un);
1163 static void sd_set_pstats(struct sd_lun *un);
1164 
1165 static int  sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk);
1166 static int  sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pkt);
1167 static int  sd_send_polled_RQS(struct sd_lun *un);
1168 static int  sd_ddi_scsi_poll(struct scsi_pkt *pkt);
1169 
1170 #if (defined(__fibre))
1171 /*
1172  * Event callbacks (photon)
1173  */
1174 static void sd_init_event_callbacks(struct sd_lun *un);
1175 static void  sd_event_callback(dev_info_t *, ddi_eventcookie_t, void *, void *);
1176 #endif
1177 
1178 /*
1179  * Defines for sd_cache_control
1180  */
1181 
1182 #define	SD_CACHE_ENABLE		1
1183 #define	SD_CACHE_DISABLE	0
1184 #define	SD_CACHE_NOCHANGE	-1
1185 
1186 static int   sd_cache_control(struct sd_lun *un, int rcd_flag, int wce_flag);
1187 static int   sd_get_write_cache_enabled(struct sd_lun *un, int *is_enabled);
1188 static void  sd_get_nv_sup(struct sd_lun *un);
1189 static dev_t sd_make_device(dev_info_t *devi);
1190 
1191 static void  sd_update_block_info(struct sd_lun *un, uint32_t lbasize,
1192 	uint64_t capacity);
1193 
1194 /*
1195  * Driver entry point functions.
1196  */
1197 static int  sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p);
1198 static int  sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p);
1199 static int  sd_ready_and_valid(struct sd_lun *un);
1200 
1201 static void sdmin(struct buf *bp);
1202 static int sdread(dev_t dev, struct uio *uio, cred_t *cred_p);
1203 static int sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p);
1204 static int sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1205 static int sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p);
1206 
1207 static int sdstrategy(struct buf *bp);
1208 static int sdioctl(dev_t, int, intptr_t, int, cred_t *, int *);
1209 
1210 /*
1211  * Function prototypes for layering functions in the iostart chain.
1212  */
1213 static void sd_mapblockaddr_iostart(int index, struct sd_lun *un,
1214 	struct buf *bp);
1215 static void sd_mapblocksize_iostart(int index, struct sd_lun *un,
1216 	struct buf *bp);
1217 static void sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp);
1218 static void sd_checksum_uscsi_iostart(int index, struct sd_lun *un,
1219 	struct buf *bp);
1220 static void sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp);
1221 static void sd_core_iostart(int index, struct sd_lun *un, struct buf *bp);
1222 
1223 /*
1224  * Function prototypes for layering functions in the iodone chain.
1225  */
1226 static void sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp);
1227 static void sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp);
1228 static void sd_mapblockaddr_iodone(int index, struct sd_lun *un,
1229 	struct buf *bp);
1230 static void sd_mapblocksize_iodone(int index, struct sd_lun *un,
1231 	struct buf *bp);
1232 static void sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp);
1233 static void sd_checksum_uscsi_iodone(int index, struct sd_lun *un,
1234 	struct buf *bp);
1235 static void sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp);
1236 
1237 /*
1238  * Prototypes for functions to support buf(9S) based IO.
1239  */
1240 static void sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg);
1241 static int sd_initpkt_for_buf(struct buf *, struct scsi_pkt **);
1242 static void sd_destroypkt_for_buf(struct buf *);
1243 static int sd_setup_rw_pkt(struct sd_lun *un, struct scsi_pkt **pktpp,
1244 	struct buf *bp, int flags,
1245 	int (*callback)(caddr_t), caddr_t callback_arg,
1246 	diskaddr_t lba, uint32_t blockcount);
1247 static int sd_setup_next_rw_pkt(struct sd_lun *un, struct scsi_pkt *pktp,
1248 	struct buf *bp, diskaddr_t lba, uint32_t blockcount);
1249 
1250 /*
1251  * Prototypes for functions to support USCSI IO.
1252  */
1253 static int sd_uscsi_strategy(struct buf *bp);
1254 static int sd_initpkt_for_uscsi(struct buf *, struct scsi_pkt **);
1255 static void sd_destroypkt_for_uscsi(struct buf *);
1256 
1257 static void sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
1258 	uchar_t chain_type, void *pktinfop);
1259 
1260 static int  sd_pm_entry(struct sd_lun *un);
1261 static void sd_pm_exit(struct sd_lun *un);
1262 
1263 static void sd_pm_idletimeout_handler(void *arg);
1264 
1265 /*
1266  * sd_core internal functions (used at the sd_core_io layer).
1267  */
1268 static void sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp);
1269 static void sdintr(struct scsi_pkt *pktp);
1270 static void sd_start_cmds(struct sd_lun *un, struct buf *immed_bp);
1271 
1272 static int sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
1273 	enum uio_seg dataspace, int path_flag);
1274 
1275 static struct buf *sd_bioclone_alloc(struct buf *bp, size_t datalen,
1276 	daddr_t blkno, int (*func)(struct buf *));
1277 static struct buf *sd_shadow_buf_alloc(struct buf *bp, size_t datalen,
1278 	uint_t bflags, daddr_t blkno, int (*func)(struct buf *));
1279 static void sd_bioclone_free(struct buf *bp);
1280 static void sd_shadow_buf_free(struct buf *bp);
1281 
1282 static void sd_print_transport_rejected_message(struct sd_lun *un,
1283 	struct sd_xbuf *xp, int code);
1284 static void sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp,
1285     void *arg, int code);
1286 static void sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp,
1287     void *arg, int code);
1288 static void sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp,
1289     void *arg, int code);
1290 
1291 static void sd_retry_command(struct sd_lun *un, struct buf *bp,
1292 	int retry_check_flag,
1293 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp,
1294 		int c),
1295 	void *user_arg, int failure_code,  clock_t retry_delay,
1296 	void (*statp)(kstat_io_t *));
1297 
1298 static void sd_set_retry_bp(struct sd_lun *un, struct buf *bp,
1299 	clock_t retry_delay, void (*statp)(kstat_io_t *));
1300 
1301 static void sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
1302 	struct scsi_pkt *pktp);
1303 static void sd_start_retry_command(void *arg);
1304 static void sd_start_direct_priority_command(void *arg);
1305 static void sd_return_failed_command(struct sd_lun *un, struct buf *bp,
1306 	int errcode);
1307 static void sd_return_failed_command_no_restart(struct sd_lun *un,
1308 	struct buf *bp, int errcode);
1309 static void sd_return_command(struct sd_lun *un, struct buf *bp);
1310 static void sd_sync_with_callback(struct sd_lun *un);
1311 static int sdrunout(caddr_t arg);
1312 
1313 static void sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp);
1314 static struct buf *sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *xp);
1315 
1316 static void sd_reduce_throttle(struct sd_lun *un, int throttle_type);
1317 static void sd_restore_throttle(void *arg);
1318 
1319 static void sd_init_cdb_limits(struct sd_lun *un);
1320 
1321 static void sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
1322 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1323 
1324 /*
1325  * Error handling functions
1326  */
1327 static void sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
1328 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1329 static void sd_pkt_status_busy(struct sd_lun *un, struct buf *bp,
1330 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1331 static void sd_pkt_status_reservation_conflict(struct sd_lun *un,
1332 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1333 static void sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
1334 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1335 
1336 static void sd_handle_request_sense(struct sd_lun *un, struct buf *bp,
1337 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1338 static void sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
1339 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1340 static int sd_validate_sense_data(struct sd_lun *un, struct buf *bp,
1341 	struct sd_xbuf *xp, size_t actual_len);
1342 static void sd_decode_sense(struct sd_lun *un, struct buf *bp,
1343 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1344 
1345 static void sd_print_sense_msg(struct sd_lun *un, struct buf *bp,
1346 	void *arg, int code);
1347 
1348 static void sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
1349 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1350 static void sd_sense_key_recoverable_error(struct sd_lun *un,
1351 	uint8_t *sense_datap,
1352 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1353 static void sd_sense_key_not_ready(struct sd_lun *un,
1354 	uint8_t *sense_datap,
1355 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1356 static void sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
1357 	uint8_t *sense_datap,
1358 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1359 static void sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
1360 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1361 static void sd_sense_key_unit_attention(struct sd_lun *un,
1362 	uint8_t *sense_datap,
1363 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1364 static void sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
1365 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1366 static void sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
1367 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1368 static void sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
1369 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1370 static void sd_sense_key_default(struct sd_lun *un,
1371 	uint8_t *sense_datap,
1372 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp);
1373 
1374 static void sd_print_retry_msg(struct sd_lun *un, struct buf *bp,
1375 	void *arg, int flag);
1376 
1377 static void sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
1378 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1379 static void sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
1380 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1381 static void sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
1382 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1383 static void sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
1384 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1385 static void sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
1386 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1387 static void sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
1388 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1389 static void sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
1390 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1391 static void sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
1392 	struct sd_xbuf *xp, struct scsi_pkt *pktp);
1393 
1394 static void sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp);
1395 
1396 static void sd_start_stop_unit_callback(void *arg);
1397 static void sd_start_stop_unit_task(void *arg);
1398 
1399 static void sd_taskq_create(void);
1400 static void sd_taskq_delete(void);
1401 static void sd_target_change_task(void *arg);
1402 static void sd_log_lun_expansion_event(struct sd_lun *un, int km_flag);
1403 static void sd_media_change_task(void *arg);
1404 
1405 static int sd_handle_mchange(struct sd_lun *un);
1406 static int sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag);
1407 static int sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp,
1408 	uint32_t *lbap, int path_flag);
1409 static int sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
1410 	uint32_t *lbap, int path_flag);
1411 static int sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag,
1412 	int path_flag);
1413 static int sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr,
1414 	size_t buflen, uchar_t evpd, uchar_t page_code, size_t *residp);
1415 static int sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag);
1416 static int sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un,
1417 	uchar_t usr_cmd, uint16_t data_len, uchar_t *data_bufp);
1418 static int sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un,
1419 	uchar_t usr_cmd, uchar_t *usr_bufp);
1420 static int sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un,
1421 	struct dk_callback *dkc);
1422 static int sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp);
1423 static int sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un,
1424 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1425 	uchar_t *bufaddr, uint_t buflen, int path_flag);
1426 static int sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
1427 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
1428 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag);
1429 static int sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize,
1430 	uchar_t *bufaddr, size_t buflen, uchar_t page_code, int path_flag);
1431 static int sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize,
1432 	uchar_t *bufaddr, size_t buflen, uchar_t save_page, int path_flag);
1433 static int sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
1434 	size_t buflen, daddr_t start_block, int path_flag);
1435 #define	sd_send_scsi_READ(un, bufaddr, buflen, start_block, path_flag)	\
1436 	sd_send_scsi_RDWR(un, SCMD_READ, bufaddr, buflen, start_block, \
1437 	path_flag)
1438 #define	sd_send_scsi_WRITE(un, bufaddr, buflen, start_block, path_flag)	\
1439 	sd_send_scsi_RDWR(un, SCMD_WRITE, bufaddr, buflen, start_block,\
1440 	path_flag)
1441 
1442 static int sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr,
1443 	uint16_t buflen, uchar_t page_code, uchar_t page_control,
1444 	uint16_t param_ptr, int path_flag);
1445 
1446 static int  sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un);
1447 static void sd_free_rqs(struct sd_lun *un);
1448 
1449 static void sd_dump_memory(struct sd_lun *un, uint_t comp, char *title,
1450 	uchar_t *data, int len, int fmt);
1451 static void sd_panic_for_res_conflict(struct sd_lun *un);
1452 
1453 /*
1454  * Disk Ioctl Function Prototypes
1455  */
1456 static int sd_get_media_info(dev_t dev, caddr_t arg, int flag);
1457 static int sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag);
1458 static int sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag);
1459 
1460 /*
1461  * Multi-host Ioctl Prototypes
1462  */
1463 static int sd_check_mhd(dev_t dev, int interval);
1464 static int sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1465 static void sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt);
1466 static char *sd_sname(uchar_t status);
1467 static void sd_mhd_resvd_recover(void *arg);
1468 static void sd_resv_reclaim_thread();
1469 static int sd_take_ownership(dev_t dev, struct mhioctkown *p);
1470 static int sd_reserve_release(dev_t dev, int cmd);
1471 static void sd_rmv_resv_reclaim_req(dev_t dev);
1472 static void sd_mhd_reset_notify_cb(caddr_t arg);
1473 static int sd_persistent_reservation_in_read_keys(struct sd_lun *un,
1474 	mhioc_inkeys_t *usrp, int flag);
1475 static int sd_persistent_reservation_in_read_resv(struct sd_lun *un,
1476 	mhioc_inresvs_t *usrp, int flag);
1477 static int sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag);
1478 static int sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag);
1479 static int sd_mhdioc_release(dev_t dev);
1480 static int sd_mhdioc_register_devid(dev_t dev);
1481 static int sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag);
1482 static int sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag);
1483 
1484 /*
1485  * SCSI removable prototypes
1486  */
1487 static int sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag);
1488 static int sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1489 static int sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag);
1490 static int sr_pause_resume(dev_t dev, int mode);
1491 static int sr_play_msf(dev_t dev, caddr_t data, int flag);
1492 static int sr_play_trkind(dev_t dev, caddr_t data, int flag);
1493 static int sr_read_all_subcodes(dev_t dev, caddr_t data, int flag);
1494 static int sr_read_subchannel(dev_t dev, caddr_t data, int flag);
1495 static int sr_read_tocentry(dev_t dev, caddr_t data, int flag);
1496 static int sr_read_tochdr(dev_t dev, caddr_t data, int flag);
1497 static int sr_read_cdda(dev_t dev, caddr_t data, int flag);
1498 static int sr_read_cdxa(dev_t dev, caddr_t data, int flag);
1499 static int sr_read_mode1(dev_t dev, caddr_t data, int flag);
1500 static int sr_read_mode2(dev_t dev, caddr_t data, int flag);
1501 static int sr_read_cd_mode2(dev_t dev, caddr_t data, int flag);
1502 static int sr_sector_mode(dev_t dev, uint32_t blksize);
1503 static int sr_eject(dev_t dev);
1504 static void sr_ejected(register struct sd_lun *un);
1505 static int sr_check_wp(dev_t dev);
1506 static int sd_check_media(dev_t dev, enum dkio_state state);
1507 static int sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp);
1508 static void sd_delayed_cv_broadcast(void *arg);
1509 static int sr_volume_ctrl(dev_t dev, caddr_t data, int flag);
1510 static int sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag);
1511 
1512 static int sd_log_page_supported(struct sd_lun *un, int log_page);
1513 
1514 /*
1515  * Function Prototype for the non-512 support (DVDRAM, MO etc.) functions.
1516  */
1517 static void sd_check_for_writable_cd(struct sd_lun *un, int path_flag);
1518 static int sd_wm_cache_constructor(void *wm, void *un, int flags);
1519 static void sd_wm_cache_destructor(void *wm, void *un);
1520 static struct sd_w_map *sd_range_lock(struct sd_lun *un, daddr_t startb,
1521 	daddr_t endb, ushort_t typ);
1522 static struct sd_w_map *sd_get_range(struct sd_lun *un, daddr_t startb,
1523 	daddr_t endb);
1524 static void sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp);
1525 static void sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm);
1526 static void sd_read_modify_write_task(void * arg);
1527 static int
1528 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
1529 	struct buf **bpp);
1530 
1531 
1532 /*
1533  * Function prototypes for failfast support.
1534  */
1535 static void sd_failfast_flushq(struct sd_lun *un);
1536 static int sd_failfast_flushq_callback(struct buf *bp);
1537 
1538 /*
1539  * Function prototypes to check for lsi devices
1540  */
1541 static void sd_is_lsi(struct sd_lun *un);
1542 
1543 /*
1544  * Function prototypes for partial DMA support
1545  */
1546 static int sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
1547 		struct scsi_pkt *pkt, struct sd_xbuf *xp);
1548 
1549 
1550 /* Function prototypes for cmlb */
1551 static int sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
1552     diskaddr_t start_block, size_t reqlength, void *tg_cookie);
1553 
1554 static int sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie);
1555 
1556 /*
1557  * Constants for failfast support:
1558  *
1559  * SD_FAILFAST_INACTIVE: Instance is currently in a normal state, with NO
1560  * failfast processing being performed.
1561  *
1562  * SD_FAILFAST_ACTIVE: Instance is in the failfast state and is performing
1563  * failfast processing on all bufs with B_FAILFAST set.
1564  */
1565 
1566 #define	SD_FAILFAST_INACTIVE		0
1567 #define	SD_FAILFAST_ACTIVE		1
1568 
1569 /*
1570  * Bitmask to control behavior of buf(9S) flushes when a transition to
1571  * the failfast state occurs. Optional bits include:
1572  *
1573  * SD_FAILFAST_FLUSH_ALL_BUFS: When set, flush ALL bufs including those that
1574  * do NOT have B_FAILFAST set. When clear, only bufs with B_FAILFAST will
1575  * be flushed.
1576  *
1577  * SD_FAILFAST_FLUSH_ALL_QUEUES: When set, flush any/all other queues in the
1578  * driver, in addition to the regular wait queue. This includes the xbuf
1579  * queues. When clear, only the driver's wait queue will be flushed.
1580  */
1581 #define	SD_FAILFAST_FLUSH_ALL_BUFS	0x01
1582 #define	SD_FAILFAST_FLUSH_ALL_QUEUES	0x02
1583 
1584 /*
1585  * The default behavior is to only flush bufs that have B_FAILFAST set, but
1586  * to flush all queues within the driver.
1587  */
1588 static int sd_failfast_flushctl = SD_FAILFAST_FLUSH_ALL_QUEUES;
1589 
1590 
1591 /*
1592  * SD Testing Fault Injection
1593  */
1594 #ifdef SD_FAULT_INJECTION
1595 static void sd_faultinjection_ioctl(int cmd, intptr_t arg, struct sd_lun *un);
1596 static void sd_faultinjection(struct scsi_pkt *pktp);
1597 static void sd_injection_log(char *buf, struct sd_lun *un);
1598 #endif
1599 
1600 /*
1601  * Device driver ops vector
1602  */
1603 static struct cb_ops sd_cb_ops = {
1604 	sdopen,			/* open */
1605 	sdclose,		/* close */
1606 	sdstrategy,		/* strategy */
1607 	nodev,			/* print */
1608 	sddump,			/* dump */
1609 	sdread,			/* read */
1610 	sdwrite,		/* write */
1611 	sdioctl,		/* ioctl */
1612 	nodev,			/* devmap */
1613 	nodev,			/* mmap */
1614 	nodev,			/* segmap */
1615 	nochpoll,		/* poll */
1616 	sd_prop_op,		/* cb_prop_op */
1617 	0,			/* streamtab  */
1618 	D_64BIT | D_MP | D_NEW | D_HOTPLUG, /* Driver compatibility flags */
1619 	CB_REV,			/* cb_rev */
1620 	sdaread, 		/* async I/O read entry point */
1621 	sdawrite		/* async I/O write entry point */
1622 };
1623 
1624 static struct dev_ops sd_ops = {
1625 	DEVO_REV,		/* devo_rev, */
1626 	0,			/* refcnt  */
1627 	sdinfo,			/* info */
1628 	nulldev,		/* identify */
1629 	sdprobe,		/* probe */
1630 	sdattach,		/* attach */
1631 	sddetach,		/* detach */
1632 	nodev,			/* reset */
1633 	&sd_cb_ops,		/* driver operations */
1634 	NULL,			/* bus operations */
1635 	sdpower			/* power */
1636 };
1637 
1638 
1639 /*
1640  * This is the loadable module wrapper.
1641  */
1642 #include <sys/modctl.h>
1643 
1644 static struct modldrv modldrv = {
1645 	&mod_driverops,		/* Type of module. This one is a driver */
1646 	SD_MODULE_NAME,		/* Module name. */
1647 	&sd_ops			/* driver ops */
1648 };
1649 
1650 
1651 static struct modlinkage modlinkage = {
1652 	MODREV_1,
1653 	&modldrv,
1654 	NULL
1655 };
1656 
1657 static cmlb_tg_ops_t sd_tgops = {
1658 	TG_DK_OPS_VERSION_1,
1659 	sd_tg_rdwr,
1660 	sd_tg_getinfo
1661 	};
1662 
1663 static struct scsi_asq_key_strings sd_additional_codes[] = {
1664 	0x81, 0, "Logical Unit is Reserved",
1665 	0x85, 0, "Audio Address Not Valid",
1666 	0xb6, 0, "Media Load Mechanism Failed",
1667 	0xB9, 0, "Audio Play Operation Aborted",
1668 	0xbf, 0, "Buffer Overflow for Read All Subcodes Command",
1669 	0x53, 2, "Medium removal prevented",
1670 	0x6f, 0, "Authentication failed during key exchange",
1671 	0x6f, 1, "Key not present",
1672 	0x6f, 2, "Key not established",
1673 	0x6f, 3, "Read without proper authentication",
1674 	0x6f, 4, "Mismatched region to this logical unit",
1675 	0x6f, 5, "Region reset count error",
1676 	0xffff, 0x0, NULL
1677 };
1678 
1679 
1680 /*
1681  * Struct for passing printing information for sense data messages
1682  */
1683 struct sd_sense_info {
1684 	int	ssi_severity;
1685 	int	ssi_pfa_flag;
1686 };
1687 
1688 /*
1689  * Table of function pointers for iostart-side routines. Separate "chains"
1690  * of layered function calls are formed by placing the function pointers
1691  * sequentially in the desired order. Functions are called according to an
1692  * incrementing table index ordering. The last function in each chain must
1693  * be sd_core_iostart(). The corresponding iodone-side routines are expected
1694  * in the sd_iodone_chain[] array.
1695  *
1696  * Note: It may seem more natural to organize both the iostart and iodone
1697  * functions together, into an array of structures (or some similar
1698  * organization) with a common index, rather than two separate arrays which
1699  * must be maintained in synchronization. The purpose of this division is
1700  * to achieve improved performance: individual arrays allows for more
1701  * effective cache line utilization on certain platforms.
1702  */
1703 
1704 typedef void (*sd_chain_t)(int index, struct sd_lun *un, struct buf *bp);
1705 
1706 
1707 static sd_chain_t sd_iostart_chain[] = {
1708 
1709 	/* Chain for buf IO for disk drive targets (PM enabled) */
1710 	sd_mapblockaddr_iostart,	/* Index: 0 */
1711 	sd_pm_iostart,			/* Index: 1 */
1712 	sd_core_iostart,		/* Index: 2 */
1713 
1714 	/* Chain for buf IO for disk drive targets (PM disabled) */
1715 	sd_mapblockaddr_iostart,	/* Index: 3 */
1716 	sd_core_iostart,		/* Index: 4 */
1717 
1718 	/* Chain for buf IO for removable-media targets (PM enabled) */
1719 	sd_mapblockaddr_iostart,	/* Index: 5 */
1720 	sd_mapblocksize_iostart,	/* Index: 6 */
1721 	sd_pm_iostart,			/* Index: 7 */
1722 	sd_core_iostart,		/* Index: 8 */
1723 
1724 	/* Chain for buf IO for removable-media targets (PM disabled) */
1725 	sd_mapblockaddr_iostart,	/* Index: 9 */
1726 	sd_mapblocksize_iostart,	/* Index: 10 */
1727 	sd_core_iostart,		/* Index: 11 */
1728 
1729 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1730 	sd_mapblockaddr_iostart,	/* Index: 12 */
1731 	sd_checksum_iostart,		/* Index: 13 */
1732 	sd_pm_iostart,			/* Index: 14 */
1733 	sd_core_iostart,		/* Index: 15 */
1734 
1735 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1736 	sd_mapblockaddr_iostart,	/* Index: 16 */
1737 	sd_checksum_iostart,		/* Index: 17 */
1738 	sd_core_iostart,		/* Index: 18 */
1739 
1740 	/* Chain for USCSI commands (all targets) */
1741 	sd_pm_iostart,			/* Index: 19 */
1742 	sd_core_iostart,		/* Index: 20 */
1743 
1744 	/* Chain for checksumming USCSI commands (all targets) */
1745 	sd_checksum_uscsi_iostart,	/* Index: 21 */
1746 	sd_pm_iostart,			/* Index: 22 */
1747 	sd_core_iostart,		/* Index: 23 */
1748 
1749 	/* Chain for "direct" USCSI commands (all targets) */
1750 	sd_core_iostart,		/* Index: 24 */
1751 
1752 	/* Chain for "direct priority" USCSI commands (all targets) */
1753 	sd_core_iostart,		/* Index: 25 */
1754 };
1755 
1756 /*
1757  * Macros to locate the first function of each iostart chain in the
1758  * sd_iostart_chain[] array. These are located by the index in the array.
1759  */
1760 #define	SD_CHAIN_DISK_IOSTART			0
1761 #define	SD_CHAIN_DISK_IOSTART_NO_PM		3
1762 #define	SD_CHAIN_RMMEDIA_IOSTART		5
1763 #define	SD_CHAIN_RMMEDIA_IOSTART_NO_PM		9
1764 #define	SD_CHAIN_CHKSUM_IOSTART			12
1765 #define	SD_CHAIN_CHKSUM_IOSTART_NO_PM		16
1766 #define	SD_CHAIN_USCSI_CMD_IOSTART		19
1767 #define	SD_CHAIN_USCSI_CHKSUM_IOSTART		21
1768 #define	SD_CHAIN_DIRECT_CMD_IOSTART		24
1769 #define	SD_CHAIN_PRIORITY_CMD_IOSTART		25
1770 
1771 
1772 /*
1773  * Table of function pointers for the iodone-side routines for the driver-
1774  * internal layering mechanism.  The calling sequence for iodone routines
1775  * uses a decrementing table index, so the last routine called in a chain
1776  * must be at the lowest array index location for that chain.  The last
1777  * routine for each chain must be either sd_buf_iodone() (for buf(9S) IOs)
1778  * or sd_uscsi_iodone() (for uscsi IOs).  Other than this, the ordering
1779  * of the functions in an iodone side chain must correspond to the ordering
1780  * of the iostart routines for that chain.  Note that there is no iodone
1781  * side routine that corresponds to sd_core_iostart(), so there is no
1782  * entry in the table for this.
1783  */
1784 
1785 static sd_chain_t sd_iodone_chain[] = {
1786 
1787 	/* Chain for buf IO for disk drive targets (PM enabled) */
1788 	sd_buf_iodone,			/* Index: 0 */
1789 	sd_mapblockaddr_iodone,		/* Index: 1 */
1790 	sd_pm_iodone,			/* Index: 2 */
1791 
1792 	/* Chain for buf IO for disk drive targets (PM disabled) */
1793 	sd_buf_iodone,			/* Index: 3 */
1794 	sd_mapblockaddr_iodone,		/* Index: 4 */
1795 
1796 	/* Chain for buf IO for removable-media targets (PM enabled) */
1797 	sd_buf_iodone,			/* Index: 5 */
1798 	sd_mapblockaddr_iodone,		/* Index: 6 */
1799 	sd_mapblocksize_iodone,		/* Index: 7 */
1800 	sd_pm_iodone,			/* Index: 8 */
1801 
1802 	/* Chain for buf IO for removable-media targets (PM disabled) */
1803 	sd_buf_iodone,			/* Index: 9 */
1804 	sd_mapblockaddr_iodone,		/* Index: 10 */
1805 	sd_mapblocksize_iodone,		/* Index: 11 */
1806 
1807 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1808 	sd_buf_iodone,			/* Index: 12 */
1809 	sd_mapblockaddr_iodone,		/* Index: 13 */
1810 	sd_checksum_iodone,		/* Index: 14 */
1811 	sd_pm_iodone,			/* Index: 15 */
1812 
1813 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1814 	sd_buf_iodone,			/* Index: 16 */
1815 	sd_mapblockaddr_iodone,		/* Index: 17 */
1816 	sd_checksum_iodone,		/* Index: 18 */
1817 
1818 	/* Chain for USCSI commands (non-checksum targets) */
1819 	sd_uscsi_iodone,		/* Index: 19 */
1820 	sd_pm_iodone,			/* Index: 20 */
1821 
1822 	/* Chain for USCSI commands (checksum targets) */
1823 	sd_uscsi_iodone,		/* Index: 21 */
1824 	sd_checksum_uscsi_iodone,	/* Index: 22 */
1825 	sd_pm_iodone,			/* Index: 22 */
1826 
1827 	/* Chain for "direct" USCSI commands (all targets) */
1828 	sd_uscsi_iodone,		/* Index: 24 */
1829 
1830 	/* Chain for "direct priority" USCSI commands (all targets) */
1831 	sd_uscsi_iodone,		/* Index: 25 */
1832 };
1833 
1834 
1835 /*
1836  * Macros to locate the "first" function in the sd_iodone_chain[] array for
1837  * each iodone-side chain. These are located by the array index, but as the
1838  * iodone side functions are called in a decrementing-index order, the
1839  * highest index number in each chain must be specified (as these correspond
1840  * to the first function in the iodone chain that will be called by the core
1841  * at IO completion time).
1842  */
1843 
1844 #define	SD_CHAIN_DISK_IODONE			2
1845 #define	SD_CHAIN_DISK_IODONE_NO_PM		4
1846 #define	SD_CHAIN_RMMEDIA_IODONE			8
1847 #define	SD_CHAIN_RMMEDIA_IODONE_NO_PM		11
1848 #define	SD_CHAIN_CHKSUM_IODONE			15
1849 #define	SD_CHAIN_CHKSUM_IODONE_NO_PM		18
1850 #define	SD_CHAIN_USCSI_CMD_IODONE		20
1851 #define	SD_CHAIN_USCSI_CHKSUM_IODONE		22
1852 #define	SD_CHAIN_DIRECT_CMD_IODONE		24
1853 #define	SD_CHAIN_PRIORITY_CMD_IODONE		25
1854 
1855 
1856 
1857 
1858 /*
1859  * Array to map a layering chain index to the appropriate initpkt routine.
1860  * The redundant entries are present so that the index used for accessing
1861  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1862  * with this table as well.
1863  */
1864 typedef int (*sd_initpkt_t)(struct buf *, struct scsi_pkt **);
1865 
1866 static sd_initpkt_t	sd_initpkt_map[] = {
1867 
1868 	/* Chain for buf IO for disk drive targets (PM enabled) */
1869 	sd_initpkt_for_buf,		/* Index: 0 */
1870 	sd_initpkt_for_buf,		/* Index: 1 */
1871 	sd_initpkt_for_buf,		/* Index: 2 */
1872 
1873 	/* Chain for buf IO for disk drive targets (PM disabled) */
1874 	sd_initpkt_for_buf,		/* Index: 3 */
1875 	sd_initpkt_for_buf,		/* Index: 4 */
1876 
1877 	/* Chain for buf IO for removable-media targets (PM enabled) */
1878 	sd_initpkt_for_buf,		/* Index: 5 */
1879 	sd_initpkt_for_buf,		/* Index: 6 */
1880 	sd_initpkt_for_buf,		/* Index: 7 */
1881 	sd_initpkt_for_buf,		/* Index: 8 */
1882 
1883 	/* Chain for buf IO for removable-media targets (PM disabled) */
1884 	sd_initpkt_for_buf,		/* Index: 9 */
1885 	sd_initpkt_for_buf,		/* Index: 10 */
1886 	sd_initpkt_for_buf,		/* Index: 11 */
1887 
1888 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1889 	sd_initpkt_for_buf,		/* Index: 12 */
1890 	sd_initpkt_for_buf,		/* Index: 13 */
1891 	sd_initpkt_for_buf,		/* Index: 14 */
1892 	sd_initpkt_for_buf,		/* Index: 15 */
1893 
1894 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1895 	sd_initpkt_for_buf,		/* Index: 16 */
1896 	sd_initpkt_for_buf,		/* Index: 17 */
1897 	sd_initpkt_for_buf,		/* Index: 18 */
1898 
1899 	/* Chain for USCSI commands (non-checksum targets) */
1900 	sd_initpkt_for_uscsi,		/* Index: 19 */
1901 	sd_initpkt_for_uscsi,		/* Index: 20 */
1902 
1903 	/* Chain for USCSI commands (checksum targets) */
1904 	sd_initpkt_for_uscsi,		/* Index: 21 */
1905 	sd_initpkt_for_uscsi,		/* Index: 22 */
1906 	sd_initpkt_for_uscsi,		/* Index: 22 */
1907 
1908 	/* Chain for "direct" USCSI commands (all targets) */
1909 	sd_initpkt_for_uscsi,		/* Index: 24 */
1910 
1911 	/* Chain for "direct priority" USCSI commands (all targets) */
1912 	sd_initpkt_for_uscsi,		/* Index: 25 */
1913 
1914 };
1915 
1916 
1917 /*
1918  * Array to map a layering chain index to the appropriate destroypktpkt routine.
1919  * The redundant entries are present so that the index used for accessing
1920  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1921  * with this table as well.
1922  */
1923 typedef void (*sd_destroypkt_t)(struct buf *);
1924 
1925 static sd_destroypkt_t	sd_destroypkt_map[] = {
1926 
1927 	/* Chain for buf IO for disk drive targets (PM enabled) */
1928 	sd_destroypkt_for_buf,		/* Index: 0 */
1929 	sd_destroypkt_for_buf,		/* Index: 1 */
1930 	sd_destroypkt_for_buf,		/* Index: 2 */
1931 
1932 	/* Chain for buf IO for disk drive targets (PM disabled) */
1933 	sd_destroypkt_for_buf,		/* Index: 3 */
1934 	sd_destroypkt_for_buf,		/* Index: 4 */
1935 
1936 	/* Chain for buf IO for removable-media targets (PM enabled) */
1937 	sd_destroypkt_for_buf,		/* Index: 5 */
1938 	sd_destroypkt_for_buf,		/* Index: 6 */
1939 	sd_destroypkt_for_buf,		/* Index: 7 */
1940 	sd_destroypkt_for_buf,		/* Index: 8 */
1941 
1942 	/* Chain for buf IO for removable-media targets (PM disabled) */
1943 	sd_destroypkt_for_buf,		/* Index: 9 */
1944 	sd_destroypkt_for_buf,		/* Index: 10 */
1945 	sd_destroypkt_for_buf,		/* Index: 11 */
1946 
1947 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
1948 	sd_destroypkt_for_buf,		/* Index: 12 */
1949 	sd_destroypkt_for_buf,		/* Index: 13 */
1950 	sd_destroypkt_for_buf,		/* Index: 14 */
1951 	sd_destroypkt_for_buf,		/* Index: 15 */
1952 
1953 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
1954 	sd_destroypkt_for_buf,		/* Index: 16 */
1955 	sd_destroypkt_for_buf,		/* Index: 17 */
1956 	sd_destroypkt_for_buf,		/* Index: 18 */
1957 
1958 	/* Chain for USCSI commands (non-checksum targets) */
1959 	sd_destroypkt_for_uscsi,	/* Index: 19 */
1960 	sd_destroypkt_for_uscsi,	/* Index: 20 */
1961 
1962 	/* Chain for USCSI commands (checksum targets) */
1963 	sd_destroypkt_for_uscsi,	/* Index: 21 */
1964 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1965 	sd_destroypkt_for_uscsi,	/* Index: 22 */
1966 
1967 	/* Chain for "direct" USCSI commands (all targets) */
1968 	sd_destroypkt_for_uscsi,	/* Index: 24 */
1969 
1970 	/* Chain for "direct priority" USCSI commands (all targets) */
1971 	sd_destroypkt_for_uscsi,	/* Index: 25 */
1972 
1973 };
1974 
1975 
1976 
1977 /*
1978  * Array to map a layering chain index to the appropriate chain "type".
1979  * The chain type indicates a specific property/usage of the chain.
1980  * The redundant entries are present so that the index used for accessing
1981  * the above sd_iostart_chain and sd_iodone_chain tables can be used directly
1982  * with this table as well.
1983  */
1984 
1985 #define	SD_CHAIN_NULL			0	/* for the special RQS cmd */
1986 #define	SD_CHAIN_BUFIO			1	/* regular buf IO */
1987 #define	SD_CHAIN_USCSI			2	/* regular USCSI commands */
1988 #define	SD_CHAIN_DIRECT			3	/* uscsi, w/ bypass power mgt */
1989 #define	SD_CHAIN_DIRECT_PRIORITY	4	/* uscsi, w/ bypass power mgt */
1990 						/* (for error recovery) */
1991 
1992 static int sd_chain_type_map[] = {
1993 
1994 	/* Chain for buf IO for disk drive targets (PM enabled) */
1995 	SD_CHAIN_BUFIO,			/* Index: 0 */
1996 	SD_CHAIN_BUFIO,			/* Index: 1 */
1997 	SD_CHAIN_BUFIO,			/* Index: 2 */
1998 
1999 	/* Chain for buf IO for disk drive targets (PM disabled) */
2000 	SD_CHAIN_BUFIO,			/* Index: 3 */
2001 	SD_CHAIN_BUFIO,			/* Index: 4 */
2002 
2003 	/* Chain for buf IO for removable-media targets (PM enabled) */
2004 	SD_CHAIN_BUFIO,			/* Index: 5 */
2005 	SD_CHAIN_BUFIO,			/* Index: 6 */
2006 	SD_CHAIN_BUFIO,			/* Index: 7 */
2007 	SD_CHAIN_BUFIO,			/* Index: 8 */
2008 
2009 	/* Chain for buf IO for removable-media targets (PM disabled) */
2010 	SD_CHAIN_BUFIO,			/* Index: 9 */
2011 	SD_CHAIN_BUFIO,			/* Index: 10 */
2012 	SD_CHAIN_BUFIO,			/* Index: 11 */
2013 
2014 	/* Chain for buf IO for disk drives with checksumming (PM enabled) */
2015 	SD_CHAIN_BUFIO,			/* Index: 12 */
2016 	SD_CHAIN_BUFIO,			/* Index: 13 */
2017 	SD_CHAIN_BUFIO,			/* Index: 14 */
2018 	SD_CHAIN_BUFIO,			/* Index: 15 */
2019 
2020 	/* Chain for buf IO for disk drives with checksumming (PM disabled) */
2021 	SD_CHAIN_BUFIO,			/* Index: 16 */
2022 	SD_CHAIN_BUFIO,			/* Index: 17 */
2023 	SD_CHAIN_BUFIO,			/* Index: 18 */
2024 
2025 	/* Chain for USCSI commands (non-checksum targets) */
2026 	SD_CHAIN_USCSI,			/* Index: 19 */
2027 	SD_CHAIN_USCSI,			/* Index: 20 */
2028 
2029 	/* Chain for USCSI commands (checksum targets) */
2030 	SD_CHAIN_USCSI,			/* Index: 21 */
2031 	SD_CHAIN_USCSI,			/* Index: 22 */
2032 	SD_CHAIN_USCSI,			/* Index: 22 */
2033 
2034 	/* Chain for "direct" USCSI commands (all targets) */
2035 	SD_CHAIN_DIRECT,		/* Index: 24 */
2036 
2037 	/* Chain for "direct priority" USCSI commands (all targets) */
2038 	SD_CHAIN_DIRECT_PRIORITY,	/* Index: 25 */
2039 };
2040 
2041 
2042 /* Macro to return TRUE if the IO has come from the sd_buf_iostart() chain. */
2043 #define	SD_IS_BUFIO(xp)			\
2044 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_BUFIO)
2045 
2046 /* Macro to return TRUE if the IO has come from the "direct priority" chain. */
2047 #define	SD_IS_DIRECT_PRIORITY(xp)	\
2048 	(sd_chain_type_map[(xp)->xb_chain_iostart] == SD_CHAIN_DIRECT_PRIORITY)
2049 
2050 
2051 
2052 /*
2053  * Struct, array, and macros to map a specific chain to the appropriate
2054  * layering indexes in the sd_iostart_chain[] and sd_iodone_chain[] arrays.
2055  *
2056  * The sd_chain_index_map[] array is used at attach time to set the various
2057  * un_xxx_chain type members of the sd_lun softstate to the specific layering
2058  * chain to be used with the instance. This allows different instances to use
2059  * different chain for buf IO, uscsi IO, etc.. Also, since the xb_chain_iostart
2060  * and xb_chain_iodone index values in the sd_xbuf are initialized to these
2061  * values at sd_xbuf init time, this allows (1) layering chains may be changed
2062  * dynamically & without the use of locking; and (2) a layer may update the
2063  * xb_chain_io[start|done] member in a given xbuf with its current index value,
2064  * to allow for deferred processing of an IO within the same chain from a
2065  * different execution context.
2066  */
2067 
2068 struct sd_chain_index {
2069 	int	sci_iostart_index;
2070 	int	sci_iodone_index;
2071 };
2072 
2073 static struct sd_chain_index	sd_chain_index_map[] = {
2074 	{ SD_CHAIN_DISK_IOSTART,		SD_CHAIN_DISK_IODONE },
2075 	{ SD_CHAIN_DISK_IOSTART_NO_PM,		SD_CHAIN_DISK_IODONE_NO_PM },
2076 	{ SD_CHAIN_RMMEDIA_IOSTART,		SD_CHAIN_RMMEDIA_IODONE },
2077 	{ SD_CHAIN_RMMEDIA_IOSTART_NO_PM,	SD_CHAIN_RMMEDIA_IODONE_NO_PM },
2078 	{ SD_CHAIN_CHKSUM_IOSTART,		SD_CHAIN_CHKSUM_IODONE },
2079 	{ SD_CHAIN_CHKSUM_IOSTART_NO_PM,	SD_CHAIN_CHKSUM_IODONE_NO_PM },
2080 	{ SD_CHAIN_USCSI_CMD_IOSTART,		SD_CHAIN_USCSI_CMD_IODONE },
2081 	{ SD_CHAIN_USCSI_CHKSUM_IOSTART,	SD_CHAIN_USCSI_CHKSUM_IODONE },
2082 	{ SD_CHAIN_DIRECT_CMD_IOSTART,		SD_CHAIN_DIRECT_CMD_IODONE },
2083 	{ SD_CHAIN_PRIORITY_CMD_IOSTART,	SD_CHAIN_PRIORITY_CMD_IODONE },
2084 };
2085 
2086 
2087 /*
2088  * The following are indexes into the sd_chain_index_map[] array.
2089  */
2090 
2091 /* un->un_buf_chain_type must be set to one of these */
2092 #define	SD_CHAIN_INFO_DISK		0
2093 #define	SD_CHAIN_INFO_DISK_NO_PM	1
2094 #define	SD_CHAIN_INFO_RMMEDIA		2
2095 #define	SD_CHAIN_INFO_RMMEDIA_NO_PM	3
2096 #define	SD_CHAIN_INFO_CHKSUM		4
2097 #define	SD_CHAIN_INFO_CHKSUM_NO_PM	5
2098 
2099 /* un->un_uscsi_chain_type must be set to one of these */
2100 #define	SD_CHAIN_INFO_USCSI_CMD		6
2101 /* USCSI with PM disabled is the same as DIRECT */
2102 #define	SD_CHAIN_INFO_USCSI_CMD_NO_PM	8
2103 #define	SD_CHAIN_INFO_USCSI_CHKSUM	7
2104 
2105 /* un->un_direct_chain_type must be set to one of these */
2106 #define	SD_CHAIN_INFO_DIRECT_CMD	8
2107 
2108 /* un->un_priority_chain_type must be set to one of these */
2109 #define	SD_CHAIN_INFO_PRIORITY_CMD	9
2110 
2111 /* size for devid inquiries */
2112 #define	MAX_INQUIRY_SIZE		0xF0
2113 
2114 /*
2115  * Macros used by functions to pass a given buf(9S) struct along to the
2116  * next function in the layering chain for further processing.
2117  *
2118  * In the following macros, passing more than three arguments to the called
2119  * routines causes the optimizer for the SPARC compiler to stop doing tail
2120  * call elimination which results in significant performance degradation.
2121  */
2122 #define	SD_BEGIN_IOSTART(index, un, bp)	\
2123 	((*(sd_iostart_chain[index]))(index, un, bp))
2124 
2125 #define	SD_BEGIN_IODONE(index, un, bp)	\
2126 	((*(sd_iodone_chain[index]))(index, un, bp))
2127 
2128 #define	SD_NEXT_IOSTART(index, un, bp)				\
2129 	((*(sd_iostart_chain[(index) + 1]))((index) + 1, un, bp))
2130 
2131 #define	SD_NEXT_IODONE(index, un, bp)				\
2132 	((*(sd_iodone_chain[(index) - 1]))((index) - 1, un, bp))
2133 
2134 /*
2135  *    Function: _init
2136  *
2137  * Description: This is the driver _init(9E) entry point.
2138  *
2139  * Return Code: Returns the value from mod_install(9F) or
2140  *		ddi_soft_state_init(9F) as appropriate.
2141  *
2142  *     Context: Called when driver module loaded.
2143  */
2144 
2145 int
2146 _init(void)
2147 {
2148 	int	err;
2149 
2150 	/* establish driver name from module name */
2151 	sd_label = (char *)mod_modname(&modlinkage);
2152 
2153 	err = ddi_soft_state_init(&sd_state, sizeof (struct sd_lun),
2154 	    SD_MAXUNIT);
2155 
2156 	if (err != 0) {
2157 		return (err);
2158 	}
2159 
2160 	mutex_init(&sd_detach_mutex, NULL, MUTEX_DRIVER, NULL);
2161 	mutex_init(&sd_log_mutex,    NULL, MUTEX_DRIVER, NULL);
2162 	mutex_init(&sd_label_mutex,  NULL, MUTEX_DRIVER, NULL);
2163 
2164 	mutex_init(&sd_tr.srq_resv_reclaim_mutex, NULL, MUTEX_DRIVER, NULL);
2165 	cv_init(&sd_tr.srq_resv_reclaim_cv, NULL, CV_DRIVER, NULL);
2166 	cv_init(&sd_tr.srq_inprocess_cv, NULL, CV_DRIVER, NULL);
2167 
2168 	/*
2169 	 * it's ok to init here even for fibre device
2170 	 */
2171 	sd_scsi_probe_cache_init();
2172 
2173 	sd_scsi_target_lun_init();
2174 
2175 	/*
2176 	 * Creating taskq before mod_install ensures that all callers (threads)
2177 	 * that enter the module after a successfull mod_install encounter
2178 	 * a valid taskq.
2179 	 */
2180 	sd_taskq_create();
2181 
2182 	err = mod_install(&modlinkage);
2183 	if (err != 0) {
2184 		/* delete taskq if install fails */
2185 		sd_taskq_delete();
2186 
2187 		mutex_destroy(&sd_detach_mutex);
2188 		mutex_destroy(&sd_log_mutex);
2189 		mutex_destroy(&sd_label_mutex);
2190 
2191 		mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2192 		cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2193 		cv_destroy(&sd_tr.srq_inprocess_cv);
2194 
2195 		sd_scsi_probe_cache_fini();
2196 
2197 		sd_scsi_target_lun_fini();
2198 
2199 		ddi_soft_state_fini(&sd_state);
2200 		return (err);
2201 	}
2202 
2203 	return (err);
2204 }
2205 
2206 
2207 /*
2208  *    Function: _fini
2209  *
2210  * Description: This is the driver _fini(9E) entry point.
2211  *
2212  * Return Code: Returns the value from mod_remove(9F)
2213  *
2214  *     Context: Called when driver module is unloaded.
2215  */
2216 
2217 int
2218 _fini(void)
2219 {
2220 	int err;
2221 
2222 	if ((err = mod_remove(&modlinkage)) != 0) {
2223 		return (err);
2224 	}
2225 
2226 	sd_taskq_delete();
2227 
2228 	mutex_destroy(&sd_detach_mutex);
2229 	mutex_destroy(&sd_log_mutex);
2230 	mutex_destroy(&sd_label_mutex);
2231 	mutex_destroy(&sd_tr.srq_resv_reclaim_mutex);
2232 
2233 	sd_scsi_probe_cache_fini();
2234 
2235 	sd_scsi_target_lun_fini();
2236 
2237 	cv_destroy(&sd_tr.srq_resv_reclaim_cv);
2238 	cv_destroy(&sd_tr.srq_inprocess_cv);
2239 
2240 	ddi_soft_state_fini(&sd_state);
2241 
2242 	return (err);
2243 }
2244 
2245 
2246 /*
2247  *    Function: _info
2248  *
2249  * Description: This is the driver _info(9E) entry point.
2250  *
2251  *   Arguments: modinfop - pointer to the driver modinfo structure
2252  *
2253  * Return Code: Returns the value from mod_info(9F).
2254  *
2255  *     Context: Kernel thread context
2256  */
2257 
2258 int
2259 _info(struct modinfo *modinfop)
2260 {
2261 	return (mod_info(&modlinkage, modinfop));
2262 }
2263 
2264 
2265 /*
2266  * The following routines implement the driver message logging facility.
2267  * They provide component- and level- based debug output filtering.
2268  * Output may also be restricted to messages for a single instance by
2269  * specifying a soft state pointer in sd_debug_un. If sd_debug_un is set
2270  * to NULL, then messages for all instances are printed.
2271  *
2272  * These routines have been cloned from each other due to the language
2273  * constraints of macros and variable argument list processing.
2274  */
2275 
2276 
2277 /*
2278  *    Function: sd_log_err
2279  *
2280  * Description: This routine is called by the SD_ERROR macro for debug
2281  *		logging of error conditions.
2282  *
2283  *   Arguments: comp - driver component being logged
2284  *		dev  - pointer to driver info structure
2285  *		fmt  - error string and format to be logged
2286  */
2287 
2288 static void
2289 sd_log_err(uint_t comp, struct sd_lun *un, const char *fmt, ...)
2290 {
2291 	va_list		ap;
2292 	dev_info_t	*dev;
2293 
2294 	ASSERT(un != NULL);
2295 	dev = SD_DEVINFO(un);
2296 	ASSERT(dev != NULL);
2297 
2298 	/*
2299 	 * Filter messages based on the global component and level masks.
2300 	 * Also print if un matches the value of sd_debug_un, or if
2301 	 * sd_debug_un is set to NULL.
2302 	 */
2303 	if ((sd_component_mask & comp) && (sd_level_mask & SD_LOGMASK_ERROR) &&
2304 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2305 		mutex_enter(&sd_log_mutex);
2306 		va_start(ap, fmt);
2307 		(void) vsprintf(sd_log_buf, fmt, ap);
2308 		va_end(ap);
2309 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2310 		mutex_exit(&sd_log_mutex);
2311 	}
2312 #ifdef SD_FAULT_INJECTION
2313 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2314 	if (un->sd_injection_mask & comp) {
2315 		mutex_enter(&sd_log_mutex);
2316 		va_start(ap, fmt);
2317 		(void) vsprintf(sd_log_buf, fmt, ap);
2318 		va_end(ap);
2319 		sd_injection_log(sd_log_buf, un);
2320 		mutex_exit(&sd_log_mutex);
2321 	}
2322 #endif
2323 }
2324 
2325 
2326 /*
2327  *    Function: sd_log_info
2328  *
2329  * Description: This routine is called by the SD_INFO macro for debug
2330  *		logging of general purpose informational conditions.
2331  *
2332  *   Arguments: comp - driver component being logged
2333  *		dev  - pointer to driver info structure
2334  *		fmt  - info string and format to be logged
2335  */
2336 
2337 static void
2338 sd_log_info(uint_t component, struct sd_lun *un, const char *fmt, ...)
2339 {
2340 	va_list		ap;
2341 	dev_info_t	*dev;
2342 
2343 	ASSERT(un != NULL);
2344 	dev = SD_DEVINFO(un);
2345 	ASSERT(dev != NULL);
2346 
2347 	/*
2348 	 * Filter messages based on the global component and level masks.
2349 	 * Also print if un matches the value of sd_debug_un, or if
2350 	 * sd_debug_un is set to NULL.
2351 	 */
2352 	if ((sd_component_mask & component) &&
2353 	    (sd_level_mask & SD_LOGMASK_INFO) &&
2354 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2355 		mutex_enter(&sd_log_mutex);
2356 		va_start(ap, fmt);
2357 		(void) vsprintf(sd_log_buf, fmt, ap);
2358 		va_end(ap);
2359 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2360 		mutex_exit(&sd_log_mutex);
2361 	}
2362 #ifdef SD_FAULT_INJECTION
2363 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2364 	if (un->sd_injection_mask & component) {
2365 		mutex_enter(&sd_log_mutex);
2366 		va_start(ap, fmt);
2367 		(void) vsprintf(sd_log_buf, fmt, ap);
2368 		va_end(ap);
2369 		sd_injection_log(sd_log_buf, un);
2370 		mutex_exit(&sd_log_mutex);
2371 	}
2372 #endif
2373 }
2374 
2375 
2376 /*
2377  *    Function: sd_log_trace
2378  *
2379  * Description: This routine is called by the SD_TRACE macro for debug
2380  *		logging of trace conditions (i.e. function entry/exit).
2381  *
2382  *   Arguments: comp - driver component being logged
2383  *		dev  - pointer to driver info structure
2384  *		fmt  - trace string and format to be logged
2385  */
2386 
2387 static void
2388 sd_log_trace(uint_t component, struct sd_lun *un, const char *fmt, ...)
2389 {
2390 	va_list		ap;
2391 	dev_info_t	*dev;
2392 
2393 	ASSERT(un != NULL);
2394 	dev = SD_DEVINFO(un);
2395 	ASSERT(dev != NULL);
2396 
2397 	/*
2398 	 * Filter messages based on the global component and level masks.
2399 	 * Also print if un matches the value of sd_debug_un, or if
2400 	 * sd_debug_un is set to NULL.
2401 	 */
2402 	if ((sd_component_mask & component) &&
2403 	    (sd_level_mask & SD_LOGMASK_TRACE) &&
2404 	    ((sd_debug_un == NULL) || (sd_debug_un == un))) {
2405 		mutex_enter(&sd_log_mutex);
2406 		va_start(ap, fmt);
2407 		(void) vsprintf(sd_log_buf, fmt, ap);
2408 		va_end(ap);
2409 		scsi_log(dev, sd_label, CE_CONT, "%s", sd_log_buf);
2410 		mutex_exit(&sd_log_mutex);
2411 	}
2412 #ifdef SD_FAULT_INJECTION
2413 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::sd_injection_mask));
2414 	if (un->sd_injection_mask & component) {
2415 		mutex_enter(&sd_log_mutex);
2416 		va_start(ap, fmt);
2417 		(void) vsprintf(sd_log_buf, fmt, ap);
2418 		va_end(ap);
2419 		sd_injection_log(sd_log_buf, un);
2420 		mutex_exit(&sd_log_mutex);
2421 	}
2422 #endif
2423 }
2424 
2425 
2426 /*
2427  *    Function: sdprobe
2428  *
2429  * Description: This is the driver probe(9e) entry point function.
2430  *
2431  *   Arguments: devi - opaque device info handle
2432  *
2433  * Return Code: DDI_PROBE_SUCCESS: If the probe was successful.
2434  *              DDI_PROBE_FAILURE: If the probe failed.
2435  *              DDI_PROBE_PARTIAL: If the instance is not present now,
2436  *				   but may be present in the future.
2437  */
2438 
2439 static int
2440 sdprobe(dev_info_t *devi)
2441 {
2442 	struct scsi_device	*devp;
2443 	int			rval;
2444 	int			instance;
2445 
2446 	/*
2447 	 * if it wasn't for pln, sdprobe could actually be nulldev
2448 	 * in the "__fibre" case.
2449 	 */
2450 	if (ddi_dev_is_sid(devi) == DDI_SUCCESS) {
2451 		return (DDI_PROBE_DONTCARE);
2452 	}
2453 
2454 	devp = ddi_get_driver_private(devi);
2455 
2456 	if (devp == NULL) {
2457 		/* Ooops... nexus driver is mis-configured... */
2458 		return (DDI_PROBE_FAILURE);
2459 	}
2460 
2461 	instance = ddi_get_instance(devi);
2462 
2463 	if (ddi_get_soft_state(sd_state, instance) != NULL) {
2464 		return (DDI_PROBE_PARTIAL);
2465 	}
2466 
2467 	/*
2468 	 * Call the SCSA utility probe routine to see if we actually
2469 	 * have a target at this SCSI nexus.
2470 	 */
2471 	switch (sd_scsi_probe_with_cache(devp, NULL_FUNC)) {
2472 	case SCSIPROBE_EXISTS:
2473 		switch (devp->sd_inq->inq_dtype) {
2474 		case DTYPE_DIRECT:
2475 			rval = DDI_PROBE_SUCCESS;
2476 			break;
2477 		case DTYPE_RODIRECT:
2478 			/* CDs etc. Can be removable media */
2479 			rval = DDI_PROBE_SUCCESS;
2480 			break;
2481 		case DTYPE_OPTICAL:
2482 			/*
2483 			 * Rewritable optical driver HP115AA
2484 			 * Can also be removable media
2485 			 */
2486 
2487 			/*
2488 			 * Do not attempt to bind to  DTYPE_OPTICAL if
2489 			 * pre solaris 9 sparc sd behavior is required
2490 			 *
2491 			 * If first time through and sd_dtype_optical_bind
2492 			 * has not been set in /etc/system check properties
2493 			 */
2494 
2495 			if (sd_dtype_optical_bind  < 0) {
2496 				sd_dtype_optical_bind = ddi_prop_get_int
2497 				    (DDI_DEV_T_ANY, devi, 0,
2498 				    "optical-device-bind", 1);
2499 			}
2500 
2501 			if (sd_dtype_optical_bind == 0) {
2502 				rval = DDI_PROBE_FAILURE;
2503 			} else {
2504 				rval = DDI_PROBE_SUCCESS;
2505 			}
2506 			break;
2507 
2508 		case DTYPE_NOTPRESENT:
2509 		default:
2510 			rval = DDI_PROBE_FAILURE;
2511 			break;
2512 		}
2513 		break;
2514 	default:
2515 		rval = DDI_PROBE_PARTIAL;
2516 		break;
2517 	}
2518 
2519 	/*
2520 	 * This routine checks for resource allocation prior to freeing,
2521 	 * so it will take care of the "smart probing" case where a
2522 	 * scsi_probe() may or may not have been issued and will *not*
2523 	 * free previously-freed resources.
2524 	 */
2525 	scsi_unprobe(devp);
2526 	return (rval);
2527 }
2528 
2529 
2530 /*
2531  *    Function: sdinfo
2532  *
2533  * Description: This is the driver getinfo(9e) entry point function.
2534  * 		Given the device number, return the devinfo pointer from
2535  *		the scsi_device structure or the instance number
2536  *		associated with the dev_t.
2537  *
2538  *   Arguments: dip     - pointer to device info structure
2539  *		infocmd - command argument (DDI_INFO_DEVT2DEVINFO,
2540  *			  DDI_INFO_DEVT2INSTANCE)
2541  *		arg     - driver dev_t
2542  *		resultp - user buffer for request response
2543  *
2544  * Return Code: DDI_SUCCESS
2545  *              DDI_FAILURE
2546  */
2547 /* ARGSUSED */
2548 static int
2549 sdinfo(dev_info_t *dip, ddi_info_cmd_t infocmd, void *arg, void **result)
2550 {
2551 	struct sd_lun	*un;
2552 	dev_t		dev;
2553 	int		instance;
2554 	int		error;
2555 
2556 	switch (infocmd) {
2557 	case DDI_INFO_DEVT2DEVINFO:
2558 		dev = (dev_t)arg;
2559 		instance = SDUNIT(dev);
2560 		if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
2561 			return (DDI_FAILURE);
2562 		}
2563 		*result = (void *) SD_DEVINFO(un);
2564 		error = DDI_SUCCESS;
2565 		break;
2566 	case DDI_INFO_DEVT2INSTANCE:
2567 		dev = (dev_t)arg;
2568 		instance = SDUNIT(dev);
2569 		*result = (void *)(uintptr_t)instance;
2570 		error = DDI_SUCCESS;
2571 		break;
2572 	default:
2573 		error = DDI_FAILURE;
2574 	}
2575 	return (error);
2576 }
2577 
2578 /*
2579  *    Function: sd_prop_op
2580  *
2581  * Description: This is the driver prop_op(9e) entry point function.
2582  *		Return the number of blocks for the partition in question
2583  *		or forward the request to the property facilities.
2584  *
2585  *   Arguments: dev       - device number
2586  *		dip       - pointer to device info structure
2587  *		prop_op   - property operator
2588  *		mod_flags - DDI_PROP_DONTPASS, don't pass to parent
2589  *		name      - pointer to property name
2590  *		valuep    - pointer or address of the user buffer
2591  *		lengthp   - property length
2592  *
2593  * Return Code: DDI_PROP_SUCCESS
2594  *              DDI_PROP_NOT_FOUND
2595  *              DDI_PROP_UNDEFINED
2596  *              DDI_PROP_NO_MEMORY
2597  *              DDI_PROP_BUF_TOO_SMALL
2598  */
2599 
2600 static int
2601 sd_prop_op(dev_t dev, dev_info_t *dip, ddi_prop_op_t prop_op, int mod_flags,
2602 	char *name, caddr_t valuep, int *lengthp)
2603 {
2604 	int		instance = ddi_get_instance(dip);
2605 	struct sd_lun	*un;
2606 	uint64_t	nblocks64;
2607 	uint_t		dblk;
2608 
2609 	/*
2610 	 * Our dynamic properties are all device specific and size oriented.
2611 	 * Requests issued under conditions where size is valid are passed
2612 	 * to ddi_prop_op_nblocks with the size information, otherwise the
2613 	 * request is passed to ddi_prop_op. Size depends on valid geometry.
2614 	 */
2615 	un = ddi_get_soft_state(sd_state, instance);
2616 	if ((dev == DDI_DEV_T_ANY) || (un == NULL)) {
2617 		return (ddi_prop_op(dev, dip, prop_op, mod_flags,
2618 		    name, valuep, lengthp));
2619 	} else if (!SD_IS_VALID_LABEL(un)) {
2620 		return (ddi_prop_op(dev, dip, prop_op, mod_flags, name,
2621 		    valuep, lengthp));
2622 	}
2623 
2624 	/* get nblocks value */
2625 	ASSERT(!mutex_owned(SD_MUTEX(un)));
2626 
2627 	(void) cmlb_partinfo(un->un_cmlbhandle, SDPART(dev),
2628 	    (diskaddr_t *)&nblocks64, NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
2629 
2630 	/* report size in target size blocks */
2631 	dblk = un->un_tgt_blocksize / un->un_sys_blocksize;
2632 	return (ddi_prop_op_nblocks_blksize(dev, dip, prop_op, mod_flags,
2633 	    name, valuep, lengthp, nblocks64 / dblk, un->un_tgt_blocksize));
2634 }
2635 
2636 /*
2637  * The following functions are for smart probing:
2638  * sd_scsi_probe_cache_init()
2639  * sd_scsi_probe_cache_fini()
2640  * sd_scsi_clear_probe_cache()
2641  * sd_scsi_probe_with_cache()
2642  */
2643 
2644 /*
2645  *    Function: sd_scsi_probe_cache_init
2646  *
2647  * Description: Initializes the probe response cache mutex and head pointer.
2648  *
2649  *     Context: Kernel thread context
2650  */
2651 
2652 static void
2653 sd_scsi_probe_cache_init(void)
2654 {
2655 	mutex_init(&sd_scsi_probe_cache_mutex, NULL, MUTEX_DRIVER, NULL);
2656 	sd_scsi_probe_cache_head = NULL;
2657 }
2658 
2659 
2660 /*
2661  *    Function: sd_scsi_probe_cache_fini
2662  *
2663  * Description: Frees all resources associated with the probe response cache.
2664  *
2665  *     Context: Kernel thread context
2666  */
2667 
2668 static void
2669 sd_scsi_probe_cache_fini(void)
2670 {
2671 	struct sd_scsi_probe_cache *cp;
2672 	struct sd_scsi_probe_cache *ncp;
2673 
2674 	/* Clean up our smart probing linked list */
2675 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = ncp) {
2676 		ncp = cp->next;
2677 		kmem_free(cp, sizeof (struct sd_scsi_probe_cache));
2678 	}
2679 	sd_scsi_probe_cache_head = NULL;
2680 	mutex_destroy(&sd_scsi_probe_cache_mutex);
2681 }
2682 
2683 
2684 /*
2685  *    Function: sd_scsi_clear_probe_cache
2686  *
2687  * Description: This routine clears the probe response cache. This is
2688  *		done when open() returns ENXIO so that when deferred
2689  *		attach is attempted (possibly after a device has been
2690  *		turned on) we will retry the probe. Since we don't know
2691  *		which target we failed to open, we just clear the
2692  *		entire cache.
2693  *
2694  *     Context: Kernel thread context
2695  */
2696 
2697 static void
2698 sd_scsi_clear_probe_cache(void)
2699 {
2700 	struct sd_scsi_probe_cache	*cp;
2701 	int				i;
2702 
2703 	mutex_enter(&sd_scsi_probe_cache_mutex);
2704 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2705 		/*
2706 		 * Reset all entries to SCSIPROBE_EXISTS.  This will
2707 		 * force probing to be performed the next time
2708 		 * sd_scsi_probe_with_cache is called.
2709 		 */
2710 		for (i = 0; i < NTARGETS_WIDE; i++) {
2711 			cp->cache[i] = SCSIPROBE_EXISTS;
2712 		}
2713 	}
2714 	mutex_exit(&sd_scsi_probe_cache_mutex);
2715 }
2716 
2717 
2718 /*
2719  *    Function: sd_scsi_probe_with_cache
2720  *
2721  * Description: This routine implements support for a scsi device probe
2722  *		with cache. The driver maintains a cache of the target
2723  *		responses to scsi probes. If we get no response from a
2724  *		target during a probe inquiry, we remember that, and we
2725  *		avoid additional calls to scsi_probe on non-zero LUNs
2726  *		on the same target until the cache is cleared. By doing
2727  *		so we avoid the 1/4 sec selection timeout for nonzero
2728  *		LUNs. lun0 of a target is always probed.
2729  *
2730  *   Arguments: devp     - Pointer to a scsi_device(9S) structure
2731  *              waitfunc - indicates what the allocator routines should
2732  *			   do when resources are not available. This value
2733  *			   is passed on to scsi_probe() when that routine
2734  *			   is called.
2735  *
2736  * Return Code: SCSIPROBE_NORESP if a NORESP in probe response cache;
2737  *		otherwise the value returned by scsi_probe(9F).
2738  *
2739  *     Context: Kernel thread context
2740  */
2741 
2742 static int
2743 sd_scsi_probe_with_cache(struct scsi_device *devp, int (*waitfn)())
2744 {
2745 	struct sd_scsi_probe_cache	*cp;
2746 	dev_info_t	*pdip = ddi_get_parent(devp->sd_dev);
2747 	int		lun, tgt;
2748 
2749 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2750 	    SCSI_ADDR_PROP_LUN, 0);
2751 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devp->sd_dev, DDI_PROP_DONTPASS,
2752 	    SCSI_ADDR_PROP_TARGET, -1);
2753 
2754 	/* Make sure caching enabled and target in range */
2755 	if ((tgt < 0) || (tgt >= NTARGETS_WIDE)) {
2756 		/* do it the old way (no cache) */
2757 		return (scsi_probe(devp, waitfn));
2758 	}
2759 
2760 	mutex_enter(&sd_scsi_probe_cache_mutex);
2761 
2762 	/* Find the cache for this scsi bus instance */
2763 	for (cp = sd_scsi_probe_cache_head; cp != NULL; cp = cp->next) {
2764 		if (cp->pdip == pdip) {
2765 			break;
2766 		}
2767 	}
2768 
2769 	/* If we can't find a cache for this pdip, create one */
2770 	if (cp == NULL) {
2771 		int i;
2772 
2773 		cp = kmem_zalloc(sizeof (struct sd_scsi_probe_cache),
2774 		    KM_SLEEP);
2775 		cp->pdip = pdip;
2776 		cp->next = sd_scsi_probe_cache_head;
2777 		sd_scsi_probe_cache_head = cp;
2778 		for (i = 0; i < NTARGETS_WIDE; i++) {
2779 			cp->cache[i] = SCSIPROBE_EXISTS;
2780 		}
2781 	}
2782 
2783 	mutex_exit(&sd_scsi_probe_cache_mutex);
2784 
2785 	/* Recompute the cache for this target if LUN zero */
2786 	if (lun == 0) {
2787 		cp->cache[tgt] = SCSIPROBE_EXISTS;
2788 	}
2789 
2790 	/* Don't probe if cache remembers a NORESP from a previous LUN. */
2791 	if (cp->cache[tgt] != SCSIPROBE_EXISTS) {
2792 		return (SCSIPROBE_NORESP);
2793 	}
2794 
2795 	/* Do the actual probe; save & return the result */
2796 	return (cp->cache[tgt] = scsi_probe(devp, waitfn));
2797 }
2798 
2799 
2800 /*
2801  *    Function: sd_scsi_target_lun_init
2802  *
2803  * Description: Initializes the attached lun chain mutex and head pointer.
2804  *
2805  *     Context: Kernel thread context
2806  */
2807 
2808 static void
2809 sd_scsi_target_lun_init(void)
2810 {
2811 	mutex_init(&sd_scsi_target_lun_mutex, NULL, MUTEX_DRIVER, NULL);
2812 	sd_scsi_target_lun_head = NULL;
2813 }
2814 
2815 
2816 /*
2817  *    Function: sd_scsi_target_lun_fini
2818  *
2819  * Description: Frees all resources associated with the attached lun
2820  *              chain
2821  *
2822  *     Context: Kernel thread context
2823  */
2824 
2825 static void
2826 sd_scsi_target_lun_fini(void)
2827 {
2828 	struct sd_scsi_hba_tgt_lun	*cp;
2829 	struct sd_scsi_hba_tgt_lun	*ncp;
2830 
2831 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = ncp) {
2832 		ncp = cp->next;
2833 		kmem_free(cp, sizeof (struct sd_scsi_hba_tgt_lun));
2834 	}
2835 	sd_scsi_target_lun_head = NULL;
2836 	mutex_destroy(&sd_scsi_target_lun_mutex);
2837 }
2838 
2839 
2840 /*
2841  *    Function: sd_scsi_get_target_lun_count
2842  *
2843  * Description: This routine will check in the attached lun chain to see
2844  * 		how many luns are attached on the required SCSI controller
2845  * 		and target. Currently, some capabilities like tagged queue
2846  *		are supported per target based by HBA. So all luns in a
2847  *		target have the same capabilities. Based on this assumption,
2848  * 		sd should only set these capabilities once per target. This
2849  *		function is called when sd needs to decide how many luns
2850  *		already attached on a target.
2851  *
2852  *   Arguments: dip	- Pointer to the system's dev_info_t for the SCSI
2853  *			  controller device.
2854  *              target	- The target ID on the controller's SCSI bus.
2855  *
2856  * Return Code: The number of luns attached on the required target and
2857  *		controller.
2858  *		-1 if target ID is not in parallel SCSI scope or the given
2859  * 		dip is not in the chain.
2860  *
2861  *     Context: Kernel thread context
2862  */
2863 
2864 static int
2865 sd_scsi_get_target_lun_count(dev_info_t *dip, int target)
2866 {
2867 	struct sd_scsi_hba_tgt_lun	*cp;
2868 
2869 	if ((target < 0) || (target >= NTARGETS_WIDE)) {
2870 		return (-1);
2871 	}
2872 
2873 	mutex_enter(&sd_scsi_target_lun_mutex);
2874 
2875 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2876 		if (cp->pdip == dip) {
2877 			break;
2878 		}
2879 	}
2880 
2881 	mutex_exit(&sd_scsi_target_lun_mutex);
2882 
2883 	if (cp == NULL) {
2884 		return (-1);
2885 	}
2886 
2887 	return (cp->nlun[target]);
2888 }
2889 
2890 
2891 /*
2892  *    Function: sd_scsi_update_lun_on_target
2893  *
2894  * Description: This routine is used to update the attached lun chain when a
2895  *		lun is attached or detached on a target.
2896  *
2897  *   Arguments: dip     - Pointer to the system's dev_info_t for the SCSI
2898  *                        controller device.
2899  *              target  - The target ID on the controller's SCSI bus.
2900  *		flag	- Indicate the lun is attached or detached.
2901  *
2902  *     Context: Kernel thread context
2903  */
2904 
2905 static void
2906 sd_scsi_update_lun_on_target(dev_info_t *dip, int target, int flag)
2907 {
2908 	struct sd_scsi_hba_tgt_lun	*cp;
2909 
2910 	mutex_enter(&sd_scsi_target_lun_mutex);
2911 
2912 	for (cp = sd_scsi_target_lun_head; cp != NULL; cp = cp->next) {
2913 		if (cp->pdip == dip) {
2914 			break;
2915 		}
2916 	}
2917 
2918 	if ((cp == NULL) && (flag == SD_SCSI_LUN_ATTACH)) {
2919 		cp = kmem_zalloc(sizeof (struct sd_scsi_hba_tgt_lun),
2920 		    KM_SLEEP);
2921 		cp->pdip = dip;
2922 		cp->next = sd_scsi_target_lun_head;
2923 		sd_scsi_target_lun_head = cp;
2924 	}
2925 
2926 	mutex_exit(&sd_scsi_target_lun_mutex);
2927 
2928 	if (cp != NULL) {
2929 		if (flag == SD_SCSI_LUN_ATTACH) {
2930 			cp->nlun[target] ++;
2931 		} else {
2932 			cp->nlun[target] --;
2933 		}
2934 	}
2935 }
2936 
2937 
2938 /*
2939  *    Function: sd_spin_up_unit
2940  *
2941  * Description: Issues the following commands to spin-up the device:
2942  *		START STOP UNIT, and INQUIRY.
2943  *
2944  *   Arguments: un - driver soft state (unit) structure
2945  *
2946  * Return Code: 0 - success
2947  *		EIO - failure
2948  *		EACCES - reservation conflict
2949  *
2950  *     Context: Kernel thread context
2951  */
2952 
2953 static int
2954 sd_spin_up_unit(struct sd_lun *un)
2955 {
2956 	size_t	resid		= 0;
2957 	int	has_conflict	= FALSE;
2958 	uchar_t *bufaddr;
2959 
2960 	ASSERT(un != NULL);
2961 
2962 	/*
2963 	 * Send a throwaway START UNIT command.
2964 	 *
2965 	 * If we fail on this, we don't care presently what precisely
2966 	 * is wrong.  EMC's arrays will also fail this with a check
2967 	 * condition (0x2/0x4/0x3) if the device is "inactive," but
2968 	 * we don't want to fail the attach because it may become
2969 	 * "active" later.
2970 	 */
2971 	if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START, SD_PATH_DIRECT)
2972 	    == EACCES)
2973 		has_conflict = TRUE;
2974 
2975 	/*
2976 	 * Send another INQUIRY command to the target. This is necessary for
2977 	 * non-removable media direct access devices because their INQUIRY data
2978 	 * may not be fully qualified until they are spun up (perhaps via the
2979 	 * START command above).  Note: This seems to be needed for some
2980 	 * legacy devices only.) The INQUIRY command should succeed even if a
2981 	 * Reservation Conflict is present.
2982 	 */
2983 	bufaddr = kmem_zalloc(SUN_INQSIZE, KM_SLEEP);
2984 	if (sd_send_scsi_INQUIRY(un, bufaddr, SUN_INQSIZE, 0, 0, &resid) != 0) {
2985 		kmem_free(bufaddr, SUN_INQSIZE);
2986 		return (EIO);
2987 	}
2988 
2989 	/*
2990 	 * If we got enough INQUIRY data, copy it over the old INQUIRY data.
2991 	 * Note that this routine does not return a failure here even if the
2992 	 * INQUIRY command did not return any data.  This is a legacy behavior.
2993 	 */
2994 	if ((SUN_INQSIZE - resid) >= SUN_MIN_INQLEN) {
2995 		bcopy(bufaddr, SD_INQUIRY(un), SUN_INQSIZE);
2996 	}
2997 
2998 	kmem_free(bufaddr, SUN_INQSIZE);
2999 
3000 	/* If we hit a reservation conflict above, tell the caller. */
3001 	if (has_conflict == TRUE) {
3002 		return (EACCES);
3003 	}
3004 
3005 	return (0);
3006 }
3007 
3008 #ifdef _LP64
3009 /*
3010  *    Function: sd_enable_descr_sense
3011  *
3012  * Description: This routine attempts to select descriptor sense format
3013  *		using the Control mode page.  Devices that support 64 bit
3014  *		LBAs (for >2TB luns) should also implement descriptor
3015  *		sense data so we will call this function whenever we see
3016  *		a lun larger than 2TB.  If for some reason the device
3017  *		supports 64 bit LBAs but doesn't support descriptor sense
3018  *		presumably the mode select will fail.  Everything will
3019  *		continue to work normally except that we will not get
3020  *		complete sense data for commands that fail with an LBA
3021  *		larger than 32 bits.
3022  *
3023  *   Arguments: un - driver soft state (unit) structure
3024  *
3025  *     Context: Kernel thread context only
3026  */
3027 
3028 static void
3029 sd_enable_descr_sense(struct sd_lun *un)
3030 {
3031 	uchar_t			*header;
3032 	struct mode_control_scsi3 *ctrl_bufp;
3033 	size_t			buflen;
3034 	size_t			bd_len;
3035 
3036 	/*
3037 	 * Read MODE SENSE page 0xA, Control Mode Page
3038 	 */
3039 	buflen = MODE_HEADER_LENGTH + MODE_BLK_DESC_LENGTH +
3040 	    sizeof (struct mode_control_scsi3);
3041 	header = kmem_zalloc(buflen, KM_SLEEP);
3042 	if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
3043 	    MODEPAGE_CTRL_MODE, SD_PATH_DIRECT) != 0) {
3044 		SD_ERROR(SD_LOG_COMMON, un,
3045 		    "sd_enable_descr_sense: mode sense ctrl page failed\n");
3046 		goto eds_exit;
3047 	}
3048 
3049 	/*
3050 	 * Determine size of Block Descriptors in order to locate
3051 	 * the mode page data. ATAPI devices return 0, SCSI devices
3052 	 * should return MODE_BLK_DESC_LENGTH.
3053 	 */
3054 	bd_len  = ((struct mode_header *)header)->bdesc_length;
3055 
3056 	/* Clear the mode data length field for MODE SELECT */
3057 	((struct mode_header *)header)->length = 0;
3058 
3059 	ctrl_bufp = (struct mode_control_scsi3 *)
3060 	    (header + MODE_HEADER_LENGTH + bd_len);
3061 
3062 	/*
3063 	 * If the page length is smaller than the expected value,
3064 	 * the target device doesn't support D_SENSE. Bail out here.
3065 	 */
3066 	if (ctrl_bufp->mode_page.length <
3067 	    sizeof (struct mode_control_scsi3) - 2) {
3068 		SD_ERROR(SD_LOG_COMMON, un,
3069 		    "sd_enable_descr_sense: enable D_SENSE failed\n");
3070 		goto eds_exit;
3071 	}
3072 
3073 	/*
3074 	 * Clear PS bit for MODE SELECT
3075 	 */
3076 	ctrl_bufp->mode_page.ps = 0;
3077 
3078 	/*
3079 	 * Set D_SENSE to enable descriptor sense format.
3080 	 */
3081 	ctrl_bufp->d_sense = 1;
3082 
3083 	/*
3084 	 * Use MODE SELECT to commit the change to the D_SENSE bit
3085 	 */
3086 	if (sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
3087 	    buflen, SD_DONTSAVE_PAGE, SD_PATH_DIRECT) != 0) {
3088 		SD_INFO(SD_LOG_COMMON, un,
3089 		    "sd_enable_descr_sense: mode select ctrl page failed\n");
3090 		goto eds_exit;
3091 	}
3092 
3093 eds_exit:
3094 	kmem_free(header, buflen);
3095 }
3096 
3097 /*
3098  *    Function: sd_reenable_dsense_task
3099  *
3100  * Description: Re-enable descriptor sense after device or bus reset
3101  *
3102  *     Context: Executes in a taskq() thread context
3103  */
3104 static void
3105 sd_reenable_dsense_task(void *arg)
3106 {
3107 	struct	sd_lun	*un = arg;
3108 
3109 	ASSERT(un != NULL);
3110 	sd_enable_descr_sense(un);
3111 }
3112 #endif /* _LP64 */
3113 
3114 /*
3115  *    Function: sd_set_mmc_caps
3116  *
3117  * Description: This routine determines if the device is MMC compliant and if
3118  *		the device supports CDDA via a mode sense of the CDVD
3119  *		capabilities mode page. Also checks if the device is a
3120  *		dvdram writable device.
3121  *
3122  *   Arguments: un - driver soft state (unit) structure
3123  *
3124  *     Context: Kernel thread context only
3125  */
3126 
3127 static void
3128 sd_set_mmc_caps(struct sd_lun *un)
3129 {
3130 	struct mode_header_grp2		*sense_mhp;
3131 	uchar_t				*sense_page;
3132 	caddr_t				buf;
3133 	int				bd_len;
3134 	int				status;
3135 	struct uscsi_cmd		com;
3136 	int				rtn;
3137 	uchar_t				*out_data_rw, *out_data_hd;
3138 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3139 
3140 	ASSERT(un != NULL);
3141 
3142 	/*
3143 	 * The flags which will be set in this function are - mmc compliant,
3144 	 * dvdram writable device, cdda support. Initialize them to FALSE
3145 	 * and if a capability is detected - it will be set to TRUE.
3146 	 */
3147 	un->un_f_mmc_cap = FALSE;
3148 	un->un_f_dvdram_writable_device = FALSE;
3149 	un->un_f_cfg_cdda = FALSE;
3150 
3151 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3152 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
3153 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, SD_PATH_DIRECT);
3154 
3155 	if (status != 0) {
3156 		/* command failed; just return */
3157 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3158 		return;
3159 	}
3160 	/*
3161 	 * If the mode sense request for the CDROM CAPABILITIES
3162 	 * page (0x2A) succeeds the device is assumed to be MMC.
3163 	 */
3164 	un->un_f_mmc_cap = TRUE;
3165 
3166 	/* Get to the page data */
3167 	sense_mhp = (struct mode_header_grp2 *)buf;
3168 	bd_len = (sense_mhp->bdesc_length_hi << 8) |
3169 	    sense_mhp->bdesc_length_lo;
3170 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3171 		/*
3172 		 * We did not get back the expected block descriptor
3173 		 * length so we cannot determine if the device supports
3174 		 * CDDA. However, we still indicate the device is MMC
3175 		 * according to the successful response to the page
3176 		 * 0x2A mode sense request.
3177 		 */
3178 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3179 		    "sd_set_mmc_caps: Mode Sense returned "
3180 		    "invalid block descriptor length\n");
3181 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3182 		return;
3183 	}
3184 
3185 	/* See if read CDDA is supported */
3186 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 +
3187 	    bd_len);
3188 	un->un_f_cfg_cdda = (sense_page[5] & 0x01) ? TRUE : FALSE;
3189 
3190 	/* See if writing DVD RAM is supported. */
3191 	un->un_f_dvdram_writable_device = (sense_page[3] & 0x20) ? TRUE : FALSE;
3192 	if (un->un_f_dvdram_writable_device == TRUE) {
3193 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3194 		return;
3195 	}
3196 
3197 	/*
3198 	 * If the device presents DVD or CD capabilities in the mode
3199 	 * page, we can return here since a RRD will not have
3200 	 * these capabilities.
3201 	 */
3202 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3203 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3204 		return;
3205 	}
3206 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3207 
3208 	/*
3209 	 * If un->un_f_dvdram_writable_device is still FALSE,
3210 	 * check for a Removable Rigid Disk (RRD).  A RRD
3211 	 * device is identified by the features RANDOM_WRITABLE and
3212 	 * HARDWARE_DEFECT_MANAGEMENT.
3213 	 */
3214 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3215 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3216 
3217 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3218 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3219 	    RANDOM_WRITABLE, SD_PATH_STANDARD);
3220 	if (rtn != 0) {
3221 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3222 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3223 		return;
3224 	}
3225 
3226 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3227 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3228 
3229 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3230 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3231 	    HARDWARE_DEFECT_MANAGEMENT, SD_PATH_STANDARD);
3232 	if (rtn == 0) {
3233 		/*
3234 		 * We have good information, check for random writable
3235 		 * and hardware defect features.
3236 		 */
3237 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3238 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT)) {
3239 			un->un_f_dvdram_writable_device = TRUE;
3240 		}
3241 	}
3242 
3243 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3244 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3245 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3246 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3247 }
3248 
3249 /*
3250  *    Function: sd_check_for_writable_cd
3251  *
3252  * Description: This routine determines if the media in the device is
3253  *		writable or not. It uses the get configuration command (0x46)
3254  *		to determine if the media is writable
3255  *
3256  *   Arguments: un - driver soft state (unit) structure
3257  *              path_flag - SD_PATH_DIRECT to use the USCSI "direct"
3258  *                           chain and the normal command waitq, or
3259  *                           SD_PATH_DIRECT_PRIORITY to use the USCSI
3260  *                           "direct" chain and bypass the normal command
3261  *                           waitq.
3262  *
3263  *     Context: Never called at interrupt context.
3264  */
3265 
3266 static void
3267 sd_check_for_writable_cd(struct sd_lun *un, int path_flag)
3268 {
3269 	struct uscsi_cmd		com;
3270 	uchar_t				*out_data;
3271 	uchar_t				*rqbuf;
3272 	int				rtn;
3273 	uchar_t				*out_data_rw, *out_data_hd;
3274 	uchar_t				*rqbuf_rw, *rqbuf_hd;
3275 	struct mode_header_grp2		*sense_mhp;
3276 	uchar_t				*sense_page;
3277 	caddr_t				buf;
3278 	int				bd_len;
3279 	int				status;
3280 
3281 	ASSERT(un != NULL);
3282 	ASSERT(mutex_owned(SD_MUTEX(un)));
3283 
3284 	/*
3285 	 * Initialize the writable media to false, if configuration info.
3286 	 * tells us otherwise then only we will set it.
3287 	 */
3288 	un->un_f_mmc_writable_media = FALSE;
3289 	mutex_exit(SD_MUTEX(un));
3290 
3291 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
3292 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3293 
3294 	rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf, SENSE_LENGTH,
3295 	    out_data, SD_PROFILE_HEADER_LEN, path_flag);
3296 
3297 	mutex_enter(SD_MUTEX(un));
3298 	if (rtn == 0) {
3299 		/*
3300 		 * We have good information, check for writable DVD.
3301 		 */
3302 		if ((out_data[6] == 0) && (out_data[7] == 0x12)) {
3303 			un->un_f_mmc_writable_media = TRUE;
3304 			kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3305 			kmem_free(rqbuf, SENSE_LENGTH);
3306 			return;
3307 		}
3308 	}
3309 
3310 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
3311 	kmem_free(rqbuf, SENSE_LENGTH);
3312 
3313 	/*
3314 	 * Determine if this is a RRD type device.
3315 	 */
3316 	mutex_exit(SD_MUTEX(un));
3317 	buf = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
3318 	status = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, (uchar_t *)buf,
3319 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP, path_flag);
3320 	mutex_enter(SD_MUTEX(un));
3321 	if (status != 0) {
3322 		/* command failed; just return */
3323 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3324 		return;
3325 	}
3326 
3327 	/* Get to the page data */
3328 	sense_mhp = (struct mode_header_grp2 *)buf;
3329 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
3330 	if (bd_len > MODE_BLK_DESC_LENGTH) {
3331 		/*
3332 		 * We did not get back the expected block descriptor length so
3333 		 * we cannot check the mode page.
3334 		 */
3335 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3336 		    "sd_check_for_writable_cd: Mode Sense returned "
3337 		    "invalid block descriptor length\n");
3338 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3339 		return;
3340 	}
3341 
3342 	/*
3343 	 * If the device presents DVD or CD capabilities in the mode
3344 	 * page, we can return here since a RRD device will not have
3345 	 * these capabilities.
3346 	 */
3347 	sense_page = (uchar_t *)(buf + MODE_HEADER_LENGTH_GRP2 + bd_len);
3348 	if ((sense_page[2] & 0x3f) || (sense_page[3] & 0x3f)) {
3349 		kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3350 		return;
3351 	}
3352 	kmem_free(buf, BUFLEN_MODE_CDROM_CAP);
3353 
3354 	/*
3355 	 * If un->un_f_mmc_writable_media is still FALSE,
3356 	 * check for RRD type media.  A RRD device is identified
3357 	 * by the features RANDOM_WRITABLE and HARDWARE_DEFECT_MANAGEMENT.
3358 	 */
3359 	mutex_exit(SD_MUTEX(un));
3360 	out_data_rw = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3361 	rqbuf_rw = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3362 
3363 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_rw,
3364 	    SENSE_LENGTH, out_data_rw, SD_CURRENT_FEATURE_LEN,
3365 	    RANDOM_WRITABLE, path_flag);
3366 	if (rtn != 0) {
3367 		kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3368 		kmem_free(rqbuf_rw, SENSE_LENGTH);
3369 		mutex_enter(SD_MUTEX(un));
3370 		return;
3371 	}
3372 
3373 	out_data_hd = kmem_zalloc(SD_CURRENT_FEATURE_LEN, KM_SLEEP);
3374 	rqbuf_hd = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
3375 
3376 	rtn = sd_send_scsi_feature_GET_CONFIGURATION(un, &com, rqbuf_hd,
3377 	    SENSE_LENGTH, out_data_hd, SD_CURRENT_FEATURE_LEN,
3378 	    HARDWARE_DEFECT_MANAGEMENT, path_flag);
3379 	mutex_enter(SD_MUTEX(un));
3380 	if (rtn == 0) {
3381 		/*
3382 		 * We have good information, check for random writable
3383 		 * and hardware defect features as current.
3384 		 */
3385 		if ((out_data_rw[9] & RANDOM_WRITABLE) &&
3386 		    (out_data_rw[10] & 0x1) &&
3387 		    (out_data_hd[9] & HARDWARE_DEFECT_MANAGEMENT) &&
3388 		    (out_data_hd[10] & 0x1)) {
3389 			un->un_f_mmc_writable_media = TRUE;
3390 		}
3391 	}
3392 
3393 	kmem_free(out_data_rw, SD_CURRENT_FEATURE_LEN);
3394 	kmem_free(rqbuf_rw, SENSE_LENGTH);
3395 	kmem_free(out_data_hd, SD_CURRENT_FEATURE_LEN);
3396 	kmem_free(rqbuf_hd, SENSE_LENGTH);
3397 }
3398 
3399 /*
3400  *    Function: sd_read_unit_properties
3401  *
3402  * Description: The following implements a property lookup mechanism.
3403  *		Properties for particular disks (keyed on vendor, model
3404  *		and rev numbers) are sought in the sd.conf file via
3405  *		sd_process_sdconf_file(), and if not found there, are
3406  *		looked for in a list hardcoded in this driver via
3407  *		sd_process_sdconf_table() Once located the properties
3408  *		are used to update the driver unit structure.
3409  *
3410  *   Arguments: un - driver soft state (unit) structure
3411  */
3412 
3413 static void
3414 sd_read_unit_properties(struct sd_lun *un)
3415 {
3416 	/*
3417 	 * sd_process_sdconf_file returns SD_FAILURE if it cannot find
3418 	 * the "sd-config-list" property (from the sd.conf file) or if
3419 	 * there was not a match for the inquiry vid/pid. If this event
3420 	 * occurs the static driver configuration table is searched for
3421 	 * a match.
3422 	 */
3423 	ASSERT(un != NULL);
3424 	if (sd_process_sdconf_file(un) == SD_FAILURE) {
3425 		sd_process_sdconf_table(un);
3426 	}
3427 
3428 	/* check for LSI device */
3429 	sd_is_lsi(un);
3430 
3431 
3432 }
3433 
3434 
3435 /*
3436  *    Function: sd_process_sdconf_file
3437  *
3438  * Description: Use ddi_getlongprop to obtain the properties from the
3439  *		driver's config file (ie, sd.conf) and update the driver
3440  *		soft state structure accordingly.
3441  *
3442  *   Arguments: un - driver soft state (unit) structure
3443  *
3444  * Return Code: SD_SUCCESS - The properties were successfully set according
3445  *			     to the driver configuration file.
3446  *		SD_FAILURE - The driver config list was not obtained or
3447  *			     there was no vid/pid match. This indicates that
3448  *			     the static config table should be used.
3449  *
3450  * The config file has a property, "sd-config-list", which consists of
3451  * one or more duplets as follows:
3452  *
3453  *  sd-config-list=
3454  *	<duplet>,
3455  *	[<duplet>,]
3456  *	[<duplet>];
3457  *
3458  * The structure of each duplet is as follows:
3459  *
3460  *  <duplet>:= <vid+pid>,<data-property-name_list>
3461  *
3462  * The first entry of the duplet is the device ID string (the concatenated
3463  * vid & pid; not to be confused with a device_id).  This is defined in
3464  * the same way as in the sd_disk_table.
3465  *
3466  * The second part of the duplet is a string that identifies a
3467  * data-property-name-list. The data-property-name-list is defined as
3468  * follows:
3469  *
3470  *  <data-property-name-list>:=<data-property-name> [<data-property-name>]
3471  *
3472  * The syntax of <data-property-name> depends on the <version> field.
3473  *
3474  * If version = SD_CONF_VERSION_1 we have the following syntax:
3475  *
3476  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3477  *
3478  * where the prop0 value will be used to set prop0 if bit0 set in the
3479  * flags, prop1 if bit1 set, etc. and N = SD_CONF_MAX_ITEMS -1
3480  *
3481  */
3482 
3483 static int
3484 sd_process_sdconf_file(struct sd_lun *un)
3485 {
3486 	char	*config_list = NULL;
3487 	int	config_list_len;
3488 	int	len;
3489 	int	dupletlen = 0;
3490 	char	*vidptr;
3491 	int	vidlen;
3492 	char	*dnlist_ptr;
3493 	char	*dataname_ptr;
3494 	int	dnlist_len;
3495 	int	dataname_len;
3496 	int	*data_list;
3497 	int	data_list_len;
3498 	int	rval = SD_FAILURE;
3499 	int	i;
3500 
3501 	ASSERT(un != NULL);
3502 
3503 	/* Obtain the configuration list associated with the .conf file */
3504 	if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), DDI_PROP_DONTPASS,
3505 	    sd_config_list, (caddr_t)&config_list, &config_list_len)
3506 	    != DDI_PROP_SUCCESS) {
3507 		return (SD_FAILURE);
3508 	}
3509 
3510 	/*
3511 	 * Compare vids in each duplet to the inquiry vid - if a match is
3512 	 * made, get the data value and update the soft state structure
3513 	 * accordingly.
3514 	 *
3515 	 * Note: This algorithm is complex and difficult to maintain. It should
3516 	 * be replaced with a more robust implementation.
3517 	 */
3518 	for (len = config_list_len, vidptr = config_list; len > 0;
3519 	    vidptr += dupletlen, len -= dupletlen) {
3520 		/*
3521 		 * Note: The assumption here is that each vid entry is on
3522 		 * a unique line from its associated duplet.
3523 		 */
3524 		vidlen = dupletlen = (int)strlen(vidptr);
3525 		if ((vidlen == 0) ||
3526 		    (sd_sdconf_id_match(un, vidptr, vidlen) != SD_SUCCESS)) {
3527 			dupletlen++;
3528 			continue;
3529 		}
3530 
3531 		/*
3532 		 * dnlist contains 1 or more blank separated
3533 		 * data-property-name entries
3534 		 */
3535 		dnlist_ptr = vidptr + vidlen + 1;
3536 		dnlist_len = (int)strlen(dnlist_ptr);
3537 		dupletlen += dnlist_len + 2;
3538 
3539 		/*
3540 		 * Set a pointer for the first data-property-name
3541 		 * entry in the list
3542 		 */
3543 		dataname_ptr = dnlist_ptr;
3544 		dataname_len = 0;
3545 
3546 		/*
3547 		 * Loop through all data-property-name entries in the
3548 		 * data-property-name-list setting the properties for each.
3549 		 */
3550 		while (dataname_len < dnlist_len) {
3551 			int version;
3552 
3553 			/*
3554 			 * Determine the length of the current
3555 			 * data-property-name entry by indexing until a
3556 			 * blank or NULL is encountered. When the space is
3557 			 * encountered reset it to a NULL for compliance
3558 			 * with ddi_getlongprop().
3559 			 */
3560 			for (i = 0; ((dataname_ptr[i] != ' ') &&
3561 			    (dataname_ptr[i] != '\0')); i++) {
3562 				;
3563 			}
3564 
3565 			dataname_len += i;
3566 			/* If not null terminated, Make it so */
3567 			if (dataname_ptr[i] == ' ') {
3568 				dataname_ptr[i] = '\0';
3569 			}
3570 			dataname_len++;
3571 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3572 			    "sd_process_sdconf_file: disk:%s, data:%s\n",
3573 			    vidptr, dataname_ptr);
3574 
3575 			/* Get the data list */
3576 			if (ddi_getlongprop(DDI_DEV_T_ANY, SD_DEVINFO(un), 0,
3577 			    dataname_ptr, (caddr_t)&data_list, &data_list_len)
3578 			    != DDI_PROP_SUCCESS) {
3579 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
3580 				    "sd_process_sdconf_file: data property (%s)"
3581 				    " has no value\n", dataname_ptr);
3582 				dataname_ptr = dnlist_ptr + dataname_len;
3583 				continue;
3584 			}
3585 
3586 			version = data_list[0];
3587 
3588 			if (version == SD_CONF_VERSION_1) {
3589 				sd_tunables values;
3590 
3591 				/* Set the properties */
3592 				if (sd_chk_vers1_data(un, data_list[1],
3593 				    &data_list[2], data_list_len, dataname_ptr)
3594 				    == SD_SUCCESS) {
3595 					sd_get_tunables_from_conf(un,
3596 					    data_list[1], &data_list[2],
3597 					    &values);
3598 					sd_set_vers1_properties(un,
3599 					    data_list[1], &values);
3600 					rval = SD_SUCCESS;
3601 				} else {
3602 					rval = SD_FAILURE;
3603 				}
3604 			} else {
3605 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3606 				    "data property %s version 0x%x is invalid.",
3607 				    dataname_ptr, version);
3608 				rval = SD_FAILURE;
3609 			}
3610 			kmem_free(data_list, data_list_len);
3611 			dataname_ptr = dnlist_ptr + dataname_len;
3612 		}
3613 	}
3614 
3615 	/* free up the memory allocated by ddi_getlongprop */
3616 	if (config_list) {
3617 		kmem_free(config_list, config_list_len);
3618 	}
3619 
3620 	return (rval);
3621 }
3622 
3623 /*
3624  *    Function: sd_get_tunables_from_conf()
3625  *
3626  *
3627  *    This function reads the data list from the sd.conf file and pulls
3628  *    the values that can have numeric values as arguments and places
3629  *    the values in the appropriate sd_tunables member.
3630  *    Since the order of the data list members varies across platforms
3631  *    This function reads them from the data list in a platform specific
3632  *    order and places them into the correct sd_tunable member that is
3633  *    consistent across all platforms.
3634  */
3635 static void
3636 sd_get_tunables_from_conf(struct sd_lun *un, int flags, int *data_list,
3637     sd_tunables *values)
3638 {
3639 	int i;
3640 	int mask;
3641 
3642 	bzero(values, sizeof (sd_tunables));
3643 
3644 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3645 
3646 		mask = 1 << i;
3647 		if (mask > flags) {
3648 			break;
3649 		}
3650 
3651 		switch (mask & flags) {
3652 		case 0:	/* This mask bit not set in flags */
3653 			continue;
3654 		case SD_CONF_BSET_THROTTLE:
3655 			values->sdt_throttle = data_list[i];
3656 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3657 			    "sd_get_tunables_from_conf: throttle = %d\n",
3658 			    values->sdt_throttle);
3659 			break;
3660 		case SD_CONF_BSET_CTYPE:
3661 			values->sdt_ctype = data_list[i];
3662 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3663 			    "sd_get_tunables_from_conf: ctype = %d\n",
3664 			    values->sdt_ctype);
3665 			break;
3666 		case SD_CONF_BSET_NRR_COUNT:
3667 			values->sdt_not_rdy_retries = data_list[i];
3668 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3669 			    "sd_get_tunables_from_conf: not_rdy_retries = %d\n",
3670 			    values->sdt_not_rdy_retries);
3671 			break;
3672 		case SD_CONF_BSET_BSY_RETRY_COUNT:
3673 			values->sdt_busy_retries = data_list[i];
3674 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3675 			    "sd_get_tunables_from_conf: busy_retries = %d\n",
3676 			    values->sdt_busy_retries);
3677 			break;
3678 		case SD_CONF_BSET_RST_RETRIES:
3679 			values->sdt_reset_retries = data_list[i];
3680 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3681 			    "sd_get_tunables_from_conf: reset_retries = %d\n",
3682 			    values->sdt_reset_retries);
3683 			break;
3684 		case SD_CONF_BSET_RSV_REL_TIME:
3685 			values->sdt_reserv_rel_time = data_list[i];
3686 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3687 			    "sd_get_tunables_from_conf: reserv_rel_time = %d\n",
3688 			    values->sdt_reserv_rel_time);
3689 			break;
3690 		case SD_CONF_BSET_MIN_THROTTLE:
3691 			values->sdt_min_throttle = data_list[i];
3692 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3693 			    "sd_get_tunables_from_conf: min_throttle = %d\n",
3694 			    values->sdt_min_throttle);
3695 			break;
3696 		case SD_CONF_BSET_DISKSORT_DISABLED:
3697 			values->sdt_disk_sort_dis = data_list[i];
3698 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3699 			    "sd_get_tunables_from_conf: disk_sort_dis = %d\n",
3700 			    values->sdt_disk_sort_dis);
3701 			break;
3702 		case SD_CONF_BSET_LUN_RESET_ENABLED:
3703 			values->sdt_lun_reset_enable = data_list[i];
3704 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3705 			    "sd_get_tunables_from_conf: lun_reset_enable = %d"
3706 			    "\n", values->sdt_lun_reset_enable);
3707 			break;
3708 		case SD_CONF_BSET_CACHE_IS_NV:
3709 			values->sdt_suppress_cache_flush = data_list[i];
3710 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3711 			    "sd_get_tunables_from_conf: \
3712 			    suppress_cache_flush = %d"
3713 			    "\n", values->sdt_suppress_cache_flush);
3714 			break;
3715 		}
3716 	}
3717 }
3718 
3719 /*
3720  *    Function: sd_process_sdconf_table
3721  *
3722  * Description: Search the static configuration table for a match on the
3723  *		inquiry vid/pid and update the driver soft state structure
3724  *		according to the table property values for the device.
3725  *
3726  *		The form of a configuration table entry is:
3727  *		  <vid+pid>,<flags>,<property-data>
3728  *		  "SEAGATE ST42400N",1,0x40000,
3729  *		  0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1;
3730  *
3731  *   Arguments: un - driver soft state (unit) structure
3732  */
3733 
3734 static void
3735 sd_process_sdconf_table(struct sd_lun *un)
3736 {
3737 	char	*id = NULL;
3738 	int	table_index;
3739 	int	idlen;
3740 
3741 	ASSERT(un != NULL);
3742 	for (table_index = 0; table_index < sd_disk_table_size;
3743 	    table_index++) {
3744 		id = sd_disk_table[table_index].device_id;
3745 		idlen = strlen(id);
3746 		if (idlen == 0) {
3747 			continue;
3748 		}
3749 
3750 		/*
3751 		 * The static configuration table currently does not
3752 		 * implement version 10 properties. Additionally,
3753 		 * multiple data-property-name entries are not
3754 		 * implemented in the static configuration table.
3755 		 */
3756 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
3757 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
3758 			    "sd_process_sdconf_table: disk %s\n", id);
3759 			sd_set_vers1_properties(un,
3760 			    sd_disk_table[table_index].flags,
3761 			    sd_disk_table[table_index].properties);
3762 			break;
3763 		}
3764 	}
3765 }
3766 
3767 
3768 /*
3769  *    Function: sd_sdconf_id_match
3770  *
3771  * Description: This local function implements a case sensitive vid/pid
3772  *		comparison as well as the boundary cases of wild card and
3773  *		multiple blanks.
3774  *
3775  *		Note: An implicit assumption made here is that the scsi
3776  *		inquiry structure will always keep the vid, pid and
3777  *		revision strings in consecutive sequence, so they can be
3778  *		read as a single string. If this assumption is not the
3779  *		case, a separate string, to be used for the check, needs
3780  *		to be built with these strings concatenated.
3781  *
3782  *   Arguments: un - driver soft state (unit) structure
3783  *		id - table or config file vid/pid
3784  *		idlen  - length of the vid/pid (bytes)
3785  *
3786  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3787  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3788  */
3789 
3790 static int
3791 sd_sdconf_id_match(struct sd_lun *un, char *id, int idlen)
3792 {
3793 	struct scsi_inquiry	*sd_inq;
3794 	int 			rval = SD_SUCCESS;
3795 
3796 	ASSERT(un != NULL);
3797 	sd_inq = un->un_sd->sd_inq;
3798 	ASSERT(id != NULL);
3799 
3800 	/*
3801 	 * We use the inq_vid as a pointer to a buffer containing the
3802 	 * vid and pid and use the entire vid/pid length of the table
3803 	 * entry for the comparison. This works because the inq_pid
3804 	 * data member follows inq_vid in the scsi_inquiry structure.
3805 	 */
3806 	if (strncasecmp(sd_inq->inq_vid, id, idlen) != 0) {
3807 		/*
3808 		 * The user id string is compared to the inquiry vid/pid
3809 		 * using a case insensitive comparison and ignoring
3810 		 * multiple spaces.
3811 		 */
3812 		rval = sd_blank_cmp(un, id, idlen);
3813 		if (rval != SD_SUCCESS) {
3814 			/*
3815 			 * User id strings that start and end with a "*"
3816 			 * are a special case. These do not have a
3817 			 * specific vendor, and the product string can
3818 			 * appear anywhere in the 16 byte PID portion of
3819 			 * the inquiry data. This is a simple strstr()
3820 			 * type search for the user id in the inquiry data.
3821 			 */
3822 			if ((id[0] == '*') && (id[idlen - 1] == '*')) {
3823 				char	*pidptr = &id[1];
3824 				int	i;
3825 				int	j;
3826 				int	pidstrlen = idlen - 2;
3827 				j = sizeof (SD_INQUIRY(un)->inq_pid) -
3828 				    pidstrlen;
3829 
3830 				if (j < 0) {
3831 					return (SD_FAILURE);
3832 				}
3833 				for (i = 0; i < j; i++) {
3834 					if (bcmp(&SD_INQUIRY(un)->inq_pid[i],
3835 					    pidptr, pidstrlen) == 0) {
3836 						rval = SD_SUCCESS;
3837 						break;
3838 					}
3839 				}
3840 			}
3841 		}
3842 	}
3843 	return (rval);
3844 }
3845 
3846 
3847 /*
3848  *    Function: sd_blank_cmp
3849  *
3850  * Description: If the id string starts and ends with a space, treat
3851  *		multiple consecutive spaces as equivalent to a single
3852  *		space. For example, this causes a sd_disk_table entry
3853  *		of " NEC CDROM " to match a device's id string of
3854  *		"NEC       CDROM".
3855  *
3856  *		Note: The success exit condition for this routine is if
3857  *		the pointer to the table entry is '\0' and the cnt of
3858  *		the inquiry length is zero. This will happen if the inquiry
3859  *		string returned by the device is padded with spaces to be
3860  *		exactly 24 bytes in length (8 byte vid + 16 byte pid). The
3861  *		SCSI spec states that the inquiry string is to be padded with
3862  *		spaces.
3863  *
3864  *   Arguments: un - driver soft state (unit) structure
3865  *		id - table or config file vid/pid
3866  *		idlen  - length of the vid/pid (bytes)
3867  *
3868  * Return Code: SD_SUCCESS - Indicates a match with the inquiry vid/pid
3869  *		SD_FAILURE - Indicates no match with the inquiry vid/pid
3870  */
3871 
3872 static int
3873 sd_blank_cmp(struct sd_lun *un, char *id, int idlen)
3874 {
3875 	char		*p1;
3876 	char		*p2;
3877 	int		cnt;
3878 	cnt = sizeof (SD_INQUIRY(un)->inq_vid) +
3879 	    sizeof (SD_INQUIRY(un)->inq_pid);
3880 
3881 	ASSERT(un != NULL);
3882 	p2 = un->un_sd->sd_inq->inq_vid;
3883 	ASSERT(id != NULL);
3884 	p1 = id;
3885 
3886 	if ((id[0] == ' ') && (id[idlen - 1] == ' ')) {
3887 		/*
3888 		 * Note: string p1 is terminated by a NUL but string p2
3889 		 * isn't.  The end of p2 is determined by cnt.
3890 		 */
3891 		for (;;) {
3892 			/* skip over any extra blanks in both strings */
3893 			while ((*p1 != '\0') && (*p1 == ' ')) {
3894 				p1++;
3895 			}
3896 			while ((cnt != 0) && (*p2 == ' ')) {
3897 				p2++;
3898 				cnt--;
3899 			}
3900 
3901 			/* compare the two strings */
3902 			if ((cnt == 0) ||
3903 			    (SD_TOUPPER(*p1) != SD_TOUPPER(*p2))) {
3904 				break;
3905 			}
3906 			while ((cnt > 0) &&
3907 			    (SD_TOUPPER(*p1) == SD_TOUPPER(*p2))) {
3908 				p1++;
3909 				p2++;
3910 				cnt--;
3911 			}
3912 		}
3913 	}
3914 
3915 	/* return SD_SUCCESS if both strings match */
3916 	return (((*p1 == '\0') && (cnt == 0)) ? SD_SUCCESS : SD_FAILURE);
3917 }
3918 
3919 
3920 /*
3921  *    Function: sd_chk_vers1_data
3922  *
3923  * Description: Verify the version 1 device properties provided by the
3924  *		user via the configuration file
3925  *
3926  *   Arguments: un	     - driver soft state (unit) structure
3927  *		flags	     - integer mask indicating properties to be set
3928  *		prop_list    - integer list of property values
3929  *		list_len     - length of user provided data
3930  *
3931  * Return Code: SD_SUCCESS - Indicates the user provided data is valid
3932  *		SD_FAILURE - Indicates the user provided data is invalid
3933  */
3934 
3935 static int
3936 sd_chk_vers1_data(struct sd_lun *un, int flags, int *prop_list,
3937     int list_len, char *dataname_ptr)
3938 {
3939 	int i;
3940 	int mask = 1;
3941 	int index = 0;
3942 
3943 	ASSERT(un != NULL);
3944 
3945 	/* Check for a NULL property name and list */
3946 	if (dataname_ptr == NULL) {
3947 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3948 		    "sd_chk_vers1_data: NULL data property name.");
3949 		return (SD_FAILURE);
3950 	}
3951 	if (prop_list == NULL) {
3952 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3953 		    "sd_chk_vers1_data: %s NULL data property list.",
3954 		    dataname_ptr);
3955 		return (SD_FAILURE);
3956 	}
3957 
3958 	/* Display a warning if undefined bits are set in the flags */
3959 	if (flags & ~SD_CONF_BIT_MASK) {
3960 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3961 		    "sd_chk_vers1_data: invalid bits 0x%x in data list %s. "
3962 		    "Properties not set.",
3963 		    (flags & ~SD_CONF_BIT_MASK), dataname_ptr);
3964 		return (SD_FAILURE);
3965 	}
3966 
3967 	/*
3968 	 * Verify the length of the list by identifying the highest bit set
3969 	 * in the flags and validating that the property list has a length
3970 	 * up to the index of this bit.
3971 	 */
3972 	for (i = 0; i < SD_CONF_MAX_ITEMS; i++) {
3973 		if (flags & mask) {
3974 			index++;
3975 		}
3976 		mask = 1 << i;
3977 	}
3978 	if ((list_len / sizeof (int)) < (index + 2)) {
3979 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
3980 		    "sd_chk_vers1_data: "
3981 		    "Data property list %s size is incorrect. "
3982 		    "Properties not set.", dataname_ptr);
3983 		scsi_log(SD_DEVINFO(un), sd_label, CE_CONT, "Size expected: "
3984 		    "version + 1 flagword + %d properties", SD_CONF_MAX_ITEMS);
3985 		return (SD_FAILURE);
3986 	}
3987 	return (SD_SUCCESS);
3988 }
3989 
3990 
3991 /*
3992  *    Function: sd_set_vers1_properties
3993  *
3994  * Description: Set version 1 device properties based on a property list
3995  *		retrieved from the driver configuration file or static
3996  *		configuration table. Version 1 properties have the format:
3997  *
3998  * 	<data-property-name>:=<version>,<flags>,<prop0>,<prop1>,.....<propN>
3999  *
4000  *		where the prop0 value will be used to set prop0 if bit0
4001  *		is set in the flags
4002  *
4003  *   Arguments: un	     - driver soft state (unit) structure
4004  *		flags	     - integer mask indicating properties to be set
4005  *		prop_list    - integer list of property values
4006  */
4007 
4008 static void
4009 sd_set_vers1_properties(struct sd_lun *un, int flags, sd_tunables *prop_list)
4010 {
4011 	ASSERT(un != NULL);
4012 
4013 	/*
4014 	 * Set the flag to indicate cache is to be disabled. An attempt
4015 	 * to disable the cache via sd_cache_control() will be made
4016 	 * later during attach once the basic initialization is complete.
4017 	 */
4018 	if (flags & SD_CONF_BSET_NOCACHE) {
4019 		un->un_f_opt_disable_cache = TRUE;
4020 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4021 		    "sd_set_vers1_properties: caching disabled flag set\n");
4022 	}
4023 
4024 	/* CD-specific configuration parameters */
4025 	if (flags & SD_CONF_BSET_PLAYMSF_BCD) {
4026 		un->un_f_cfg_playmsf_bcd = TRUE;
4027 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4028 		    "sd_set_vers1_properties: playmsf_bcd set\n");
4029 	}
4030 	if (flags & SD_CONF_BSET_READSUB_BCD) {
4031 		un->un_f_cfg_readsub_bcd = TRUE;
4032 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4033 		    "sd_set_vers1_properties: readsub_bcd set\n");
4034 	}
4035 	if (flags & SD_CONF_BSET_READ_TOC_TRK_BCD) {
4036 		un->un_f_cfg_read_toc_trk_bcd = TRUE;
4037 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4038 		    "sd_set_vers1_properties: read_toc_trk_bcd set\n");
4039 	}
4040 	if (flags & SD_CONF_BSET_READ_TOC_ADDR_BCD) {
4041 		un->un_f_cfg_read_toc_addr_bcd = TRUE;
4042 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4043 		    "sd_set_vers1_properties: read_toc_addr_bcd set\n");
4044 	}
4045 	if (flags & SD_CONF_BSET_NO_READ_HEADER) {
4046 		un->un_f_cfg_no_read_header = TRUE;
4047 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4048 		    "sd_set_vers1_properties: no_read_header set\n");
4049 	}
4050 	if (flags & SD_CONF_BSET_READ_CD_XD4) {
4051 		un->un_f_cfg_read_cd_xd4 = TRUE;
4052 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4053 		    "sd_set_vers1_properties: read_cd_xd4 set\n");
4054 	}
4055 
4056 	/* Support for devices which do not have valid/unique serial numbers */
4057 	if (flags & SD_CONF_BSET_FAB_DEVID) {
4058 		un->un_f_opt_fab_devid = TRUE;
4059 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4060 		    "sd_set_vers1_properties: fab_devid bit set\n");
4061 	}
4062 
4063 	/* Support for user throttle configuration */
4064 	if (flags & SD_CONF_BSET_THROTTLE) {
4065 		ASSERT(prop_list != NULL);
4066 		un->un_saved_throttle = un->un_throttle =
4067 		    prop_list->sdt_throttle;
4068 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4069 		    "sd_set_vers1_properties: throttle set to %d\n",
4070 		    prop_list->sdt_throttle);
4071 	}
4072 
4073 	/* Set the per disk retry count according to the conf file or table. */
4074 	if (flags & SD_CONF_BSET_NRR_COUNT) {
4075 		ASSERT(prop_list != NULL);
4076 		if (prop_list->sdt_not_rdy_retries) {
4077 			un->un_notready_retry_count =
4078 			    prop_list->sdt_not_rdy_retries;
4079 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4080 			    "sd_set_vers1_properties: not ready retry count"
4081 			    " set to %d\n", un->un_notready_retry_count);
4082 		}
4083 	}
4084 
4085 	/* The controller type is reported for generic disk driver ioctls */
4086 	if (flags & SD_CONF_BSET_CTYPE) {
4087 		ASSERT(prop_list != NULL);
4088 		switch (prop_list->sdt_ctype) {
4089 		case CTYPE_CDROM:
4090 			un->un_ctype = prop_list->sdt_ctype;
4091 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4092 			    "sd_set_vers1_properties: ctype set to "
4093 			    "CTYPE_CDROM\n");
4094 			break;
4095 		case CTYPE_CCS:
4096 			un->un_ctype = prop_list->sdt_ctype;
4097 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4098 			    "sd_set_vers1_properties: ctype set to "
4099 			    "CTYPE_CCS\n");
4100 			break;
4101 		case CTYPE_ROD:		/* RW optical */
4102 			un->un_ctype = prop_list->sdt_ctype;
4103 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4104 			    "sd_set_vers1_properties: ctype set to "
4105 			    "CTYPE_ROD\n");
4106 			break;
4107 		default:
4108 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
4109 			    "sd_set_vers1_properties: Could not set "
4110 			    "invalid ctype value (%d)",
4111 			    prop_list->sdt_ctype);
4112 		}
4113 	}
4114 
4115 	/* Purple failover timeout */
4116 	if (flags & SD_CONF_BSET_BSY_RETRY_COUNT) {
4117 		ASSERT(prop_list != NULL);
4118 		un->un_busy_retry_count =
4119 		    prop_list->sdt_busy_retries;
4120 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4121 		    "sd_set_vers1_properties: "
4122 		    "busy retry count set to %d\n",
4123 		    un->un_busy_retry_count);
4124 	}
4125 
4126 	/* Purple reset retry count */
4127 	if (flags & SD_CONF_BSET_RST_RETRIES) {
4128 		ASSERT(prop_list != NULL);
4129 		un->un_reset_retry_count =
4130 		    prop_list->sdt_reset_retries;
4131 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4132 		    "sd_set_vers1_properties: "
4133 		    "reset retry count set to %d\n",
4134 		    un->un_reset_retry_count);
4135 	}
4136 
4137 	/* Purple reservation release timeout */
4138 	if (flags & SD_CONF_BSET_RSV_REL_TIME) {
4139 		ASSERT(prop_list != NULL);
4140 		un->un_reserve_release_time =
4141 		    prop_list->sdt_reserv_rel_time;
4142 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4143 		    "sd_set_vers1_properties: "
4144 		    "reservation release timeout set to %d\n",
4145 		    un->un_reserve_release_time);
4146 	}
4147 
4148 	/*
4149 	 * Driver flag telling the driver to verify that no commands are pending
4150 	 * for a device before issuing a Test Unit Ready. This is a workaround
4151 	 * for a firmware bug in some Seagate eliteI drives.
4152 	 */
4153 	if (flags & SD_CONF_BSET_TUR_CHECK) {
4154 		un->un_f_cfg_tur_check = TRUE;
4155 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4156 		    "sd_set_vers1_properties: tur queue check set\n");
4157 	}
4158 
4159 	if (flags & SD_CONF_BSET_MIN_THROTTLE) {
4160 		un->un_min_throttle = prop_list->sdt_min_throttle;
4161 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4162 		    "sd_set_vers1_properties: min throttle set to %d\n",
4163 		    un->un_min_throttle);
4164 	}
4165 
4166 	if (flags & SD_CONF_BSET_DISKSORT_DISABLED) {
4167 		un->un_f_disksort_disabled =
4168 		    (prop_list->sdt_disk_sort_dis != 0) ?
4169 		    TRUE : FALSE;
4170 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4171 		    "sd_set_vers1_properties: disksort disabled "
4172 		    "flag set to %d\n",
4173 		    prop_list->sdt_disk_sort_dis);
4174 	}
4175 
4176 	if (flags & SD_CONF_BSET_LUN_RESET_ENABLED) {
4177 		un->un_f_lun_reset_enabled =
4178 		    (prop_list->sdt_lun_reset_enable != 0) ?
4179 		    TRUE : FALSE;
4180 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4181 		    "sd_set_vers1_properties: lun reset enabled "
4182 		    "flag set to %d\n",
4183 		    prop_list->sdt_lun_reset_enable);
4184 	}
4185 
4186 	if (flags & SD_CONF_BSET_CACHE_IS_NV) {
4187 		un->un_f_suppress_cache_flush =
4188 		    (prop_list->sdt_suppress_cache_flush != 0) ?
4189 		    TRUE : FALSE;
4190 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
4191 		    "sd_set_vers1_properties: suppress_cache_flush "
4192 		    "flag set to %d\n",
4193 		    prop_list->sdt_suppress_cache_flush);
4194 	}
4195 
4196 	/*
4197 	 * Validate the throttle values.
4198 	 * If any of the numbers are invalid, set everything to defaults.
4199 	 */
4200 	if ((un->un_throttle < SD_LOWEST_VALID_THROTTLE) ||
4201 	    (un->un_min_throttle < SD_LOWEST_VALID_THROTTLE) ||
4202 	    (un->un_min_throttle > un->un_throttle)) {
4203 		un->un_saved_throttle = un->un_throttle = sd_max_throttle;
4204 		un->un_min_throttle = sd_min_throttle;
4205 	}
4206 }
4207 
4208 /*
4209  *   Function: sd_is_lsi()
4210  *
4211  *   Description: Check for lsi devices, step through the static device
4212  *	table to match vid/pid.
4213  *
4214  *   Args: un - ptr to sd_lun
4215  *
4216  *   Notes:  When creating new LSI property, need to add the new LSI property
4217  *		to this function.
4218  */
4219 static void
4220 sd_is_lsi(struct sd_lun *un)
4221 {
4222 	char	*id = NULL;
4223 	int	table_index;
4224 	int	idlen;
4225 	void	*prop;
4226 
4227 	ASSERT(un != NULL);
4228 	for (table_index = 0; table_index < sd_disk_table_size;
4229 	    table_index++) {
4230 		id = sd_disk_table[table_index].device_id;
4231 		idlen = strlen(id);
4232 		if (idlen == 0) {
4233 			continue;
4234 		}
4235 
4236 		if (sd_sdconf_id_match(un, id, idlen) == SD_SUCCESS) {
4237 			prop = sd_disk_table[table_index].properties;
4238 			if (prop == &lsi_properties ||
4239 			    prop == &lsi_oem_properties ||
4240 			    prop == &lsi_properties_scsi ||
4241 			    prop == &symbios_properties) {
4242 				un->un_f_cfg_is_lsi = TRUE;
4243 			}
4244 			break;
4245 		}
4246 	}
4247 }
4248 
4249 /*
4250  *    Function: sd_get_physical_geometry
4251  *
4252  * Description: Retrieve the MODE SENSE page 3 (Format Device Page) and
4253  *		MODE SENSE page 4 (Rigid Disk Drive Geometry Page) from the
4254  *		target, and use this information to initialize the physical
4255  *		geometry cache specified by pgeom_p.
4256  *
4257  *		MODE SENSE is an optional command, so failure in this case
4258  *		does not necessarily denote an error. We want to use the
4259  *		MODE SENSE commands to derive the physical geometry of the
4260  *		device, but if either command fails, the logical geometry is
4261  *		used as the fallback for disk label geometry in cmlb.
4262  *
4263  *		This requires that un->un_blockcount and un->un_tgt_blocksize
4264  *		have already been initialized for the current target and
4265  *		that the current values be passed as args so that we don't
4266  *		end up ever trying to use -1 as a valid value. This could
4267  *		happen if either value is reset while we're not holding
4268  *		the mutex.
4269  *
4270  *   Arguments: un - driver soft state (unit) structure
4271  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
4272  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
4273  *			to use the USCSI "direct" chain and bypass the normal
4274  *			command waitq.
4275  *
4276  *     Context: Kernel thread only (can sleep).
4277  */
4278 
4279 static int
4280 sd_get_physical_geometry(struct sd_lun *un, cmlb_geom_t *pgeom_p,
4281 	diskaddr_t capacity, int lbasize, int path_flag)
4282 {
4283 	struct	mode_format	*page3p;
4284 	struct	mode_geometry	*page4p;
4285 	struct	mode_header	*headerp;
4286 	int	sector_size;
4287 	int	nsect;
4288 	int	nhead;
4289 	int	ncyl;
4290 	int	intrlv;
4291 	int	spc;
4292 	diskaddr_t	modesense_capacity;
4293 	int	rpm;
4294 	int	bd_len;
4295 	int	mode_header_length;
4296 	uchar_t	*p3bufp;
4297 	uchar_t	*p4bufp;
4298 	int	cdbsize;
4299 	int 	ret = EIO;
4300 
4301 	ASSERT(un != NULL);
4302 
4303 	if (lbasize == 0) {
4304 		if (ISCD(un)) {
4305 			lbasize = 2048;
4306 		} else {
4307 			lbasize = un->un_sys_blocksize;
4308 		}
4309 	}
4310 	pgeom_p->g_secsize = (unsigned short)lbasize;
4311 
4312 	/*
4313 	 * If the unit is a cd/dvd drive MODE SENSE page three
4314 	 * and MODE SENSE page four are reserved (see SBC spec
4315 	 * and MMC spec). To prevent soft errors just return
4316 	 * using the default LBA size.
4317 	 */
4318 	if (ISCD(un))
4319 		return (ret);
4320 
4321 	cdbsize = (un->un_f_cfg_is_atapi == TRUE) ? CDB_GROUP2 : CDB_GROUP0;
4322 
4323 	/*
4324 	 * Retrieve MODE SENSE page 3 - Format Device Page
4325 	 */
4326 	p3bufp = kmem_zalloc(SD_MODE_SENSE_PAGE3_LENGTH, KM_SLEEP);
4327 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p3bufp,
4328 	    SD_MODE_SENSE_PAGE3_LENGTH, SD_MODE_SENSE_PAGE3_CODE, path_flag)
4329 	    != 0) {
4330 		SD_ERROR(SD_LOG_COMMON, un,
4331 		    "sd_get_physical_geometry: mode sense page 3 failed\n");
4332 		goto page3_exit;
4333 	}
4334 
4335 	/*
4336 	 * Determine size of Block Descriptors in order to locate the mode
4337 	 * page data.  ATAPI devices return 0, SCSI devices should return
4338 	 * MODE_BLK_DESC_LENGTH.
4339 	 */
4340 	headerp = (struct mode_header *)p3bufp;
4341 	if (un->un_f_cfg_is_atapi == TRUE) {
4342 		struct mode_header_grp2 *mhp =
4343 		    (struct mode_header_grp2 *)headerp;
4344 		mode_header_length = MODE_HEADER_LENGTH_GRP2;
4345 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4346 	} else {
4347 		mode_header_length = MODE_HEADER_LENGTH;
4348 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4349 	}
4350 
4351 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4352 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4353 		    "received unexpected bd_len of %d, page3\n", bd_len);
4354 		goto page3_exit;
4355 	}
4356 
4357 	page3p = (struct mode_format *)
4358 	    ((caddr_t)headerp + mode_header_length + bd_len);
4359 
4360 	if (page3p->mode_page.code != SD_MODE_SENSE_PAGE3_CODE) {
4361 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4362 		    "mode sense pg3 code mismatch %d\n",
4363 		    page3p->mode_page.code);
4364 		goto page3_exit;
4365 	}
4366 
4367 	/*
4368 	 * Use this physical geometry data only if BOTH MODE SENSE commands
4369 	 * complete successfully; otherwise, revert to the logical geometry.
4370 	 * So, we need to save everything in temporary variables.
4371 	 */
4372 	sector_size = BE_16(page3p->data_bytes_sect);
4373 
4374 	/*
4375 	 * 1243403: The NEC D38x7 drives do not support MODE SENSE sector size
4376 	 */
4377 	if (sector_size == 0) {
4378 		sector_size = un->un_sys_blocksize;
4379 	} else {
4380 		sector_size &= ~(un->un_sys_blocksize - 1);
4381 	}
4382 
4383 	nsect  = BE_16(page3p->sect_track);
4384 	intrlv = BE_16(page3p->interleave);
4385 
4386 	SD_INFO(SD_LOG_COMMON, un,
4387 	    "sd_get_physical_geometry: Format Parameters (page 3)\n");
4388 	SD_INFO(SD_LOG_COMMON, un,
4389 	    "   mode page: %d; nsect: %d; sector size: %d;\n",
4390 	    page3p->mode_page.code, nsect, sector_size);
4391 	SD_INFO(SD_LOG_COMMON, un,
4392 	    "   interleave: %d; track skew: %d; cylinder skew: %d;\n", intrlv,
4393 	    BE_16(page3p->track_skew),
4394 	    BE_16(page3p->cylinder_skew));
4395 
4396 
4397 	/*
4398 	 * Retrieve MODE SENSE page 4 - Rigid Disk Drive Geometry Page
4399 	 */
4400 	p4bufp = kmem_zalloc(SD_MODE_SENSE_PAGE4_LENGTH, KM_SLEEP);
4401 	if (sd_send_scsi_MODE_SENSE(un, cdbsize, p4bufp,
4402 	    SD_MODE_SENSE_PAGE4_LENGTH, SD_MODE_SENSE_PAGE4_CODE, path_flag)
4403 	    != 0) {
4404 		SD_ERROR(SD_LOG_COMMON, un,
4405 		    "sd_get_physical_geometry: mode sense page 4 failed\n");
4406 		goto page4_exit;
4407 	}
4408 
4409 	/*
4410 	 * Determine size of Block Descriptors in order to locate the mode
4411 	 * page data.  ATAPI devices return 0, SCSI devices should return
4412 	 * MODE_BLK_DESC_LENGTH.
4413 	 */
4414 	headerp = (struct mode_header *)p4bufp;
4415 	if (un->un_f_cfg_is_atapi == TRUE) {
4416 		struct mode_header_grp2 *mhp =
4417 		    (struct mode_header_grp2 *)headerp;
4418 		bd_len = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
4419 	} else {
4420 		bd_len = ((struct mode_header *)headerp)->bdesc_length;
4421 	}
4422 
4423 	if (bd_len > MODE_BLK_DESC_LENGTH) {
4424 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4425 		    "received unexpected bd_len of %d, page4\n", bd_len);
4426 		goto page4_exit;
4427 	}
4428 
4429 	page4p = (struct mode_geometry *)
4430 	    ((caddr_t)headerp + mode_header_length + bd_len);
4431 
4432 	if (page4p->mode_page.code != SD_MODE_SENSE_PAGE4_CODE) {
4433 		SD_ERROR(SD_LOG_COMMON, un, "sd_get_physical_geometry: "
4434 		    "mode sense pg4 code mismatch %d\n",
4435 		    page4p->mode_page.code);
4436 		goto page4_exit;
4437 	}
4438 
4439 	/*
4440 	 * Stash the data now, after we know that both commands completed.
4441 	 */
4442 
4443 
4444 	nhead = (int)page4p->heads;	/* uchar, so no conversion needed */
4445 	spc   = nhead * nsect;
4446 	ncyl  = (page4p->cyl_ub << 16) + (page4p->cyl_mb << 8) + page4p->cyl_lb;
4447 	rpm   = BE_16(page4p->rpm);
4448 
4449 	modesense_capacity = spc * ncyl;
4450 
4451 	SD_INFO(SD_LOG_COMMON, un,
4452 	    "sd_get_physical_geometry: Geometry Parameters (page 4)\n");
4453 	SD_INFO(SD_LOG_COMMON, un,
4454 	    "   cylinders: %d; heads: %d; rpm: %d;\n", ncyl, nhead, rpm);
4455 	SD_INFO(SD_LOG_COMMON, un,
4456 	    "   computed capacity(h*s*c): %d;\n", modesense_capacity);
4457 	SD_INFO(SD_LOG_COMMON, un, "   pgeom_p: %p; read cap: %d\n",
4458 	    (void *)pgeom_p, capacity);
4459 
4460 	/*
4461 	 * Compensate if the drive's geometry is not rectangular, i.e.,
4462 	 * the product of C * H * S returned by MODE SENSE >= that returned
4463 	 * by read capacity. This is an idiosyncrasy of the original x86
4464 	 * disk subsystem.
4465 	 */
4466 	if (modesense_capacity >= capacity) {
4467 		SD_INFO(SD_LOG_COMMON, un,
4468 		    "sd_get_physical_geometry: adjusting acyl; "
4469 		    "old: %d; new: %d\n", pgeom_p->g_acyl,
4470 		    (modesense_capacity - capacity + spc - 1) / spc);
4471 		if (sector_size != 0) {
4472 			/* 1243403: NEC D38x7 drives don't support sec size */
4473 			pgeom_p->g_secsize = (unsigned short)sector_size;
4474 		}
4475 		pgeom_p->g_nsect    = (unsigned short)nsect;
4476 		pgeom_p->g_nhead    = (unsigned short)nhead;
4477 		pgeom_p->g_capacity = capacity;
4478 		pgeom_p->g_acyl	    =
4479 		    (modesense_capacity - pgeom_p->g_capacity + spc - 1) / spc;
4480 		pgeom_p->g_ncyl	    = ncyl - pgeom_p->g_acyl;
4481 	}
4482 
4483 	pgeom_p->g_rpm    = (unsigned short)rpm;
4484 	pgeom_p->g_intrlv = (unsigned short)intrlv;
4485 	ret = 0;
4486 
4487 	SD_INFO(SD_LOG_COMMON, un,
4488 	    "sd_get_physical_geometry: mode sense geometry:\n");
4489 	SD_INFO(SD_LOG_COMMON, un,
4490 	    "   nsect: %d; sector size: %d; interlv: %d\n",
4491 	    nsect, sector_size, intrlv);
4492 	SD_INFO(SD_LOG_COMMON, un,
4493 	    "   nhead: %d; ncyl: %d; rpm: %d; capacity(ms): %d\n",
4494 	    nhead, ncyl, rpm, modesense_capacity);
4495 	SD_INFO(SD_LOG_COMMON, un,
4496 	    "sd_get_physical_geometry: (cached)\n");
4497 	SD_INFO(SD_LOG_COMMON, un,
4498 	    "   ncyl: %ld; acyl: %d; nhead: %d; nsect: %d\n",
4499 	    pgeom_p->g_ncyl,  pgeom_p->g_acyl,
4500 	    pgeom_p->g_nhead, pgeom_p->g_nsect);
4501 	SD_INFO(SD_LOG_COMMON, un,
4502 	    "   lbasize: %d; capacity: %ld; intrlv: %d; rpm: %d\n",
4503 	    pgeom_p->g_secsize, pgeom_p->g_capacity,
4504 	    pgeom_p->g_intrlv, pgeom_p->g_rpm);
4505 
4506 page4_exit:
4507 	kmem_free(p4bufp, SD_MODE_SENSE_PAGE4_LENGTH);
4508 page3_exit:
4509 	kmem_free(p3bufp, SD_MODE_SENSE_PAGE3_LENGTH);
4510 
4511 	return (ret);
4512 }
4513 
4514 /*
4515  *    Function: sd_get_virtual_geometry
4516  *
4517  * Description: Ask the controller to tell us about the target device.
4518  *
4519  *   Arguments: un - pointer to softstate
4520  *		capacity - disk capacity in #blocks
4521  *		lbasize - disk block size in bytes
4522  *
4523  *     Context: Kernel thread only
4524  */
4525 
4526 static int
4527 sd_get_virtual_geometry(struct sd_lun *un, cmlb_geom_t *lgeom_p,
4528     diskaddr_t capacity, int lbasize)
4529 {
4530 	uint_t	geombuf;
4531 	int	spc;
4532 
4533 	ASSERT(un != NULL);
4534 
4535 	/* Set sector size, and total number of sectors */
4536 	(void) scsi_ifsetcap(SD_ADDRESS(un), "sector-size",   lbasize,  1);
4537 	(void) scsi_ifsetcap(SD_ADDRESS(un), "total-sectors", capacity, 1);
4538 
4539 	/* Let the HBA tell us its geometry */
4540 	geombuf = (uint_t)scsi_ifgetcap(SD_ADDRESS(un), "geometry", 1);
4541 
4542 	/* A value of -1 indicates an undefined "geometry" property */
4543 	if (geombuf == (-1)) {
4544 		return (EINVAL);
4545 	}
4546 
4547 	/* Initialize the logical geometry cache. */
4548 	lgeom_p->g_nhead   = (geombuf >> 16) & 0xffff;
4549 	lgeom_p->g_nsect   = geombuf & 0xffff;
4550 	lgeom_p->g_secsize = un->un_sys_blocksize;
4551 
4552 	spc = lgeom_p->g_nhead * lgeom_p->g_nsect;
4553 
4554 	/*
4555 	 * Note: The driver originally converted the capacity value from
4556 	 * target blocks to system blocks. However, the capacity value passed
4557 	 * to this routine is already in terms of system blocks (this scaling
4558 	 * is done when the READ CAPACITY command is issued and processed).
4559 	 * This 'error' may have gone undetected because the usage of g_ncyl
4560 	 * (which is based upon g_capacity) is very limited within the driver
4561 	 */
4562 	lgeom_p->g_capacity = capacity;
4563 
4564 	/*
4565 	 * Set ncyl to zero if the hba returned a zero nhead or nsect value. The
4566 	 * hba may return zero values if the device has been removed.
4567 	 */
4568 	if (spc == 0) {
4569 		lgeom_p->g_ncyl = 0;
4570 	} else {
4571 		lgeom_p->g_ncyl = lgeom_p->g_capacity / spc;
4572 	}
4573 	lgeom_p->g_acyl = 0;
4574 
4575 	SD_INFO(SD_LOG_COMMON, un, "sd_get_virtual_geometry: (cached)\n");
4576 	return (0);
4577 
4578 }
4579 /*
4580  *    Function: sd_update_block_info
4581  *
4582  * Description: Calculate a byte count to sector count bitshift value
4583  *		from sector size.
4584  *
4585  *   Arguments: un: unit struct.
4586  *		lbasize: new target sector size
4587  *		capacity: new target capacity, ie. block count
4588  *
4589  *     Context: Kernel thread context
4590  */
4591 
4592 static void
4593 sd_update_block_info(struct sd_lun *un, uint32_t lbasize, uint64_t capacity)
4594 {
4595 	uint_t		dblk;
4596 
4597 	if (lbasize != 0) {
4598 		un->un_tgt_blocksize = lbasize;
4599 		un->un_f_tgt_blocksize_is_valid	= TRUE;
4600 	}
4601 
4602 	if (capacity != 0) {
4603 		un->un_blockcount		= capacity;
4604 		un->un_f_blockcount_is_valid	= TRUE;
4605 	}
4606 
4607 	/*
4608 	 * Update device capacity properties.
4609 	 *
4610 	 *   'device-nblocks'	number of blocks in target's units
4611 	 *   'device-blksize'	data bearing size of target's block
4612 	 *
4613 	 * NOTE: math is complicated by the fact that un_tgt_blocksize may
4614 	 * not be a power of two for checksumming disks with 520/528 byte
4615 	 * sectors.
4616 	 */
4617 	if (un->un_f_tgt_blocksize_is_valid &&
4618 	    un->un_f_blockcount_is_valid &&
4619 	    un->un_sys_blocksize) {
4620 		dblk = un->un_tgt_blocksize / un->un_sys_blocksize;
4621 		(void) ddi_prop_update_int64(DDI_DEV_T_NONE, SD_DEVINFO(un),
4622 		    "device-nblocks", un->un_blockcount / dblk);
4623 		/*
4624 		 * To save memory, only define "device-blksize" when its
4625 		 * value is differnet than the default DEV_BSIZE value.
4626 		 */
4627 		if ((un->un_sys_blocksize * dblk) != DEV_BSIZE)
4628 			(void) ddi_prop_update_int(DDI_DEV_T_NONE,
4629 			    SD_DEVINFO(un), "device-blksize",
4630 			    un->un_sys_blocksize * dblk);
4631 	}
4632 }
4633 
4634 
4635 /*
4636  *    Function: sd_register_devid
4637  *
4638  * Description: This routine will obtain the device id information from the
4639  *		target, obtain the serial number, and register the device
4640  *		id with the ddi framework.
4641  *
4642  *   Arguments: devi - the system's dev_info_t for the device.
4643  *		un - driver soft state (unit) structure
4644  *		reservation_flag - indicates if a reservation conflict
4645  *		occurred during attach
4646  *
4647  *     Context: Kernel Thread
4648  */
4649 static void
4650 sd_register_devid(struct sd_lun *un, dev_info_t *devi, int reservation_flag)
4651 {
4652 	int		rval		= 0;
4653 	uchar_t		*inq80		= NULL;
4654 	size_t		inq80_len	= MAX_INQUIRY_SIZE;
4655 	size_t		inq80_resid	= 0;
4656 	uchar_t		*inq83		= NULL;
4657 	size_t		inq83_len	= MAX_INQUIRY_SIZE;
4658 	size_t		inq83_resid	= 0;
4659 	int		dlen, len;
4660 	char		*sn;
4661 
4662 	ASSERT(un != NULL);
4663 	ASSERT(mutex_owned(SD_MUTEX(un)));
4664 	ASSERT((SD_DEVINFO(un)) == devi);
4665 
4666 	/*
4667 	 * If transport has already registered a devid for this target
4668 	 * then that takes precedence over the driver's determination
4669 	 * of the devid.
4670 	 */
4671 	if (ddi_devid_get(SD_DEVINFO(un), &un->un_devid) == DDI_SUCCESS) {
4672 		ASSERT(un->un_devid);
4673 		return; /* use devid registered by the transport */
4674 	}
4675 
4676 	/*
4677 	 * This is the case of antiquated Sun disk drives that have the
4678 	 * FAB_DEVID property set in the disk_table.  These drives
4679 	 * manage the devid's by storing them in last 2 available sectors
4680 	 * on the drive and have them fabricated by the ddi layer by calling
4681 	 * ddi_devid_init and passing the DEVID_FAB flag.
4682 	 */
4683 	if (un->un_f_opt_fab_devid == TRUE) {
4684 		/*
4685 		 * Depending on EINVAL isn't reliable, since a reserved disk
4686 		 * may result in invalid geometry, so check to make sure a
4687 		 * reservation conflict did not occur during attach.
4688 		 */
4689 		if ((sd_get_devid(un) == EINVAL) &&
4690 		    (reservation_flag != SD_TARGET_IS_RESERVED)) {
4691 			/*
4692 			 * The devid is invalid AND there is no reservation
4693 			 * conflict.  Fabricate a new devid.
4694 			 */
4695 			(void) sd_create_devid(un);
4696 		}
4697 
4698 		/* Register the devid if it exists */
4699 		if (un->un_devid != NULL) {
4700 			(void) ddi_devid_register(SD_DEVINFO(un),
4701 			    un->un_devid);
4702 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4703 			    "sd_register_devid: Devid Fabricated\n");
4704 		}
4705 		return;
4706 	}
4707 
4708 	/*
4709 	 * We check the availibility of the World Wide Name (0x83) and Unit
4710 	 * Serial Number (0x80) pages in sd_check_vpd_page_support(), and using
4711 	 * un_vpd_page_mask from them, we decide which way to get the WWN.  If
4712 	 * 0x83 is availible, that is the best choice.  Our next choice is
4713 	 * 0x80.  If neither are availible, we munge the devid from the device
4714 	 * vid/pid/serial # for Sun qualified disks, or use the ddi framework
4715 	 * to fabricate a devid for non-Sun qualified disks.
4716 	 */
4717 	if (sd_check_vpd_page_support(un) == 0) {
4718 		/* collect page 80 data if available */
4719 		if (un->un_vpd_page_mask & SD_VPD_UNIT_SERIAL_PG) {
4720 
4721 			mutex_exit(SD_MUTEX(un));
4722 			inq80 = kmem_zalloc(inq80_len, KM_SLEEP);
4723 			rval = sd_send_scsi_INQUIRY(un, inq80, inq80_len,
4724 			    0x01, 0x80, &inq80_resid);
4725 
4726 			if (rval != 0) {
4727 				kmem_free(inq80, inq80_len);
4728 				inq80 = NULL;
4729 				inq80_len = 0;
4730 			} else if (ddi_prop_exists(
4731 			    DDI_DEV_T_NONE, SD_DEVINFO(un),
4732 			    DDI_PROP_NOTPROM | DDI_PROP_DONTPASS,
4733 			    INQUIRY_SERIAL_NO) == 0) {
4734 				/*
4735 				 * If we don't already have a serial number
4736 				 * property, do quick verify of data returned
4737 				 * and define property.
4738 				 */
4739 				dlen = inq80_len - inq80_resid;
4740 				len = (size_t)inq80[3];
4741 				if ((dlen >= 4) && ((len + 4) <= dlen)) {
4742 					/*
4743 					 * Ensure sn termination, skip leading
4744 					 * blanks, and create property
4745 					 * 'inquiry-serial-no'.
4746 					 */
4747 					sn = (char *)&inq80[4];
4748 					sn[len] = 0;
4749 					while (*sn && (*sn == ' '))
4750 						sn++;
4751 					if (*sn) {
4752 						(void) ddi_prop_update_string(
4753 						    DDI_DEV_T_NONE,
4754 						    SD_DEVINFO(un),
4755 						    INQUIRY_SERIAL_NO, sn);
4756 					}
4757 				}
4758 			}
4759 			mutex_enter(SD_MUTEX(un));
4760 		}
4761 
4762 		/* collect page 83 data if available */
4763 		if (un->un_vpd_page_mask & SD_VPD_DEVID_WWN_PG) {
4764 			mutex_exit(SD_MUTEX(un));
4765 			inq83 = kmem_zalloc(inq83_len, KM_SLEEP);
4766 			rval = sd_send_scsi_INQUIRY(un, inq83, inq83_len,
4767 			    0x01, 0x83, &inq83_resid);
4768 
4769 			if (rval != 0) {
4770 				kmem_free(inq83, inq83_len);
4771 				inq83 = NULL;
4772 				inq83_len = 0;
4773 			}
4774 			mutex_enter(SD_MUTEX(un));
4775 		}
4776 	}
4777 
4778 	/* encode best devid possible based on data available */
4779 	if (ddi_devid_scsi_encode(DEVID_SCSI_ENCODE_VERSION_LATEST,
4780 	    (char *)ddi_driver_name(SD_DEVINFO(un)),
4781 	    (uchar_t *)SD_INQUIRY(un), sizeof (*SD_INQUIRY(un)),
4782 	    inq80, inq80_len - inq80_resid, inq83, inq83_len -
4783 	    inq83_resid, &un->un_devid) == DDI_SUCCESS) {
4784 
4785 		/* devid successfully encoded, register devid */
4786 		(void) ddi_devid_register(SD_DEVINFO(un), un->un_devid);
4787 
4788 	} else {
4789 		/*
4790 		 * Unable to encode a devid based on data available.
4791 		 * This is not a Sun qualified disk.  Older Sun disk
4792 		 * drives that have the SD_FAB_DEVID property
4793 		 * set in the disk_table and non Sun qualified
4794 		 * disks are treated in the same manner.  These
4795 		 * drives manage the devid's by storing them in
4796 		 * last 2 available sectors on the drive and
4797 		 * have them fabricated by the ddi layer by
4798 		 * calling ddi_devid_init and passing the
4799 		 * DEVID_FAB flag.
4800 		 * Create a fabricate devid only if there's no
4801 		 * fabricate devid existed.
4802 		 */
4803 		if (sd_get_devid(un) == EINVAL) {
4804 			(void) sd_create_devid(un);
4805 		}
4806 		un->un_f_opt_fab_devid = TRUE;
4807 
4808 		/* Register the devid if it exists */
4809 		if (un->un_devid != NULL) {
4810 			(void) ddi_devid_register(SD_DEVINFO(un),
4811 			    un->un_devid);
4812 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
4813 			    "sd_register_devid: devid fabricated using "
4814 			    "ddi framework\n");
4815 		}
4816 	}
4817 
4818 	/* clean up resources */
4819 	if (inq80 != NULL) {
4820 		kmem_free(inq80, inq80_len);
4821 	}
4822 	if (inq83 != NULL) {
4823 		kmem_free(inq83, inq83_len);
4824 	}
4825 }
4826 
4827 
4828 
4829 /*
4830  *    Function: sd_get_devid
4831  *
4832  * Description: This routine will return 0 if a valid device id has been
4833  *		obtained from the target and stored in the soft state. If a
4834  *		valid device id has not been previously read and stored, a
4835  *		read attempt will be made.
4836  *
4837  *   Arguments: un - driver soft state (unit) structure
4838  *
4839  * Return Code: 0 if we successfully get the device id
4840  *
4841  *     Context: Kernel Thread
4842  */
4843 
4844 static int
4845 sd_get_devid(struct sd_lun *un)
4846 {
4847 	struct dk_devid		*dkdevid;
4848 	ddi_devid_t		tmpid;
4849 	uint_t			*ip;
4850 	size_t			sz;
4851 	diskaddr_t		blk;
4852 	int			status;
4853 	int			chksum;
4854 	int			i;
4855 	size_t			buffer_size;
4856 
4857 	ASSERT(un != NULL);
4858 	ASSERT(mutex_owned(SD_MUTEX(un)));
4859 
4860 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: entry: un: 0x%p\n",
4861 	    un);
4862 
4863 	if (un->un_devid != NULL) {
4864 		return (0);
4865 	}
4866 
4867 	mutex_exit(SD_MUTEX(un));
4868 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
4869 	    (void *)SD_PATH_DIRECT) != 0) {
4870 		mutex_enter(SD_MUTEX(un));
4871 		return (EINVAL);
4872 	}
4873 
4874 	/*
4875 	 * Read and verify device id, stored in the reserved cylinders at the
4876 	 * end of the disk. Backup label is on the odd sectors of the last
4877 	 * track of the last cylinder. Device id will be on track of the next
4878 	 * to last cylinder.
4879 	 */
4880 	mutex_enter(SD_MUTEX(un));
4881 	buffer_size = SD_REQBYTES2TGTBYTES(un, sizeof (struct dk_devid));
4882 	mutex_exit(SD_MUTEX(un));
4883 	dkdevid = kmem_alloc(buffer_size, KM_SLEEP);
4884 	status = sd_send_scsi_READ(un, dkdevid, buffer_size, blk,
4885 	    SD_PATH_DIRECT);
4886 	if (status != 0) {
4887 		goto error;
4888 	}
4889 
4890 	/* Validate the revision */
4891 	if ((dkdevid->dkd_rev_hi != DK_DEVID_REV_MSB) ||
4892 	    (dkdevid->dkd_rev_lo != DK_DEVID_REV_LSB)) {
4893 		status = EINVAL;
4894 		goto error;
4895 	}
4896 
4897 	/* Calculate the checksum */
4898 	chksum = 0;
4899 	ip = (uint_t *)dkdevid;
4900 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
4901 	    i++) {
4902 		chksum ^= ip[i];
4903 	}
4904 
4905 	/* Compare the checksums */
4906 	if (DKD_GETCHKSUM(dkdevid) != chksum) {
4907 		status = EINVAL;
4908 		goto error;
4909 	}
4910 
4911 	/* Validate the device id */
4912 	if (ddi_devid_valid((ddi_devid_t)&dkdevid->dkd_devid) != DDI_SUCCESS) {
4913 		status = EINVAL;
4914 		goto error;
4915 	}
4916 
4917 	/*
4918 	 * Store the device id in the driver soft state
4919 	 */
4920 	sz = ddi_devid_sizeof((ddi_devid_t)&dkdevid->dkd_devid);
4921 	tmpid = kmem_alloc(sz, KM_SLEEP);
4922 
4923 	mutex_enter(SD_MUTEX(un));
4924 
4925 	un->un_devid = tmpid;
4926 	bcopy(&dkdevid->dkd_devid, un->un_devid, sz);
4927 
4928 	kmem_free(dkdevid, buffer_size);
4929 
4930 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_get_devid: exit: un:0x%p\n", un);
4931 
4932 	return (status);
4933 error:
4934 	mutex_enter(SD_MUTEX(un));
4935 	kmem_free(dkdevid, buffer_size);
4936 	return (status);
4937 }
4938 
4939 
4940 /*
4941  *    Function: sd_create_devid
4942  *
4943  * Description: This routine will fabricate the device id and write it
4944  *		to the disk.
4945  *
4946  *   Arguments: un - driver soft state (unit) structure
4947  *
4948  * Return Code: value of the fabricated device id
4949  *
4950  *     Context: Kernel Thread
4951  */
4952 
4953 static ddi_devid_t
4954 sd_create_devid(struct sd_lun *un)
4955 {
4956 	ASSERT(un != NULL);
4957 
4958 	/* Fabricate the devid */
4959 	if (ddi_devid_init(SD_DEVINFO(un), DEVID_FAB, 0, NULL, &un->un_devid)
4960 	    == DDI_FAILURE) {
4961 		return (NULL);
4962 	}
4963 
4964 	/* Write the devid to disk */
4965 	if (sd_write_deviceid(un) != 0) {
4966 		ddi_devid_free(un->un_devid);
4967 		un->un_devid = NULL;
4968 	}
4969 
4970 	return (un->un_devid);
4971 }
4972 
4973 
4974 /*
4975  *    Function: sd_write_deviceid
4976  *
4977  * Description: This routine will write the device id to the disk
4978  *		reserved sector.
4979  *
4980  *   Arguments: un - driver soft state (unit) structure
4981  *
4982  * Return Code: EINVAL
4983  *		value returned by sd_send_scsi_cmd
4984  *
4985  *     Context: Kernel Thread
4986  */
4987 
4988 static int
4989 sd_write_deviceid(struct sd_lun *un)
4990 {
4991 	struct dk_devid		*dkdevid;
4992 	diskaddr_t		blk;
4993 	uint_t			*ip, chksum;
4994 	int			status;
4995 	int			i;
4996 
4997 	ASSERT(mutex_owned(SD_MUTEX(un)));
4998 
4999 	mutex_exit(SD_MUTEX(un));
5000 	if (cmlb_get_devid_block(un->un_cmlbhandle, &blk,
5001 	    (void *)SD_PATH_DIRECT) != 0) {
5002 		mutex_enter(SD_MUTEX(un));
5003 		return (-1);
5004 	}
5005 
5006 
5007 	/* Allocate the buffer */
5008 	dkdevid = kmem_zalloc(un->un_sys_blocksize, KM_SLEEP);
5009 
5010 	/* Fill in the revision */
5011 	dkdevid->dkd_rev_hi = DK_DEVID_REV_MSB;
5012 	dkdevid->dkd_rev_lo = DK_DEVID_REV_LSB;
5013 
5014 	/* Copy in the device id */
5015 	mutex_enter(SD_MUTEX(un));
5016 	bcopy(un->un_devid, &dkdevid->dkd_devid,
5017 	    ddi_devid_sizeof(un->un_devid));
5018 	mutex_exit(SD_MUTEX(un));
5019 
5020 	/* Calculate the checksum */
5021 	chksum = 0;
5022 	ip = (uint_t *)dkdevid;
5023 	for (i = 0; i < ((un->un_sys_blocksize - sizeof (int))/sizeof (int));
5024 	    i++) {
5025 		chksum ^= ip[i];
5026 	}
5027 
5028 	/* Fill-in checksum */
5029 	DKD_FORMCHKSUM(chksum, dkdevid);
5030 
5031 	/* Write the reserved sector */
5032 	status = sd_send_scsi_WRITE(un, dkdevid, un->un_sys_blocksize, blk,
5033 	    SD_PATH_DIRECT);
5034 
5035 	kmem_free(dkdevid, un->un_sys_blocksize);
5036 
5037 	mutex_enter(SD_MUTEX(un));
5038 	return (status);
5039 }
5040 
5041 
5042 /*
5043  *    Function: sd_check_vpd_page_support
5044  *
5045  * Description: This routine sends an inquiry command with the EVPD bit set and
5046  *		a page code of 0x00 to the device. It is used to determine which
5047  *		vital product pages are availible to find the devid. We are
5048  *		looking for pages 0x83 or 0x80.  If we return a negative 1, the
5049  *		device does not support that command.
5050  *
5051  *   Arguments: un  - driver soft state (unit) structure
5052  *
5053  * Return Code: 0 - success
5054  *		1 - check condition
5055  *
5056  *     Context: This routine can sleep.
5057  */
5058 
5059 static int
5060 sd_check_vpd_page_support(struct sd_lun *un)
5061 {
5062 	uchar_t	*page_list	= NULL;
5063 	uchar_t	page_length	= 0xff;	/* Use max possible length */
5064 	uchar_t	evpd		= 0x01;	/* Set the EVPD bit */
5065 	uchar_t	page_code	= 0x00;	/* Supported VPD Pages */
5066 	int    	rval		= 0;
5067 	int	counter;
5068 
5069 	ASSERT(un != NULL);
5070 	ASSERT(mutex_owned(SD_MUTEX(un)));
5071 
5072 	mutex_exit(SD_MUTEX(un));
5073 
5074 	/*
5075 	 * We'll set the page length to the maximum to save figuring it out
5076 	 * with an additional call.
5077 	 */
5078 	page_list =  kmem_zalloc(page_length, KM_SLEEP);
5079 
5080 	rval = sd_send_scsi_INQUIRY(un, page_list, page_length, evpd,
5081 	    page_code, NULL);
5082 
5083 	mutex_enter(SD_MUTEX(un));
5084 
5085 	/*
5086 	 * Now we must validate that the device accepted the command, as some
5087 	 * drives do not support it.  If the drive does support it, we will
5088 	 * return 0, and the supported pages will be in un_vpd_page_mask.  If
5089 	 * not, we return -1.
5090 	 */
5091 	if ((rval == 0) && (page_list[VPD_MODE_PAGE] == 0x00)) {
5092 		/* Loop to find one of the 2 pages we need */
5093 		counter = 4;  /* Supported pages start at byte 4, with 0x00 */
5094 
5095 		/*
5096 		 * Pages are returned in ascending order, and 0x83 is what we
5097 		 * are hoping for.
5098 		 */
5099 		while ((page_list[counter] <= 0x86) &&
5100 		    (counter <= (page_list[VPD_PAGE_LENGTH] +
5101 		    VPD_HEAD_OFFSET))) {
5102 			/*
5103 			 * Add 3 because page_list[3] is the number of
5104 			 * pages minus 3
5105 			 */
5106 
5107 			switch (page_list[counter]) {
5108 			case 0x00:
5109 				un->un_vpd_page_mask |= SD_VPD_SUPPORTED_PG;
5110 				break;
5111 			case 0x80:
5112 				un->un_vpd_page_mask |= SD_VPD_UNIT_SERIAL_PG;
5113 				break;
5114 			case 0x81:
5115 				un->un_vpd_page_mask |= SD_VPD_OPERATING_PG;
5116 				break;
5117 			case 0x82:
5118 				un->un_vpd_page_mask |= SD_VPD_ASCII_OP_PG;
5119 				break;
5120 			case 0x83:
5121 				un->un_vpd_page_mask |= SD_VPD_DEVID_WWN_PG;
5122 				break;
5123 			case 0x86:
5124 				un->un_vpd_page_mask |= SD_VPD_EXTENDED_DATA_PG;
5125 				break;
5126 			}
5127 			counter++;
5128 		}
5129 
5130 	} else {
5131 		rval = -1;
5132 
5133 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
5134 		    "sd_check_vpd_page_support: This drive does not implement "
5135 		    "VPD pages.\n");
5136 	}
5137 
5138 	kmem_free(page_list, page_length);
5139 
5140 	return (rval);
5141 }
5142 
5143 
5144 /*
5145  *    Function: sd_setup_pm
5146  *
5147  * Description: Initialize Power Management on the device
5148  *
5149  *     Context: Kernel Thread
5150  */
5151 
5152 static void
5153 sd_setup_pm(struct sd_lun *un, dev_info_t *devi)
5154 {
5155 	uint_t	log_page_size;
5156 	uchar_t	*log_page_data;
5157 	int	rval;
5158 
5159 	/*
5160 	 * Since we are called from attach, holding a mutex for
5161 	 * un is unnecessary. Because some of the routines called
5162 	 * from here require SD_MUTEX to not be held, assert this
5163 	 * right up front.
5164 	 */
5165 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5166 	/*
5167 	 * Since the sd device does not have the 'reg' property,
5168 	 * cpr will not call its DDI_SUSPEND/DDI_RESUME entries.
5169 	 * The following code is to tell cpr that this device
5170 	 * DOES need to be suspended and resumed.
5171 	 */
5172 	(void) ddi_prop_update_string(DDI_DEV_T_NONE, devi,
5173 	    "pm-hardware-state", "needs-suspend-resume");
5174 
5175 	/*
5176 	 * This complies with the new power management framework
5177 	 * for certain desktop machines. Create the pm_components
5178 	 * property as a string array property.
5179 	 */
5180 	if (un->un_f_pm_supported) {
5181 		/*
5182 		 * not all devices have a motor, try it first.
5183 		 * some devices may return ILLEGAL REQUEST, some
5184 		 * will hang
5185 		 * The following START_STOP_UNIT is used to check if target
5186 		 * device has a motor.
5187 		 */
5188 		un->un_f_start_stop_supported = TRUE;
5189 		if (sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
5190 		    SD_PATH_DIRECT) != 0) {
5191 			un->un_f_start_stop_supported = FALSE;
5192 		}
5193 
5194 		/*
5195 		 * create pm properties anyways otherwise the parent can't
5196 		 * go to sleep
5197 		 */
5198 		(void) sd_create_pm_components(devi, un);
5199 		un->un_f_pm_is_enabled = TRUE;
5200 		return;
5201 	}
5202 
5203 	if (!un->un_f_log_sense_supported) {
5204 		un->un_power_level = SD_SPINDLE_ON;
5205 		un->un_f_pm_is_enabled = FALSE;
5206 		return;
5207 	}
5208 
5209 	rval = sd_log_page_supported(un, START_STOP_CYCLE_PAGE);
5210 
5211 #ifdef	SDDEBUG
5212 	if (sd_force_pm_supported) {
5213 		/* Force a successful result */
5214 		rval = 1;
5215 	}
5216 #endif
5217 
5218 	/*
5219 	 * If the start-stop cycle counter log page is not supported
5220 	 * or if the pm-capable property is SD_PM_CAPABLE_FALSE (0)
5221 	 * then we should not create the pm_components property.
5222 	 */
5223 	if (rval == -1) {
5224 		/*
5225 		 * Error.
5226 		 * Reading log sense failed, most likely this is
5227 		 * an older drive that does not support log sense.
5228 		 * If this fails auto-pm is not supported.
5229 		 */
5230 		un->un_power_level = SD_SPINDLE_ON;
5231 		un->un_f_pm_is_enabled = FALSE;
5232 
5233 	} else if (rval == 0) {
5234 		/*
5235 		 * Page not found.
5236 		 * The start stop cycle counter is implemented as page
5237 		 * START_STOP_CYCLE_PAGE_VU_PAGE (0x31) in older disks. For
5238 		 * newer disks it is implemented as START_STOP_CYCLE_PAGE (0xE).
5239 		 */
5240 		if (sd_log_page_supported(un, START_STOP_CYCLE_VU_PAGE) == 1) {
5241 			/*
5242 			 * Page found, use this one.
5243 			 */
5244 			un->un_start_stop_cycle_page = START_STOP_CYCLE_VU_PAGE;
5245 			un->un_f_pm_is_enabled = TRUE;
5246 		} else {
5247 			/*
5248 			 * Error or page not found.
5249 			 * auto-pm is not supported for this device.
5250 			 */
5251 			un->un_power_level = SD_SPINDLE_ON;
5252 			un->un_f_pm_is_enabled = FALSE;
5253 		}
5254 	} else {
5255 		/*
5256 		 * Page found, use it.
5257 		 */
5258 		un->un_start_stop_cycle_page = START_STOP_CYCLE_PAGE;
5259 		un->un_f_pm_is_enabled = TRUE;
5260 	}
5261 
5262 
5263 	if (un->un_f_pm_is_enabled == TRUE) {
5264 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5265 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5266 
5267 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
5268 		    log_page_size, un->un_start_stop_cycle_page,
5269 		    0x01, 0, SD_PATH_DIRECT);
5270 #ifdef	SDDEBUG
5271 		if (sd_force_pm_supported) {
5272 			/* Force a successful result */
5273 			rval = 0;
5274 		}
5275 #endif
5276 
5277 		/*
5278 		 * If the Log sense for Page( Start/stop cycle counter page)
5279 		 * succeeds, then power managment is supported and we can
5280 		 * enable auto-pm.
5281 		 */
5282 		if (rval == 0)  {
5283 			(void) sd_create_pm_components(devi, un);
5284 		} else {
5285 			un->un_power_level = SD_SPINDLE_ON;
5286 			un->un_f_pm_is_enabled = FALSE;
5287 		}
5288 
5289 		kmem_free(log_page_data, log_page_size);
5290 	}
5291 }
5292 
5293 
5294 /*
5295  *    Function: sd_create_pm_components
5296  *
5297  * Description: Initialize PM property.
5298  *
5299  *     Context: Kernel thread context
5300  */
5301 
5302 static void
5303 sd_create_pm_components(dev_info_t *devi, struct sd_lun *un)
5304 {
5305 	char *pm_comp[] = { "NAME=spindle-motor", "0=off", "1=on", NULL };
5306 
5307 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5308 
5309 	if (ddi_prop_update_string_array(DDI_DEV_T_NONE, devi,
5310 	    "pm-components", pm_comp, 3) == DDI_PROP_SUCCESS) {
5311 		/*
5312 		 * When components are initially created they are idle,
5313 		 * power up any non-removables.
5314 		 * Note: the return value of pm_raise_power can't be used
5315 		 * for determining if PM should be enabled for this device.
5316 		 * Even if you check the return values and remove this
5317 		 * property created above, the PM framework will not honor the
5318 		 * change after the first call to pm_raise_power. Hence,
5319 		 * removal of that property does not help if pm_raise_power
5320 		 * fails. In the case of removable media, the start/stop
5321 		 * will fail if the media is not present.
5322 		 */
5323 		if (un->un_f_attach_spinup && (pm_raise_power(SD_DEVINFO(un), 0,
5324 		    SD_SPINDLE_ON) == DDI_SUCCESS)) {
5325 			mutex_enter(SD_MUTEX(un));
5326 			un->un_power_level = SD_SPINDLE_ON;
5327 			mutex_enter(&un->un_pm_mutex);
5328 			/* Set to on and not busy. */
5329 			un->un_pm_count = 0;
5330 		} else {
5331 			mutex_enter(SD_MUTEX(un));
5332 			un->un_power_level = SD_SPINDLE_OFF;
5333 			mutex_enter(&un->un_pm_mutex);
5334 			/* Set to off. */
5335 			un->un_pm_count = -1;
5336 		}
5337 		mutex_exit(&un->un_pm_mutex);
5338 		mutex_exit(SD_MUTEX(un));
5339 	} else {
5340 		un->un_power_level = SD_SPINDLE_ON;
5341 		un->un_f_pm_is_enabled = FALSE;
5342 	}
5343 }
5344 
5345 
5346 /*
5347  *    Function: sd_ddi_suspend
5348  *
5349  * Description: Performs system power-down operations. This includes
5350  *		setting the drive state to indicate its suspended so
5351  *		that no new commands will be accepted. Also, wait for
5352  *		all commands that are in transport or queued to a timer
5353  *		for retry to complete. All timeout threads are cancelled.
5354  *
5355  * Return Code: DDI_FAILURE or DDI_SUCCESS
5356  *
5357  *     Context: Kernel thread context
5358  */
5359 
5360 static int
5361 sd_ddi_suspend(dev_info_t *devi)
5362 {
5363 	struct	sd_lun	*un;
5364 	clock_t		wait_cmds_complete;
5365 
5366 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
5367 	if (un == NULL) {
5368 		return (DDI_FAILURE);
5369 	}
5370 
5371 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: entry\n");
5372 
5373 	mutex_enter(SD_MUTEX(un));
5374 
5375 	/* Return success if the device is already suspended. */
5376 	if (un->un_state == SD_STATE_SUSPENDED) {
5377 		mutex_exit(SD_MUTEX(un));
5378 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5379 		    "device already suspended, exiting\n");
5380 		return (DDI_SUCCESS);
5381 	}
5382 
5383 	/* Return failure if the device is being used by HA */
5384 	if (un->un_resvd_status &
5385 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE)) {
5386 		mutex_exit(SD_MUTEX(un));
5387 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5388 		    "device in use by HA, exiting\n");
5389 		return (DDI_FAILURE);
5390 	}
5391 
5392 	/*
5393 	 * Return failure if the device is in a resource wait
5394 	 * or power changing state.
5395 	 */
5396 	if ((un->un_state == SD_STATE_RWAIT) ||
5397 	    (un->un_state == SD_STATE_PM_CHANGING)) {
5398 		mutex_exit(SD_MUTEX(un));
5399 		SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: "
5400 		    "device in resource wait state, exiting\n");
5401 		return (DDI_FAILURE);
5402 	}
5403 
5404 
5405 	un->un_save_state = un->un_last_state;
5406 	New_state(un, SD_STATE_SUSPENDED);
5407 
5408 	/*
5409 	 * Wait for all commands that are in transport or queued to a timer
5410 	 * for retry to complete.
5411 	 *
5412 	 * While waiting, no new commands will be accepted or sent because of
5413 	 * the new state we set above.
5414 	 *
5415 	 * Wait till current operation has completed. If we are in the resource
5416 	 * wait state (with an intr outstanding) then we need to wait till the
5417 	 * intr completes and starts the next cmd. We want to wait for
5418 	 * SD_WAIT_CMDS_COMPLETE seconds before failing the DDI_SUSPEND.
5419 	 */
5420 	wait_cmds_complete = ddi_get_lbolt() +
5421 	    (sd_wait_cmds_complete * drv_usectohz(1000000));
5422 
5423 	while (un->un_ncmds_in_transport != 0) {
5424 		/*
5425 		 * Fail if commands do not finish in the specified time.
5426 		 */
5427 		if (cv_timedwait(&un->un_disk_busy_cv, SD_MUTEX(un),
5428 		    wait_cmds_complete) == -1) {
5429 			/*
5430 			 * Undo the state changes made above. Everything
5431 			 * must go back to it's original value.
5432 			 */
5433 			Restore_state(un);
5434 			un->un_last_state = un->un_save_state;
5435 			/* Wake up any threads that might be waiting. */
5436 			cv_broadcast(&un->un_suspend_cv);
5437 			mutex_exit(SD_MUTEX(un));
5438 			SD_ERROR(SD_LOG_IO_PM, un,
5439 			    "sd_ddi_suspend: failed due to outstanding cmds\n");
5440 			SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exiting\n");
5441 			return (DDI_FAILURE);
5442 		}
5443 	}
5444 
5445 	/*
5446 	 * Cancel SCSI watch thread and timeouts, if any are active
5447 	 */
5448 
5449 	if (SD_OK_TO_SUSPEND_SCSI_WATCHER(un)) {
5450 		opaque_t temp_token = un->un_swr_token;
5451 		mutex_exit(SD_MUTEX(un));
5452 		scsi_watch_suspend(temp_token);
5453 		mutex_enter(SD_MUTEX(un));
5454 	}
5455 
5456 	if (un->un_reset_throttle_timeid != NULL) {
5457 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
5458 		un->un_reset_throttle_timeid = NULL;
5459 		mutex_exit(SD_MUTEX(un));
5460 		(void) untimeout(temp_id);
5461 		mutex_enter(SD_MUTEX(un));
5462 	}
5463 
5464 	if (un->un_dcvb_timeid != NULL) {
5465 		timeout_id_t temp_id = un->un_dcvb_timeid;
5466 		un->un_dcvb_timeid = NULL;
5467 		mutex_exit(SD_MUTEX(un));
5468 		(void) untimeout(temp_id);
5469 		mutex_enter(SD_MUTEX(un));
5470 	}
5471 
5472 	mutex_enter(&un->un_pm_mutex);
5473 	if (un->un_pm_timeid != NULL) {
5474 		timeout_id_t temp_id = un->un_pm_timeid;
5475 		un->un_pm_timeid = NULL;
5476 		mutex_exit(&un->un_pm_mutex);
5477 		mutex_exit(SD_MUTEX(un));
5478 		(void) untimeout(temp_id);
5479 		mutex_enter(SD_MUTEX(un));
5480 	} else {
5481 		mutex_exit(&un->un_pm_mutex);
5482 	}
5483 
5484 	if (un->un_retry_timeid != NULL) {
5485 		timeout_id_t temp_id = un->un_retry_timeid;
5486 		un->un_retry_timeid = NULL;
5487 		mutex_exit(SD_MUTEX(un));
5488 		(void) untimeout(temp_id);
5489 		mutex_enter(SD_MUTEX(un));
5490 
5491 		if (un->un_retry_bp != NULL) {
5492 			un->un_retry_bp->av_forw = un->un_waitq_headp;
5493 			un->un_waitq_headp = un->un_retry_bp;
5494 			if (un->un_waitq_tailp == NULL) {
5495 				un->un_waitq_tailp = un->un_retry_bp;
5496 			}
5497 			un->un_retry_bp = NULL;
5498 			un->un_retry_statp = NULL;
5499 		}
5500 	}
5501 
5502 	if (un->un_direct_priority_timeid != NULL) {
5503 		timeout_id_t temp_id = un->un_direct_priority_timeid;
5504 		un->un_direct_priority_timeid = NULL;
5505 		mutex_exit(SD_MUTEX(un));
5506 		(void) untimeout(temp_id);
5507 		mutex_enter(SD_MUTEX(un));
5508 	}
5509 
5510 	if (un->un_f_is_fibre == TRUE) {
5511 		/*
5512 		 * Remove callbacks for insert and remove events
5513 		 */
5514 		if (un->un_insert_event != NULL) {
5515 			mutex_exit(SD_MUTEX(un));
5516 			(void) ddi_remove_event_handler(un->un_insert_cb_id);
5517 			mutex_enter(SD_MUTEX(un));
5518 			un->un_insert_event = NULL;
5519 		}
5520 
5521 		if (un->un_remove_event != NULL) {
5522 			mutex_exit(SD_MUTEX(un));
5523 			(void) ddi_remove_event_handler(un->un_remove_cb_id);
5524 			mutex_enter(SD_MUTEX(un));
5525 			un->un_remove_event = NULL;
5526 		}
5527 	}
5528 
5529 	mutex_exit(SD_MUTEX(un));
5530 
5531 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_suspend: exit\n");
5532 
5533 	return (DDI_SUCCESS);
5534 }
5535 
5536 
5537 /*
5538  *    Function: sd_ddi_pm_suspend
5539  *
5540  * Description: Set the drive state to low power.
5541  *		Someone else is required to actually change the drive
5542  *		power level.
5543  *
5544  *   Arguments: un - driver soft state (unit) structure
5545  *
5546  * Return Code: DDI_FAILURE or DDI_SUCCESS
5547  *
5548  *     Context: Kernel thread context
5549  */
5550 
5551 static int
5552 sd_ddi_pm_suspend(struct sd_lun *un)
5553 {
5554 	ASSERT(un != NULL);
5555 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: entry\n");
5556 
5557 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5558 	mutex_enter(SD_MUTEX(un));
5559 
5560 	/*
5561 	 * Exit if power management is not enabled for this device, or if
5562 	 * the device is being used by HA.
5563 	 */
5564 	if ((un->un_f_pm_is_enabled == FALSE) || (un->un_resvd_status &
5565 	    (SD_RESERVE | SD_WANT_RESERVE | SD_LOST_RESERVE))) {
5566 		mutex_exit(SD_MUTEX(un));
5567 		SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exiting\n");
5568 		return (DDI_SUCCESS);
5569 	}
5570 
5571 	SD_INFO(SD_LOG_POWER, un, "sd_ddi_pm_suspend: un_ncmds_in_driver=%ld\n",
5572 	    un->un_ncmds_in_driver);
5573 
5574 	/*
5575 	 * See if the device is not busy, ie.:
5576 	 *    - we have no commands in the driver for this device
5577 	 *    - not waiting for resources
5578 	 */
5579 	if ((un->un_ncmds_in_driver == 0) &&
5580 	    (un->un_state != SD_STATE_RWAIT)) {
5581 		/*
5582 		 * The device is not busy, so it is OK to go to low power state.
5583 		 * Indicate low power, but rely on someone else to actually
5584 		 * change it.
5585 		 */
5586 		mutex_enter(&un->un_pm_mutex);
5587 		un->un_pm_count = -1;
5588 		mutex_exit(&un->un_pm_mutex);
5589 		un->un_power_level = SD_SPINDLE_OFF;
5590 	}
5591 
5592 	mutex_exit(SD_MUTEX(un));
5593 
5594 	SD_TRACE(SD_LOG_POWER, un, "sd_ddi_pm_suspend: exit\n");
5595 
5596 	return (DDI_SUCCESS);
5597 }
5598 
5599 
5600 /*
5601  *    Function: sd_ddi_resume
5602  *
5603  * Description: Performs system power-up operations..
5604  *
5605  * Return Code: DDI_SUCCESS
5606  *		DDI_FAILURE
5607  *
5608  *     Context: Kernel thread context
5609  */
5610 
5611 static int
5612 sd_ddi_resume(dev_info_t *devi)
5613 {
5614 	struct	sd_lun	*un;
5615 
5616 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
5617 	if (un == NULL) {
5618 		return (DDI_FAILURE);
5619 	}
5620 
5621 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: entry\n");
5622 
5623 	mutex_enter(SD_MUTEX(un));
5624 	Restore_state(un);
5625 
5626 	/*
5627 	 * Restore the state which was saved to give the
5628 	 * the right state in un_last_state
5629 	 */
5630 	un->un_last_state = un->un_save_state;
5631 	/*
5632 	 * Note: throttle comes back at full.
5633 	 * Also note: this MUST be done before calling pm_raise_power
5634 	 * otherwise the system can get hung in biowait. The scenario where
5635 	 * this'll happen is under cpr suspend. Writing of the system
5636 	 * state goes through sddump, which writes 0 to un_throttle. If
5637 	 * writing the system state then fails, example if the partition is
5638 	 * too small, then cpr attempts a resume. If throttle isn't restored
5639 	 * from the saved value until after calling pm_raise_power then
5640 	 * cmds sent in sdpower are not transported and sd_send_scsi_cmd hangs
5641 	 * in biowait.
5642 	 */
5643 	un->un_throttle = un->un_saved_throttle;
5644 
5645 	/*
5646 	 * The chance of failure is very rare as the only command done in power
5647 	 * entry point is START command when you transition from 0->1 or
5648 	 * unknown->1. Put it to SPINDLE ON state irrespective of the state at
5649 	 * which suspend was done. Ignore the return value as the resume should
5650 	 * not be failed. In the case of removable media the media need not be
5651 	 * inserted and hence there is a chance that raise power will fail with
5652 	 * media not present.
5653 	 */
5654 	if (un->un_f_attach_spinup) {
5655 		mutex_exit(SD_MUTEX(un));
5656 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
5657 		mutex_enter(SD_MUTEX(un));
5658 	}
5659 
5660 	/*
5661 	 * Don't broadcast to the suspend cv and therefore possibly
5662 	 * start I/O until after power has been restored.
5663 	 */
5664 	cv_broadcast(&un->un_suspend_cv);
5665 	cv_broadcast(&un->un_state_cv);
5666 
5667 	/* restart thread */
5668 	if (SD_OK_TO_RESUME_SCSI_WATCHER(un)) {
5669 		scsi_watch_resume(un->un_swr_token);
5670 	}
5671 
5672 #if (defined(__fibre))
5673 	if (un->un_f_is_fibre == TRUE) {
5674 		/*
5675 		 * Add callbacks for insert and remove events
5676 		 */
5677 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
5678 			sd_init_event_callbacks(un);
5679 		}
5680 	}
5681 #endif
5682 
5683 	/*
5684 	 * Transport any pending commands to the target.
5685 	 *
5686 	 * If this is a low-activity device commands in queue will have to wait
5687 	 * until new commands come in, which may take awhile. Also, we
5688 	 * specifically don't check un_ncmds_in_transport because we know that
5689 	 * there really are no commands in progress after the unit was
5690 	 * suspended and we could have reached the throttle level, been
5691 	 * suspended, and have no new commands coming in for awhile. Highly
5692 	 * unlikely, but so is the low-activity disk scenario.
5693 	 */
5694 	ddi_xbuf_dispatch(un->un_xbuf_attr);
5695 
5696 	sd_start_cmds(un, NULL);
5697 	mutex_exit(SD_MUTEX(un));
5698 
5699 	SD_TRACE(SD_LOG_IO_PM, un, "sd_ddi_resume: exit\n");
5700 
5701 	return (DDI_SUCCESS);
5702 }
5703 
5704 
5705 /*
5706  *    Function: sd_ddi_pm_resume
5707  *
5708  * Description: Set the drive state to powered on.
5709  *		Someone else is required to actually change the drive
5710  *		power level.
5711  *
5712  *   Arguments: un - driver soft state (unit) structure
5713  *
5714  * Return Code: DDI_SUCCESS
5715  *
5716  *     Context: Kernel thread context
5717  */
5718 
5719 static int
5720 sd_ddi_pm_resume(struct sd_lun *un)
5721 {
5722 	ASSERT(un != NULL);
5723 
5724 	ASSERT(!mutex_owned(SD_MUTEX(un)));
5725 	mutex_enter(SD_MUTEX(un));
5726 	un->un_power_level = SD_SPINDLE_ON;
5727 
5728 	ASSERT(!mutex_owned(&un->un_pm_mutex));
5729 	mutex_enter(&un->un_pm_mutex);
5730 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
5731 		un->un_pm_count++;
5732 		ASSERT(un->un_pm_count == 0);
5733 		/*
5734 		 * Note: no longer do the cv_broadcast on un_suspend_cv. The
5735 		 * un_suspend_cv is for a system resume, not a power management
5736 		 * device resume. (4297749)
5737 		 *	 cv_broadcast(&un->un_suspend_cv);
5738 		 */
5739 	}
5740 	mutex_exit(&un->un_pm_mutex);
5741 	mutex_exit(SD_MUTEX(un));
5742 
5743 	return (DDI_SUCCESS);
5744 }
5745 
5746 
5747 /*
5748  *    Function: sd_pm_idletimeout_handler
5749  *
5750  * Description: A timer routine that's active only while a device is busy.
5751  *		The purpose is to extend slightly the pm framework's busy
5752  *		view of the device to prevent busy/idle thrashing for
5753  *		back-to-back commands. Do this by comparing the current time
5754  *		to the time at which the last command completed and when the
5755  *		difference is greater than sd_pm_idletime, call
5756  *		pm_idle_component. In addition to indicating idle to the pm
5757  *		framework, update the chain type to again use the internal pm
5758  *		layers of the driver.
5759  *
5760  *   Arguments: arg - driver soft state (unit) structure
5761  *
5762  *     Context: Executes in a timeout(9F) thread context
5763  */
5764 
5765 static void
5766 sd_pm_idletimeout_handler(void *arg)
5767 {
5768 	struct sd_lun *un = arg;
5769 
5770 	time_t	now;
5771 
5772 	mutex_enter(&sd_detach_mutex);
5773 	if (un->un_detach_count != 0) {
5774 		/* Abort if the instance is detaching */
5775 		mutex_exit(&sd_detach_mutex);
5776 		return;
5777 	}
5778 	mutex_exit(&sd_detach_mutex);
5779 
5780 	now = ddi_get_time();
5781 	/*
5782 	 * Grab both mutexes, in the proper order, since we're accessing
5783 	 * both PM and softstate variables.
5784 	 */
5785 	mutex_enter(SD_MUTEX(un));
5786 	mutex_enter(&un->un_pm_mutex);
5787 	if (((now - un->un_pm_idle_time) > sd_pm_idletime) &&
5788 	    (un->un_ncmds_in_driver == 0) && (un->un_pm_count == 0)) {
5789 		/*
5790 		 * Update the chain types.
5791 		 * This takes affect on the next new command received.
5792 		 */
5793 		if (un->un_f_non_devbsize_supported) {
5794 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
5795 		} else {
5796 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
5797 		}
5798 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
5799 
5800 		SD_TRACE(SD_LOG_IO_PM, un,
5801 		    "sd_pm_idletimeout_handler: idling device\n");
5802 		(void) pm_idle_component(SD_DEVINFO(un), 0);
5803 		un->un_pm_idle_timeid = NULL;
5804 	} else {
5805 		un->un_pm_idle_timeid =
5806 		    timeout(sd_pm_idletimeout_handler, un,
5807 		    (drv_usectohz((clock_t)300000))); /* 300 ms. */
5808 	}
5809 	mutex_exit(&un->un_pm_mutex);
5810 	mutex_exit(SD_MUTEX(un));
5811 }
5812 
5813 
5814 /*
5815  *    Function: sd_pm_timeout_handler
5816  *
5817  * Description: Callback to tell framework we are idle.
5818  *
5819  *     Context: timeout(9f) thread context.
5820  */
5821 
5822 static void
5823 sd_pm_timeout_handler(void *arg)
5824 {
5825 	struct sd_lun *un = arg;
5826 
5827 	(void) pm_idle_component(SD_DEVINFO(un), 0);
5828 	mutex_enter(&un->un_pm_mutex);
5829 	un->un_pm_timeid = NULL;
5830 	mutex_exit(&un->un_pm_mutex);
5831 }
5832 
5833 
5834 /*
5835  *    Function: sdpower
5836  *
5837  * Description: PM entry point.
5838  *
5839  * Return Code: DDI_SUCCESS
5840  *		DDI_FAILURE
5841  *
5842  *     Context: Kernel thread context
5843  */
5844 
5845 static int
5846 sdpower(dev_info_t *devi, int component, int level)
5847 {
5848 	struct sd_lun	*un;
5849 	int		instance;
5850 	int		rval = DDI_SUCCESS;
5851 	uint_t		i, log_page_size, maxcycles, ncycles;
5852 	uchar_t		*log_page_data;
5853 	int		log_sense_page;
5854 	int		medium_present;
5855 	time_t		intvlp;
5856 	dev_t		dev;
5857 	struct pm_trans_data	sd_pm_tran_data;
5858 	uchar_t		save_state;
5859 	int		sval;
5860 	uchar_t		state_before_pm;
5861 	int		got_semaphore_here;
5862 
5863 	instance = ddi_get_instance(devi);
5864 
5865 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
5866 	    (SD_SPINDLE_OFF > level) || (level > SD_SPINDLE_ON) ||
5867 	    component != 0) {
5868 		return (DDI_FAILURE);
5869 	}
5870 
5871 	dev = sd_make_device(SD_DEVINFO(un));
5872 
5873 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: entry, level = %d\n", level);
5874 
5875 	/*
5876 	 * Must synchronize power down with close.
5877 	 * Attempt to decrement/acquire the open/close semaphore,
5878 	 * but do NOT wait on it. If it's not greater than zero,
5879 	 * ie. it can't be decremented without waiting, then
5880 	 * someone else, either open or close, already has it
5881 	 * and the try returns 0. Use that knowledge here to determine
5882 	 * if it's OK to change the device power level.
5883 	 * Also, only increment it on exit if it was decremented, ie. gotten,
5884 	 * here.
5885 	 */
5886 	got_semaphore_here = sema_tryp(&un->un_semoclose);
5887 
5888 	mutex_enter(SD_MUTEX(un));
5889 
5890 	SD_INFO(SD_LOG_POWER, un, "sdpower: un_ncmds_in_driver = %ld\n",
5891 	    un->un_ncmds_in_driver);
5892 
5893 	/*
5894 	 * If un_ncmds_in_driver is non-zero it indicates commands are
5895 	 * already being processed in the driver, or if the semaphore was
5896 	 * not gotten here it indicates an open or close is being processed.
5897 	 * At the same time somebody is requesting to go low power which
5898 	 * can't happen, therefore we need to return failure.
5899 	 */
5900 	if ((level == SD_SPINDLE_OFF) &&
5901 	    ((un->un_ncmds_in_driver != 0) || (got_semaphore_here == 0))) {
5902 		mutex_exit(SD_MUTEX(un));
5903 
5904 		if (got_semaphore_here != 0) {
5905 			sema_v(&un->un_semoclose);
5906 		}
5907 		SD_TRACE(SD_LOG_IO_PM, un,
5908 		    "sdpower: exit, device has queued cmds.\n");
5909 		return (DDI_FAILURE);
5910 	}
5911 
5912 	/*
5913 	 * if it is OFFLINE that means the disk is completely dead
5914 	 * in our case we have to put the disk in on or off by sending commands
5915 	 * Of course that will fail anyway so return back here.
5916 	 *
5917 	 * Power changes to a device that's OFFLINE or SUSPENDED
5918 	 * are not allowed.
5919 	 */
5920 	if ((un->un_state == SD_STATE_OFFLINE) ||
5921 	    (un->un_state == SD_STATE_SUSPENDED)) {
5922 		mutex_exit(SD_MUTEX(un));
5923 
5924 		if (got_semaphore_here != 0) {
5925 			sema_v(&un->un_semoclose);
5926 		}
5927 		SD_TRACE(SD_LOG_IO_PM, un,
5928 		    "sdpower: exit, device is off-line.\n");
5929 		return (DDI_FAILURE);
5930 	}
5931 
5932 	/*
5933 	 * Change the device's state to indicate it's power level
5934 	 * is being changed. Do this to prevent a power off in the
5935 	 * middle of commands, which is especially bad on devices
5936 	 * that are really powered off instead of just spun down.
5937 	 */
5938 	state_before_pm = un->un_state;
5939 	un->un_state = SD_STATE_PM_CHANGING;
5940 
5941 	mutex_exit(SD_MUTEX(un));
5942 
5943 	/*
5944 	 * If "pm-capable" property is set to TRUE by HBA drivers,
5945 	 * bypass the following checking, otherwise, check the log
5946 	 * sense information for this device
5947 	 */
5948 	if ((level == SD_SPINDLE_OFF) && un->un_f_log_sense_supported) {
5949 		/*
5950 		 * Get the log sense information to understand whether the
5951 		 * the powercycle counts have gone beyond the threshhold.
5952 		 */
5953 		log_page_size = START_STOP_CYCLE_COUNTER_PAGE_SIZE;
5954 		log_page_data = kmem_zalloc(log_page_size, KM_SLEEP);
5955 
5956 		mutex_enter(SD_MUTEX(un));
5957 		log_sense_page = un->un_start_stop_cycle_page;
5958 		mutex_exit(SD_MUTEX(un));
5959 
5960 		rval = sd_send_scsi_LOG_SENSE(un, log_page_data,
5961 		    log_page_size, log_sense_page, 0x01, 0, SD_PATH_DIRECT);
5962 #ifdef	SDDEBUG
5963 		if (sd_force_pm_supported) {
5964 			/* Force a successful result */
5965 			rval = 0;
5966 		}
5967 #endif
5968 		if (rval != 0) {
5969 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
5970 			    "Log Sense Failed\n");
5971 			kmem_free(log_page_data, log_page_size);
5972 			/* Cannot support power management on those drives */
5973 
5974 			if (got_semaphore_here != 0) {
5975 				sema_v(&un->un_semoclose);
5976 			}
5977 			/*
5978 			 * On exit put the state back to it's original value
5979 			 * and broadcast to anyone waiting for the power
5980 			 * change completion.
5981 			 */
5982 			mutex_enter(SD_MUTEX(un));
5983 			un->un_state = state_before_pm;
5984 			cv_broadcast(&un->un_suspend_cv);
5985 			mutex_exit(SD_MUTEX(un));
5986 			SD_TRACE(SD_LOG_IO_PM, un,
5987 			    "sdpower: exit, Log Sense Failed.\n");
5988 			return (DDI_FAILURE);
5989 		}
5990 
5991 		/*
5992 		 * From the page data - Convert the essential information to
5993 		 * pm_trans_data
5994 		 */
5995 		maxcycles =
5996 		    (log_page_data[0x1c] << 24) | (log_page_data[0x1d] << 16) |
5997 		    (log_page_data[0x1E] << 8)  | log_page_data[0x1F];
5998 
5999 		sd_pm_tran_data.un.scsi_cycles.lifemax = maxcycles;
6000 
6001 		ncycles =
6002 		    (log_page_data[0x24] << 24) | (log_page_data[0x25] << 16) |
6003 		    (log_page_data[0x26] << 8)  | log_page_data[0x27];
6004 
6005 		sd_pm_tran_data.un.scsi_cycles.ncycles = ncycles;
6006 
6007 		for (i = 0; i < DC_SCSI_MFR_LEN; i++) {
6008 			sd_pm_tran_data.un.scsi_cycles.svc_date[i] =
6009 			    log_page_data[8+i];
6010 		}
6011 
6012 		kmem_free(log_page_data, log_page_size);
6013 
6014 		/*
6015 		 * Call pm_trans_check routine to get the Ok from
6016 		 * the global policy
6017 		 */
6018 
6019 		sd_pm_tran_data.format = DC_SCSI_FORMAT;
6020 		sd_pm_tran_data.un.scsi_cycles.flag = 0;
6021 
6022 		rval = pm_trans_check(&sd_pm_tran_data, &intvlp);
6023 #ifdef	SDDEBUG
6024 		if (sd_force_pm_supported) {
6025 			/* Force a successful result */
6026 			rval = 1;
6027 		}
6028 #endif
6029 		switch (rval) {
6030 		case 0:
6031 			/*
6032 			 * Not Ok to Power cycle or error in parameters passed
6033 			 * Would have given the advised time to consider power
6034 			 * cycle. Based on the new intvlp parameter we are
6035 			 * supposed to pretend we are busy so that pm framework
6036 			 * will never call our power entry point. Because of
6037 			 * that install a timeout handler and wait for the
6038 			 * recommended time to elapse so that power management
6039 			 * can be effective again.
6040 			 *
6041 			 * To effect this behavior, call pm_busy_component to
6042 			 * indicate to the framework this device is busy.
6043 			 * By not adjusting un_pm_count the rest of PM in
6044 			 * the driver will function normally, and independant
6045 			 * of this but because the framework is told the device
6046 			 * is busy it won't attempt powering down until it gets
6047 			 * a matching idle. The timeout handler sends this.
6048 			 * Note: sd_pm_entry can't be called here to do this
6049 			 * because sdpower may have been called as a result
6050 			 * of a call to pm_raise_power from within sd_pm_entry.
6051 			 *
6052 			 * If a timeout handler is already active then
6053 			 * don't install another.
6054 			 */
6055 			mutex_enter(&un->un_pm_mutex);
6056 			if (un->un_pm_timeid == NULL) {
6057 				un->un_pm_timeid =
6058 				    timeout(sd_pm_timeout_handler,
6059 				    un, intvlp * drv_usectohz(1000000));
6060 				mutex_exit(&un->un_pm_mutex);
6061 				(void) pm_busy_component(SD_DEVINFO(un), 0);
6062 			} else {
6063 				mutex_exit(&un->un_pm_mutex);
6064 			}
6065 			if (got_semaphore_here != 0) {
6066 				sema_v(&un->un_semoclose);
6067 			}
6068 			/*
6069 			 * On exit put the state back to it's original value
6070 			 * and broadcast to anyone waiting for the power
6071 			 * change completion.
6072 			 */
6073 			mutex_enter(SD_MUTEX(un));
6074 			un->un_state = state_before_pm;
6075 			cv_broadcast(&un->un_suspend_cv);
6076 			mutex_exit(SD_MUTEX(un));
6077 
6078 			SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, "
6079 			    "trans check Failed, not ok to power cycle.\n");
6080 			return (DDI_FAILURE);
6081 
6082 		case -1:
6083 			if (got_semaphore_here != 0) {
6084 				sema_v(&un->un_semoclose);
6085 			}
6086 			/*
6087 			 * On exit put the state back to it's original value
6088 			 * and broadcast to anyone waiting for the power
6089 			 * change completion.
6090 			 */
6091 			mutex_enter(SD_MUTEX(un));
6092 			un->un_state = state_before_pm;
6093 			cv_broadcast(&un->un_suspend_cv);
6094 			mutex_exit(SD_MUTEX(un));
6095 			SD_TRACE(SD_LOG_IO_PM, un,
6096 			    "sdpower: exit, trans check command Failed.\n");
6097 			return (DDI_FAILURE);
6098 		}
6099 	}
6100 
6101 	if (level == SD_SPINDLE_OFF) {
6102 		/*
6103 		 * Save the last state... if the STOP FAILS we need it
6104 		 * for restoring
6105 		 */
6106 		mutex_enter(SD_MUTEX(un));
6107 		save_state = un->un_last_state;
6108 		/*
6109 		 * There must not be any cmds. getting processed
6110 		 * in the driver when we get here. Power to the
6111 		 * device is potentially going off.
6112 		 */
6113 		ASSERT(un->un_ncmds_in_driver == 0);
6114 		mutex_exit(SD_MUTEX(un));
6115 
6116 		/*
6117 		 * For now suspend the device completely before spindle is
6118 		 * turned off
6119 		 */
6120 		if ((rval = sd_ddi_pm_suspend(un)) == DDI_FAILURE) {
6121 			if (got_semaphore_here != 0) {
6122 				sema_v(&un->un_semoclose);
6123 			}
6124 			/*
6125 			 * On exit put the state back to it's original value
6126 			 * and broadcast to anyone waiting for the power
6127 			 * change completion.
6128 			 */
6129 			mutex_enter(SD_MUTEX(un));
6130 			un->un_state = state_before_pm;
6131 			cv_broadcast(&un->un_suspend_cv);
6132 			mutex_exit(SD_MUTEX(un));
6133 			SD_TRACE(SD_LOG_IO_PM, un,
6134 			    "sdpower: exit, PM suspend Failed.\n");
6135 			return (DDI_FAILURE);
6136 		}
6137 	}
6138 
6139 	/*
6140 	 * The transition from SPINDLE_OFF to SPINDLE_ON can happen in open,
6141 	 * close, or strategy. Dump no long uses this routine, it uses it's
6142 	 * own code so it can be done in polled mode.
6143 	 */
6144 
6145 	medium_present = TRUE;
6146 
6147 	/*
6148 	 * When powering up, issue a TUR in case the device is at unit
6149 	 * attention.  Don't do retries. Bypass the PM layer, otherwise
6150 	 * a deadlock on un_pm_busy_cv will occur.
6151 	 */
6152 	if (level == SD_SPINDLE_ON) {
6153 		(void) sd_send_scsi_TEST_UNIT_READY(un,
6154 		    SD_DONT_RETRY_TUR | SD_BYPASS_PM);
6155 	}
6156 
6157 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: sending \'%s\' unit\n",
6158 	    ((level == SD_SPINDLE_ON) ? "START" : "STOP"));
6159 
6160 	sval = sd_send_scsi_START_STOP_UNIT(un,
6161 	    ((level == SD_SPINDLE_ON) ? SD_TARGET_START : SD_TARGET_STOP),
6162 	    SD_PATH_DIRECT);
6163 	/* Command failed, check for media present. */
6164 	if ((sval == ENXIO) && un->un_f_has_removable_media) {
6165 		medium_present = FALSE;
6166 	}
6167 
6168 	/*
6169 	 * The conditions of interest here are:
6170 	 *   if a spindle off with media present fails,
6171 	 *	then restore the state and return an error.
6172 	 *   else if a spindle on fails,
6173 	 *	then return an error (there's no state to restore).
6174 	 * In all other cases we setup for the new state
6175 	 * and return success.
6176 	 */
6177 	switch (level) {
6178 	case SD_SPINDLE_OFF:
6179 		if ((medium_present == TRUE) && (sval != 0)) {
6180 			/* The stop command from above failed */
6181 			rval = DDI_FAILURE;
6182 			/*
6183 			 * The stop command failed, and we have media
6184 			 * present. Put the level back by calling the
6185 			 * sd_pm_resume() and set the state back to
6186 			 * it's previous value.
6187 			 */
6188 			(void) sd_ddi_pm_resume(un);
6189 			mutex_enter(SD_MUTEX(un));
6190 			un->un_last_state = save_state;
6191 			mutex_exit(SD_MUTEX(un));
6192 			break;
6193 		}
6194 		/*
6195 		 * The stop command from above succeeded.
6196 		 */
6197 		if (un->un_f_monitor_media_state) {
6198 			/*
6199 			 * Terminate watch thread in case of removable media
6200 			 * devices going into low power state. This is as per
6201 			 * the requirements of pm framework, otherwise commands
6202 			 * will be generated for the device (through watch
6203 			 * thread), even when the device is in low power state.
6204 			 */
6205 			mutex_enter(SD_MUTEX(un));
6206 			un->un_f_watcht_stopped = FALSE;
6207 			if (un->un_swr_token != NULL) {
6208 				opaque_t temp_token = un->un_swr_token;
6209 				un->un_f_watcht_stopped = TRUE;
6210 				un->un_swr_token = NULL;
6211 				mutex_exit(SD_MUTEX(un));
6212 				(void) scsi_watch_request_terminate(temp_token,
6213 				    SCSI_WATCH_TERMINATE_WAIT);
6214 			} else {
6215 				mutex_exit(SD_MUTEX(un));
6216 			}
6217 		}
6218 		break;
6219 
6220 	default:	/* The level requested is spindle on... */
6221 		/*
6222 		 * Legacy behavior: return success on a failed spinup
6223 		 * if there is no media in the drive.
6224 		 * Do this by looking at medium_present here.
6225 		 */
6226 		if ((sval != 0) && medium_present) {
6227 			/* The start command from above failed */
6228 			rval = DDI_FAILURE;
6229 			break;
6230 		}
6231 		/*
6232 		 * The start command from above succeeded
6233 		 * Resume the devices now that we have
6234 		 * started the disks
6235 		 */
6236 		(void) sd_ddi_pm_resume(un);
6237 
6238 		/*
6239 		 * Resume the watch thread since it was suspended
6240 		 * when the device went into low power mode.
6241 		 */
6242 		if (un->un_f_monitor_media_state) {
6243 			mutex_enter(SD_MUTEX(un));
6244 			if (un->un_f_watcht_stopped == TRUE) {
6245 				opaque_t temp_token;
6246 
6247 				un->un_f_watcht_stopped = FALSE;
6248 				mutex_exit(SD_MUTEX(un));
6249 				temp_token = scsi_watch_request_submit(
6250 				    SD_SCSI_DEVP(un),
6251 				    sd_check_media_time,
6252 				    SENSE_LENGTH, sd_media_watch_cb,
6253 				    (caddr_t)dev);
6254 				mutex_enter(SD_MUTEX(un));
6255 				un->un_swr_token = temp_token;
6256 			}
6257 			mutex_exit(SD_MUTEX(un));
6258 		}
6259 	}
6260 	if (got_semaphore_here != 0) {
6261 		sema_v(&un->un_semoclose);
6262 	}
6263 	/*
6264 	 * On exit put the state back to it's original value
6265 	 * and broadcast to anyone waiting for the power
6266 	 * change completion.
6267 	 */
6268 	mutex_enter(SD_MUTEX(un));
6269 	un->un_state = state_before_pm;
6270 	cv_broadcast(&un->un_suspend_cv);
6271 	mutex_exit(SD_MUTEX(un));
6272 
6273 	SD_TRACE(SD_LOG_IO_PM, un, "sdpower: exit, status = 0x%x\n", rval);
6274 
6275 	return (rval);
6276 }
6277 
6278 
6279 
6280 /*
6281  *    Function: sdattach
6282  *
6283  * Description: Driver's attach(9e) entry point function.
6284  *
6285  *   Arguments: devi - opaque device info handle
6286  *		cmd  - attach  type
6287  *
6288  * Return Code: DDI_SUCCESS
6289  *		DDI_FAILURE
6290  *
6291  *     Context: Kernel thread context
6292  */
6293 
6294 static int
6295 sdattach(dev_info_t *devi, ddi_attach_cmd_t cmd)
6296 {
6297 	switch (cmd) {
6298 	case DDI_ATTACH:
6299 		return (sd_unit_attach(devi));
6300 	case DDI_RESUME:
6301 		return (sd_ddi_resume(devi));
6302 	default:
6303 		break;
6304 	}
6305 	return (DDI_FAILURE);
6306 }
6307 
6308 
6309 /*
6310  *    Function: sddetach
6311  *
6312  * Description: Driver's detach(9E) entry point function.
6313  *
6314  *   Arguments: devi - opaque device info handle
6315  *		cmd  - detach  type
6316  *
6317  * Return Code: DDI_SUCCESS
6318  *		DDI_FAILURE
6319  *
6320  *     Context: Kernel thread context
6321  */
6322 
6323 static int
6324 sddetach(dev_info_t *devi, ddi_detach_cmd_t cmd)
6325 {
6326 	switch (cmd) {
6327 	case DDI_DETACH:
6328 		return (sd_unit_detach(devi));
6329 	case DDI_SUSPEND:
6330 		return (sd_ddi_suspend(devi));
6331 	default:
6332 		break;
6333 	}
6334 	return (DDI_FAILURE);
6335 }
6336 
6337 
6338 /*
6339  *     Function: sd_sync_with_callback
6340  *
6341  *  Description: Prevents sd_unit_attach or sd_unit_detach from freeing the soft
6342  *		 state while the callback routine is active.
6343  *
6344  *    Arguments: un: softstate structure for the instance
6345  *
6346  *	Context: Kernel thread context
6347  */
6348 
6349 static void
6350 sd_sync_with_callback(struct sd_lun *un)
6351 {
6352 	ASSERT(un != NULL);
6353 
6354 	mutex_enter(SD_MUTEX(un));
6355 
6356 	ASSERT(un->un_in_callback >= 0);
6357 
6358 	while (un->un_in_callback > 0) {
6359 		mutex_exit(SD_MUTEX(un));
6360 		delay(2);
6361 		mutex_enter(SD_MUTEX(un));
6362 	}
6363 
6364 	mutex_exit(SD_MUTEX(un));
6365 }
6366 
6367 /*
6368  *    Function: sd_unit_attach
6369  *
6370  * Description: Performs DDI_ATTACH processing for sdattach(). Allocates
6371  *		the soft state structure for the device and performs
6372  *		all necessary structure and device initializations.
6373  *
6374  *   Arguments: devi: the system's dev_info_t for the device.
6375  *
6376  * Return Code: DDI_SUCCESS if attach is successful.
6377  *		DDI_FAILURE if any part of the attach fails.
6378  *
6379  *     Context: Called at attach(9e) time for the DDI_ATTACH flag.
6380  *		Kernel thread context only.  Can sleep.
6381  */
6382 
6383 static int
6384 sd_unit_attach(dev_info_t *devi)
6385 {
6386 	struct	scsi_device	*devp;
6387 	struct	sd_lun		*un;
6388 	char			*variantp;
6389 	int	reservation_flag = SD_TARGET_IS_UNRESERVED;
6390 	int	instance;
6391 	int	rval;
6392 	int	wc_enabled;
6393 	int	tgt;
6394 	uint64_t	capacity;
6395 	uint_t		lbasize = 0;
6396 	dev_info_t	*pdip = ddi_get_parent(devi);
6397 	int		offbyone = 0;
6398 	int		geom_label_valid = 0;
6399 #if defined(__sparc)
6400 	int		max_xfer_size;
6401 #endif
6402 
6403 	/*
6404 	 * Retrieve the target driver's private data area. This was set
6405 	 * up by the HBA.
6406 	 */
6407 	devp = ddi_get_driver_private(devi);
6408 
6409 	/*
6410 	 * Retrieve the target ID of the device.
6411 	 */
6412 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
6413 	    SCSI_ADDR_PROP_TARGET, -1);
6414 
6415 	/*
6416 	 * Since we have no idea what state things were left in by the last
6417 	 * user of the device, set up some 'default' settings, ie. turn 'em
6418 	 * off. The scsi_ifsetcap calls force re-negotiations with the drive.
6419 	 * Do this before the scsi_probe, which sends an inquiry.
6420 	 * This is a fix for bug (4430280).
6421 	 * Of special importance is wide-xfer. The drive could have been left
6422 	 * in wide transfer mode by the last driver to communicate with it,
6423 	 * this includes us. If that's the case, and if the following is not
6424 	 * setup properly or we don't re-negotiate with the drive prior to
6425 	 * transferring data to/from the drive, it causes bus parity errors,
6426 	 * data overruns, and unexpected interrupts. This first occurred when
6427 	 * the fix for bug (4378686) was made.
6428 	 */
6429 	(void) scsi_ifsetcap(&devp->sd_address, "lun-reset", 0, 1);
6430 	(void) scsi_ifsetcap(&devp->sd_address, "wide-xfer", 0, 1);
6431 	(void) scsi_ifsetcap(&devp->sd_address, "auto-rqsense", 0, 1);
6432 
6433 	/*
6434 	 * Currently, scsi_ifsetcap sets tagged-qing capability for all LUNs
6435 	 * on a target. Setting it per lun instance actually sets the
6436 	 * capability of this target, which affects those luns already
6437 	 * attached on the same target. So during attach, we can only disable
6438 	 * this capability only when no other lun has been attached on this
6439 	 * target. By doing this, we assume a target has the same tagged-qing
6440 	 * capability for every lun. The condition can be removed when HBA
6441 	 * is changed to support per lun based tagged-qing capability.
6442 	 */
6443 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
6444 		(void) scsi_ifsetcap(&devp->sd_address, "tagged-qing", 0, 1);
6445 	}
6446 
6447 	/*
6448 	 * Use scsi_probe() to issue an INQUIRY command to the device.
6449 	 * This call will allocate and fill in the scsi_inquiry structure
6450 	 * and point the sd_inq member of the scsi_device structure to it.
6451 	 * If the attach succeeds, then this memory will not be de-allocated
6452 	 * (via scsi_unprobe()) until the instance is detached.
6453 	 */
6454 	if (scsi_probe(devp, SLEEP_FUNC) != SCSIPROBE_EXISTS) {
6455 		goto probe_failed;
6456 	}
6457 
6458 	/*
6459 	 * Check the device type as specified in the inquiry data and
6460 	 * claim it if it is of a type that we support.
6461 	 */
6462 	switch (devp->sd_inq->inq_dtype) {
6463 	case DTYPE_DIRECT:
6464 		break;
6465 	case DTYPE_RODIRECT:
6466 		break;
6467 	case DTYPE_OPTICAL:
6468 		break;
6469 	case DTYPE_NOTPRESENT:
6470 	default:
6471 		/* Unsupported device type; fail the attach. */
6472 		goto probe_failed;
6473 	}
6474 
6475 	/*
6476 	 * Allocate the soft state structure for this unit.
6477 	 *
6478 	 * We rely upon this memory being set to all zeroes by
6479 	 * ddi_soft_state_zalloc().  We assume that any member of the
6480 	 * soft state structure that is not explicitly initialized by
6481 	 * this routine will have a value of zero.
6482 	 */
6483 	instance = ddi_get_instance(devp->sd_dev);
6484 	if (ddi_soft_state_zalloc(sd_state, instance) != DDI_SUCCESS) {
6485 		goto probe_failed;
6486 	}
6487 
6488 	/*
6489 	 * Retrieve a pointer to the newly-allocated soft state.
6490 	 *
6491 	 * This should NEVER fail if the ddi_soft_state_zalloc() call above
6492 	 * was successful, unless something has gone horribly wrong and the
6493 	 * ddi's soft state internals are corrupt (in which case it is
6494 	 * probably better to halt here than just fail the attach....)
6495 	 */
6496 	if ((un = ddi_get_soft_state(sd_state, instance)) == NULL) {
6497 		panic("sd_unit_attach: NULL soft state on instance:0x%x",
6498 		    instance);
6499 		/*NOTREACHED*/
6500 	}
6501 
6502 	/*
6503 	 * Link the back ptr of the driver soft state to the scsi_device
6504 	 * struct for this lun.
6505 	 * Save a pointer to the softstate in the driver-private area of
6506 	 * the scsi_device struct.
6507 	 * Note: We cannot call SD_INFO, SD_TRACE, SD_ERROR, or SD_DIAG until
6508 	 * we first set un->un_sd below.
6509 	 */
6510 	un->un_sd = devp;
6511 	devp->sd_private = (opaque_t)un;
6512 
6513 	/*
6514 	 * The following must be after devp is stored in the soft state struct.
6515 	 */
6516 #ifdef SDDEBUG
6517 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6518 	    "%s_unit_attach: un:0x%p instance:%d\n",
6519 	    ddi_driver_name(devi), un, instance);
6520 #endif
6521 
6522 	/*
6523 	 * Set up the device type and node type (for the minor nodes).
6524 	 * By default we assume that the device can at least support the
6525 	 * Common Command Set. Call it a CD-ROM if it reports itself
6526 	 * as a RODIRECT device.
6527 	 */
6528 	switch (devp->sd_inq->inq_dtype) {
6529 	case DTYPE_RODIRECT:
6530 		un->un_node_type = DDI_NT_CD_CHAN;
6531 		un->un_ctype	 = CTYPE_CDROM;
6532 		break;
6533 	case DTYPE_OPTICAL:
6534 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6535 		un->un_ctype	 = CTYPE_ROD;
6536 		break;
6537 	default:
6538 		un->un_node_type = DDI_NT_BLOCK_CHAN;
6539 		un->un_ctype	 = CTYPE_CCS;
6540 		break;
6541 	}
6542 
6543 	/*
6544 	 * Try to read the interconnect type from the HBA.
6545 	 *
6546 	 * Note: This driver is currently compiled as two binaries, a parallel
6547 	 * scsi version (sd) and a fibre channel version (ssd). All functional
6548 	 * differences are determined at compile time. In the future a single
6549 	 * binary will be provided and the inteconnect type will be used to
6550 	 * differentiate between fibre and parallel scsi behaviors. At that time
6551 	 * it will be necessary for all fibre channel HBAs to support this
6552 	 * property.
6553 	 *
6554 	 * set un_f_is_fiber to TRUE ( default fiber )
6555 	 */
6556 	un->un_f_is_fibre = TRUE;
6557 	switch (scsi_ifgetcap(SD_ADDRESS(un), "interconnect-type", -1)) {
6558 	case INTERCONNECT_SSA:
6559 		un->un_interconnect_type = SD_INTERCONNECT_SSA;
6560 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6561 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SSA\n", un);
6562 		break;
6563 	case INTERCONNECT_PARALLEL:
6564 		un->un_f_is_fibre = FALSE;
6565 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
6566 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6567 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_PARALLEL\n", un);
6568 		break;
6569 	case INTERCONNECT_SATA:
6570 		un->un_f_is_fibre = FALSE;
6571 		un->un_interconnect_type = SD_INTERCONNECT_SATA;
6572 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6573 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_SATA\n", un);
6574 		break;
6575 	case INTERCONNECT_FIBRE:
6576 		un->un_interconnect_type = SD_INTERCONNECT_FIBRE;
6577 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6578 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FIBRE\n", un);
6579 		break;
6580 	case INTERCONNECT_FABRIC:
6581 		un->un_interconnect_type = SD_INTERCONNECT_FABRIC;
6582 		un->un_node_type = DDI_NT_BLOCK_FABRIC;
6583 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6584 		    "sd_unit_attach: un:0x%p SD_INTERCONNECT_FABRIC\n", un);
6585 		break;
6586 	default:
6587 #ifdef SD_DEFAULT_INTERCONNECT_TYPE
6588 		/*
6589 		 * The HBA does not support the "interconnect-type" property
6590 		 * (or did not provide a recognized type).
6591 		 *
6592 		 * Note: This will be obsoleted when a single fibre channel
6593 		 * and parallel scsi driver is delivered. In the meantime the
6594 		 * interconnect type will be set to the platform default.If that
6595 		 * type is not parallel SCSI, it means that we should be
6596 		 * assuming "ssd" semantics. However, here this also means that
6597 		 * the FC HBA is not supporting the "interconnect-type" property
6598 		 * like we expect it to, so log this occurrence.
6599 		 */
6600 		un->un_interconnect_type = SD_DEFAULT_INTERCONNECT_TYPE;
6601 		if (!SD_IS_PARALLEL_SCSI(un)) {
6602 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6603 			    "sd_unit_attach: un:0x%p Assuming "
6604 			    "INTERCONNECT_FIBRE\n", un);
6605 		} else {
6606 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6607 			    "sd_unit_attach: un:0x%p Assuming "
6608 			    "INTERCONNECT_PARALLEL\n", un);
6609 			un->un_f_is_fibre = FALSE;
6610 		}
6611 #else
6612 		/*
6613 		 * Note: This source will be implemented when a single fibre
6614 		 * channel and parallel scsi driver is delivered. The default
6615 		 * will be to assume that if a device does not support the
6616 		 * "interconnect-type" property it is a parallel SCSI HBA and
6617 		 * we will set the interconnect type for parallel scsi.
6618 		 */
6619 		un->un_interconnect_type = SD_INTERCONNECT_PARALLEL;
6620 		un->un_f_is_fibre = FALSE;
6621 #endif
6622 		break;
6623 	}
6624 
6625 	if (un->un_f_is_fibre == TRUE) {
6626 		if (scsi_ifgetcap(SD_ADDRESS(un), "scsi-version", 1) ==
6627 		    SCSI_VERSION_3) {
6628 			switch (un->un_interconnect_type) {
6629 			case SD_INTERCONNECT_FIBRE:
6630 			case SD_INTERCONNECT_SSA:
6631 				un->un_node_type = DDI_NT_BLOCK_WWN;
6632 				break;
6633 			default:
6634 				break;
6635 			}
6636 		}
6637 	}
6638 
6639 	/*
6640 	 * Initialize the Request Sense command for the target
6641 	 */
6642 	if (sd_alloc_rqs(devp, un) != DDI_SUCCESS) {
6643 		goto alloc_rqs_failed;
6644 	}
6645 
6646 	/*
6647 	 * Set un_retry_count with SD_RETRY_COUNT, this is ok for Sparc
6648 	 * with separate binary for sd and ssd.
6649 	 *
6650 	 * x86 has 1 binary, un_retry_count is set base on connection type.
6651 	 * The hardcoded values will go away when Sparc uses 1 binary
6652 	 * for sd and ssd.  This hardcoded values need to match
6653 	 * SD_RETRY_COUNT in sddef.h
6654 	 * The value used is base on interconnect type.
6655 	 * fibre = 3, parallel = 5
6656 	 */
6657 #if defined(__i386) || defined(__amd64)
6658 	un->un_retry_count = un->un_f_is_fibre ? 3 : 5;
6659 #else
6660 	un->un_retry_count = SD_RETRY_COUNT;
6661 #endif
6662 
6663 	/*
6664 	 * Set the per disk retry count to the default number of retries
6665 	 * for disks and CDROMs. This value can be overridden by the
6666 	 * disk property list or an entry in sd.conf.
6667 	 */
6668 	un->un_notready_retry_count =
6669 	    ISCD(un) ? CD_NOT_READY_RETRY_COUNT(un)
6670 	    : DISK_NOT_READY_RETRY_COUNT(un);
6671 
6672 	/*
6673 	 * Set the busy retry count to the default value of un_retry_count.
6674 	 * This can be overridden by entries in sd.conf or the device
6675 	 * config table.
6676 	 */
6677 	un->un_busy_retry_count = un->un_retry_count;
6678 
6679 	/*
6680 	 * Init the reset threshold for retries.  This number determines
6681 	 * how many retries must be performed before a reset can be issued
6682 	 * (for certain error conditions). This can be overridden by entries
6683 	 * in sd.conf or the device config table.
6684 	 */
6685 	un->un_reset_retry_count = (un->un_retry_count / 2);
6686 
6687 	/*
6688 	 * Set the victim_retry_count to the default un_retry_count
6689 	 */
6690 	un->un_victim_retry_count = (2 * un->un_retry_count);
6691 
6692 	/*
6693 	 * Set the reservation release timeout to the default value of
6694 	 * 5 seconds. This can be overridden by entries in ssd.conf or the
6695 	 * device config table.
6696 	 */
6697 	un->un_reserve_release_time = 5;
6698 
6699 	/*
6700 	 * Set up the default maximum transfer size. Note that this may
6701 	 * get updated later in the attach, when setting up default wide
6702 	 * operations for disks.
6703 	 */
6704 #if defined(__i386) || defined(__amd64)
6705 	un->un_max_xfer_size = (uint_t)SD_DEFAULT_MAX_XFER_SIZE;
6706 	un->un_partial_dma_supported = 1;
6707 #else
6708 	un->un_max_xfer_size = (uint_t)maxphys;
6709 #endif
6710 
6711 	/*
6712 	 * Get "allow bus device reset" property (defaults to "enabled" if
6713 	 * the property was not defined). This is to disable bus resets for
6714 	 * certain kinds of error recovery. Note: In the future when a run-time
6715 	 * fibre check is available the soft state flag should default to
6716 	 * enabled.
6717 	 */
6718 	if (un->un_f_is_fibre == TRUE) {
6719 		un->un_f_allow_bus_device_reset = TRUE;
6720 	} else {
6721 		if (ddi_getprop(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
6722 		    "allow-bus-device-reset", 1) != 0) {
6723 			un->un_f_allow_bus_device_reset = TRUE;
6724 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6725 			    "sd_unit_attach: un:0x%p Bus device reset "
6726 			    "enabled\n", un);
6727 		} else {
6728 			un->un_f_allow_bus_device_reset = FALSE;
6729 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6730 			    "sd_unit_attach: un:0x%p Bus device reset "
6731 			    "disabled\n", un);
6732 		}
6733 	}
6734 
6735 	/*
6736 	 * Check if this is an ATAPI device. ATAPI devices use Group 1
6737 	 * Read/Write commands and Group 2 Mode Sense/Select commands.
6738 	 *
6739 	 * Note: The "obsolete" way of doing this is to check for the "atapi"
6740 	 * property. The new "variant" property with a value of "atapi" has been
6741 	 * introduced so that future 'variants' of standard SCSI behavior (like
6742 	 * atapi) could be specified by the underlying HBA drivers by supplying
6743 	 * a new value for the "variant" property, instead of having to define a
6744 	 * new property.
6745 	 */
6746 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "atapi", -1) != -1) {
6747 		un->un_f_cfg_is_atapi = TRUE;
6748 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
6749 		    "sd_unit_attach: un:0x%p Atapi device\n", un);
6750 	}
6751 	if (ddi_prop_lookup_string(DDI_DEV_T_ANY, devi, 0, "variant",
6752 	    &variantp) == DDI_PROP_SUCCESS) {
6753 		if (strcmp(variantp, "atapi") == 0) {
6754 			un->un_f_cfg_is_atapi = TRUE;
6755 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6756 			    "sd_unit_attach: un:0x%p Atapi device\n", un);
6757 		}
6758 		ddi_prop_free(variantp);
6759 	}
6760 
6761 	un->un_cmd_timeout	= SD_IO_TIME;
6762 
6763 	/* Info on current states, statuses, etc. (Updated frequently) */
6764 	un->un_state		= SD_STATE_NORMAL;
6765 	un->un_last_state	= SD_STATE_NORMAL;
6766 
6767 	/* Control & status info for command throttling */
6768 	un->un_throttle		= sd_max_throttle;
6769 	un->un_saved_throttle	= sd_max_throttle;
6770 	un->un_min_throttle	= sd_min_throttle;
6771 
6772 	if (un->un_f_is_fibre == TRUE) {
6773 		un->un_f_use_adaptive_throttle = TRUE;
6774 	} else {
6775 		un->un_f_use_adaptive_throttle = FALSE;
6776 	}
6777 
6778 	/* Removable media support. */
6779 	cv_init(&un->un_state_cv, NULL, CV_DRIVER, NULL);
6780 	un->un_mediastate		= DKIO_NONE;
6781 	un->un_specified_mediastate	= DKIO_NONE;
6782 
6783 	/* CVs for suspend/resume (PM or DR) */
6784 	cv_init(&un->un_suspend_cv,   NULL, CV_DRIVER, NULL);
6785 	cv_init(&un->un_disk_busy_cv, NULL, CV_DRIVER, NULL);
6786 
6787 	/* Power management support. */
6788 	un->un_power_level = SD_SPINDLE_UNINIT;
6789 
6790 	cv_init(&un->un_wcc_cv,   NULL, CV_DRIVER, NULL);
6791 	un->un_f_wcc_inprog = 0;
6792 
6793 	/*
6794 	 * The open/close semaphore is used to serialize threads executing
6795 	 * in the driver's open & close entry point routines for a given
6796 	 * instance.
6797 	 */
6798 	(void) sema_init(&un->un_semoclose, 1, NULL, SEMA_DRIVER, NULL);
6799 
6800 	/*
6801 	 * The conf file entry and softstate variable is a forceful override,
6802 	 * meaning a non-zero value must be entered to change the default.
6803 	 */
6804 	un->un_f_disksort_disabled = FALSE;
6805 
6806 	/*
6807 	 * Retrieve the properties from the static driver table or the driver
6808 	 * configuration file (.conf) for this unit and update the soft state
6809 	 * for the device as needed for the indicated properties.
6810 	 * Note: the property configuration needs to occur here as some of the
6811 	 * following routines may have dependancies on soft state flags set
6812 	 * as part of the driver property configuration.
6813 	 */
6814 	sd_read_unit_properties(un);
6815 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6816 	    "sd_unit_attach: un:0x%p property configuration complete.\n", un);
6817 
6818 	/*
6819 	 * Only if a device has "hotpluggable" property, it is
6820 	 * treated as hotpluggable device. Otherwise, it is
6821 	 * regarded as non-hotpluggable one.
6822 	 */
6823 	if (ddi_prop_get_int(DDI_DEV_T_ANY, devi, 0, "hotpluggable",
6824 	    -1) != -1) {
6825 		un->un_f_is_hotpluggable = TRUE;
6826 	}
6827 
6828 	/*
6829 	 * set unit's attributes(flags) according to "hotpluggable" and
6830 	 * RMB bit in INQUIRY data.
6831 	 */
6832 	sd_set_unit_attributes(un, devi);
6833 
6834 	/*
6835 	 * By default, we mark the capacity, lbasize, and geometry
6836 	 * as invalid. Only if we successfully read a valid capacity
6837 	 * will we update the un_blockcount and un_tgt_blocksize with the
6838 	 * valid values (the geometry will be validated later).
6839 	 */
6840 	un->un_f_blockcount_is_valid	= FALSE;
6841 	un->un_f_tgt_blocksize_is_valid	= FALSE;
6842 
6843 	/*
6844 	 * Use DEV_BSIZE and DEV_BSHIFT as defaults, until we can determine
6845 	 * otherwise.
6846 	 */
6847 	un->un_tgt_blocksize  = un->un_sys_blocksize  = DEV_BSIZE;
6848 	un->un_blockcount = 0;
6849 
6850 	/*
6851 	 * Set up the per-instance info needed to determine the correct
6852 	 * CDBs and other info for issuing commands to the target.
6853 	 */
6854 	sd_init_cdb_limits(un);
6855 
6856 	/*
6857 	 * Set up the IO chains to use, based upon the target type.
6858 	 */
6859 	if (un->un_f_non_devbsize_supported) {
6860 		un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA;
6861 	} else {
6862 		un->un_buf_chain_type = SD_CHAIN_INFO_DISK;
6863 	}
6864 	un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD;
6865 	un->un_direct_chain_type = SD_CHAIN_INFO_DIRECT_CMD;
6866 	un->un_priority_chain_type = SD_CHAIN_INFO_PRIORITY_CMD;
6867 
6868 	un->un_xbuf_attr = ddi_xbuf_attr_create(sizeof (struct sd_xbuf),
6869 	    sd_xbuf_strategy, un, sd_xbuf_active_limit,  sd_xbuf_reserve_limit,
6870 	    ddi_driver_major(devi), DDI_XBUF_QTHREAD_DRIVER);
6871 	ddi_xbuf_attr_register_devinfo(un->un_xbuf_attr, devi);
6872 
6873 
6874 	if (ISCD(un)) {
6875 		un->un_additional_codes = sd_additional_codes;
6876 	} else {
6877 		un->un_additional_codes = NULL;
6878 	}
6879 
6880 	/*
6881 	 * Create the kstats here so they can be available for attach-time
6882 	 * routines that send commands to the unit (either polled or via
6883 	 * sd_send_scsi_cmd).
6884 	 *
6885 	 * Note: This is a critical sequence that needs to be maintained:
6886 	 *	1) Instantiate the kstats here, before any routines using the
6887 	 *	   iopath (i.e. sd_send_scsi_cmd).
6888 	 *	2) Instantiate and initialize the partition stats
6889 	 *	   (sd_set_pstats).
6890 	 *	3) Initialize the error stats (sd_set_errstats), following
6891 	 *	   sd_validate_geometry(),sd_register_devid(),
6892 	 *	   and sd_cache_control().
6893 	 */
6894 
6895 	un->un_stats = kstat_create(sd_label, instance,
6896 	    NULL, "disk", KSTAT_TYPE_IO, 1, KSTAT_FLAG_PERSISTENT);
6897 	if (un->un_stats != NULL) {
6898 		un->un_stats->ks_lock = SD_MUTEX(un);
6899 		kstat_install(un->un_stats);
6900 	}
6901 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6902 	    "sd_unit_attach: un:0x%p un_stats created\n", un);
6903 
6904 	sd_create_errstats(un, instance);
6905 	if (un->un_errstats == NULL) {
6906 		goto create_errstats_failed;
6907 	}
6908 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
6909 	    "sd_unit_attach: un:0x%p errstats created\n", un);
6910 
6911 	/*
6912 	 * The following if/else code was relocated here from below as part
6913 	 * of the fix for bug (4430280). However with the default setup added
6914 	 * on entry to this routine, it's no longer absolutely necessary for
6915 	 * this to be before the call to sd_spin_up_unit.
6916 	 */
6917 	if (SD_IS_PARALLEL_SCSI(un) || SD_IS_SERIAL(un)) {
6918 		int tq_trigger_flag = (((devp->sd_inq->inq_ansi == 4) ||
6919 		    (devp->sd_inq->inq_ansi == 5)) &&
6920 		    devp->sd_inq->inq_bque) || devp->sd_inq->inq_cmdque;
6921 
6922 		/*
6923 		 * If tagged queueing is supported by the target
6924 		 * and by the host adapter then we will enable it
6925 		 */
6926 		un->un_tagflags = 0;
6927 		if ((devp->sd_inq->inq_rdf == RDF_SCSI2) && tq_trigger_flag &&
6928 		    (un->un_f_arq_enabled == TRUE)) {
6929 			if (scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing",
6930 			    1, 1) == 1) {
6931 				un->un_tagflags = FLAG_STAG;
6932 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6933 				    "sd_unit_attach: un:0x%p tag queueing "
6934 				    "enabled\n", un);
6935 			} else if (scsi_ifgetcap(SD_ADDRESS(un),
6936 			    "untagged-qing", 0) == 1) {
6937 				un->un_f_opt_queueing = TRUE;
6938 				un->un_saved_throttle = un->un_throttle =
6939 				    min(un->un_throttle, 3);
6940 			} else {
6941 				un->un_f_opt_queueing = FALSE;
6942 				un->un_saved_throttle = un->un_throttle = 1;
6943 			}
6944 		} else if ((scsi_ifgetcap(SD_ADDRESS(un), "untagged-qing", 0)
6945 		    == 1) && (un->un_f_arq_enabled == TRUE)) {
6946 			/* The Host Adapter supports internal queueing. */
6947 			un->un_f_opt_queueing = TRUE;
6948 			un->un_saved_throttle = un->un_throttle =
6949 			    min(un->un_throttle, 3);
6950 		} else {
6951 			un->un_f_opt_queueing = FALSE;
6952 			un->un_saved_throttle = un->un_throttle = 1;
6953 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6954 			    "sd_unit_attach: un:0x%p no tag queueing\n", un);
6955 		}
6956 
6957 		/*
6958 		 * Enable large transfers for SATA/SAS drives
6959 		 */
6960 		if (SD_IS_SERIAL(un)) {
6961 			un->un_max_xfer_size =
6962 			    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
6963 			    sd_max_xfer_size, SD_MAX_XFER_SIZE);
6964 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
6965 			    "sd_unit_attach: un:0x%p max transfer "
6966 			    "size=0x%x\n", un, un->un_max_xfer_size);
6967 
6968 		}
6969 
6970 		/* Setup or tear down default wide operations for disks */
6971 
6972 		/*
6973 		 * Note: Legacy: it may be possible for both "sd_max_xfer_size"
6974 		 * and "ssd_max_xfer_size" to exist simultaneously on the same
6975 		 * system and be set to different values. In the future this
6976 		 * code may need to be updated when the ssd module is
6977 		 * obsoleted and removed from the system. (4299588)
6978 		 */
6979 		if (SD_IS_PARALLEL_SCSI(un) &&
6980 		    (devp->sd_inq->inq_rdf == RDF_SCSI2) &&
6981 		    (devp->sd_inq->inq_wbus16 || devp->sd_inq->inq_wbus32)) {
6982 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
6983 			    1, 1) == 1) {
6984 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6985 				    "sd_unit_attach: un:0x%p Wide Transfer "
6986 				    "enabled\n", un);
6987 			}
6988 
6989 			/*
6990 			 * If tagged queuing has also been enabled, then
6991 			 * enable large xfers
6992 			 */
6993 			if (un->un_saved_throttle == sd_max_throttle) {
6994 				un->un_max_xfer_size =
6995 				    ddi_getprop(DDI_DEV_T_ANY, devi, 0,
6996 				    sd_max_xfer_size, SD_MAX_XFER_SIZE);
6997 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
6998 				    "sd_unit_attach: un:0x%p max transfer "
6999 				    "size=0x%x\n", un, un->un_max_xfer_size);
7000 			}
7001 		} else {
7002 			if (scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer",
7003 			    0, 1) == 1) {
7004 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7005 				    "sd_unit_attach: un:0x%p "
7006 				    "Wide Transfer disabled\n", un);
7007 			}
7008 		}
7009 	} else {
7010 		un->un_tagflags = FLAG_STAG;
7011 		un->un_max_xfer_size = ddi_getprop(DDI_DEV_T_ANY,
7012 		    devi, 0, sd_max_xfer_size, SD_MAX_XFER_SIZE);
7013 	}
7014 
7015 	/*
7016 	 * If this target supports LUN reset, try to enable it.
7017 	 */
7018 	if (un->un_f_lun_reset_enabled) {
7019 		if (scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 1, 1) == 1) {
7020 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7021 			    "un:0x%p lun_reset capability set\n", un);
7022 		} else {
7023 			SD_INFO(SD_LOG_ATTACH_DETACH, un, "sd_unit_attach: "
7024 			    "un:0x%p lun-reset capability not set\n", un);
7025 		}
7026 	}
7027 
7028 	/*
7029 	 * Adjust the maximum transfer size. This is to fix
7030 	 * the problem of partial DMA support on SPARC. Some
7031 	 * HBA driver, like aac, has very small dma_attr_maxxfer
7032 	 * size, which requires partial DMA support on SPARC.
7033 	 * In the future the SPARC pci nexus driver may solve
7034 	 * the problem instead of this fix.
7035 	 */
7036 #if defined(__sparc)
7037 	max_xfer_size = scsi_ifgetcap(SD_ADDRESS(un), "dma-max", 1);
7038 	if ((max_xfer_size > 0) && (max_xfer_size < un->un_max_xfer_size)) {
7039 		un->un_max_xfer_size = max_xfer_size;
7040 		un->un_partial_dma_supported = 1;
7041 	}
7042 #endif
7043 
7044 	/*
7045 	 * Set PKT_DMA_PARTIAL flag.
7046 	 */
7047 	if (un->un_partial_dma_supported == 1) {
7048 		un->un_pkt_flags = PKT_DMA_PARTIAL;
7049 	} else {
7050 		un->un_pkt_flags = 0;
7051 	}
7052 
7053 	/*
7054 	 * At this point in the attach, we have enough info in the
7055 	 * soft state to be able to issue commands to the target.
7056 	 *
7057 	 * All command paths used below MUST issue their commands as
7058 	 * SD_PATH_DIRECT. This is important as intermediate layers
7059 	 * are not all initialized yet (such as PM).
7060 	 */
7061 
7062 	/*
7063 	 * Send a TEST UNIT READY command to the device. This should clear
7064 	 * any outstanding UNIT ATTENTION that may be present.
7065 	 *
7066 	 * Note: Don't check for success, just track if there is a reservation,
7067 	 * this is a throw away command to clear any unit attentions.
7068 	 *
7069 	 * Note: This MUST be the first command issued to the target during
7070 	 * attach to ensure power on UNIT ATTENTIONS are cleared.
7071 	 * Pass in flag SD_DONT_RETRY_TUR to prevent the long delays associated
7072 	 * with attempts at spinning up a device with no media.
7073 	 */
7074 	if (sd_send_scsi_TEST_UNIT_READY(un, SD_DONT_RETRY_TUR) == EACCES) {
7075 		reservation_flag = SD_TARGET_IS_RESERVED;
7076 	}
7077 
7078 	/*
7079 	 * If the device is NOT a removable media device, attempt to spin
7080 	 * it up (using the START_STOP_UNIT command) and read its capacity
7081 	 * (using the READ CAPACITY command).  Note, however, that either
7082 	 * of these could fail and in some cases we would continue with
7083 	 * the attach despite the failure (see below).
7084 	 */
7085 	if (un->un_f_descr_format_supported) {
7086 		switch (sd_spin_up_unit(un)) {
7087 		case 0:
7088 			/*
7089 			 * Spin-up was successful; now try to read the
7090 			 * capacity.  If successful then save the results
7091 			 * and mark the capacity & lbasize as valid.
7092 			 */
7093 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7094 			    "sd_unit_attach: un:0x%p spin-up successful\n", un);
7095 
7096 			switch (sd_send_scsi_READ_CAPACITY(un, &capacity,
7097 			    &lbasize, SD_PATH_DIRECT)) {
7098 			case 0: {
7099 				if (capacity > DK_MAX_BLOCKS) {
7100 #ifdef _LP64
7101 					if (capacity + 1 >
7102 					    SD_GROUP1_MAX_ADDRESS) {
7103 						/*
7104 						 * Enable descriptor format
7105 						 * sense data so that we can
7106 						 * get 64 bit sense data
7107 						 * fields.
7108 						 */
7109 						sd_enable_descr_sense(un);
7110 					}
7111 #else
7112 					/* 32-bit kernels can't handle this */
7113 					scsi_log(SD_DEVINFO(un),
7114 					    sd_label, CE_WARN,
7115 					    "disk has %llu blocks, which "
7116 					    "is too large for a 32-bit "
7117 					    "kernel", capacity);
7118 
7119 #if defined(__i386) || defined(__amd64)
7120 					/*
7121 					 * 1TB disk was treated as (1T - 512)B
7122 					 * in the past, so that it might have
7123 					 * valid VTOC and solaris partitions,
7124 					 * we have to allow it to continue to
7125 					 * work.
7126 					 */
7127 					if (capacity -1 > DK_MAX_BLOCKS)
7128 #endif
7129 					goto spinup_failed;
7130 #endif
7131 				}
7132 
7133 				/*
7134 				 * Here it's not necessary to check the case:
7135 				 * the capacity of the device is bigger than
7136 				 * what the max hba cdb can support. Because
7137 				 * sd_send_scsi_READ_CAPACITY will retrieve
7138 				 * the capacity by sending USCSI command, which
7139 				 * is constrained by the max hba cdb. Actually,
7140 				 * sd_send_scsi_READ_CAPACITY will return
7141 				 * EINVAL when using bigger cdb than required
7142 				 * cdb length. Will handle this case in
7143 				 * "case EINVAL".
7144 				 */
7145 
7146 				/*
7147 				 * The following relies on
7148 				 * sd_send_scsi_READ_CAPACITY never
7149 				 * returning 0 for capacity and/or lbasize.
7150 				 */
7151 				sd_update_block_info(un, lbasize, capacity);
7152 
7153 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7154 				    "sd_unit_attach: un:0x%p capacity = %ld "
7155 				    "blocks; lbasize= %ld.\n", un,
7156 				    un->un_blockcount, un->un_tgt_blocksize);
7157 
7158 				break;
7159 			}
7160 			case EINVAL:
7161 				/*
7162 				 * In the case where the max-cdb-length property
7163 				 * is smaller than the required CDB length for
7164 				 * a SCSI device, a target driver can fail to
7165 				 * attach to that device.
7166 				 */
7167 				scsi_log(SD_DEVINFO(un),
7168 				    sd_label, CE_WARN,
7169 				    "disk capacity is too large "
7170 				    "for current cdb length");
7171 				goto spinup_failed;
7172 			case EACCES:
7173 				/*
7174 				 * Should never get here if the spin-up
7175 				 * succeeded, but code it in anyway.
7176 				 * From here, just continue with the attach...
7177 				 */
7178 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
7179 				    "sd_unit_attach: un:0x%p "
7180 				    "sd_send_scsi_READ_CAPACITY "
7181 				    "returned reservation conflict\n", un);
7182 				reservation_flag = SD_TARGET_IS_RESERVED;
7183 				break;
7184 			default:
7185 				/*
7186 				 * Likewise, should never get here if the
7187 				 * spin-up succeeded. Just continue with
7188 				 * the attach...
7189 				 */
7190 				break;
7191 			}
7192 			break;
7193 		case EACCES:
7194 			/*
7195 			 * Device is reserved by another host.  In this case
7196 			 * we could not spin it up or read the capacity, but
7197 			 * we continue with the attach anyway.
7198 			 */
7199 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7200 			    "sd_unit_attach: un:0x%p spin-up reservation "
7201 			    "conflict.\n", un);
7202 			reservation_flag = SD_TARGET_IS_RESERVED;
7203 			break;
7204 		default:
7205 			/* Fail the attach if the spin-up failed. */
7206 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
7207 			    "sd_unit_attach: un:0x%p spin-up failed.", un);
7208 			goto spinup_failed;
7209 		}
7210 	}
7211 
7212 	/*
7213 	 * Check to see if this is a MMC drive
7214 	 */
7215 	if (ISCD(un)) {
7216 		sd_set_mmc_caps(un);
7217 	}
7218 
7219 
7220 	/*
7221 	 * Add a zero-length attribute to tell the world we support
7222 	 * kernel ioctls (for layered drivers)
7223 	 */
7224 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7225 	    DDI_KERNEL_IOCTL, NULL, 0);
7226 
7227 	/*
7228 	 * Add a boolean property to tell the world we support
7229 	 * the B_FAILFAST flag (for layered drivers)
7230 	 */
7231 	(void) ddi_prop_create(DDI_DEV_T_NONE, devi, DDI_PROP_CANSLEEP,
7232 	    "ddi-failfast-supported", NULL, 0);
7233 
7234 	/*
7235 	 * Initialize power management
7236 	 */
7237 	mutex_init(&un->un_pm_mutex, NULL, MUTEX_DRIVER, NULL);
7238 	cv_init(&un->un_pm_busy_cv, NULL, CV_DRIVER, NULL);
7239 	sd_setup_pm(un, devi);
7240 	if (un->un_f_pm_is_enabled == FALSE) {
7241 		/*
7242 		 * For performance, point to a jump table that does
7243 		 * not include pm.
7244 		 * The direct and priority chains don't change with PM.
7245 		 *
7246 		 * Note: this is currently done based on individual device
7247 		 * capabilities. When an interface for determining system
7248 		 * power enabled state becomes available, or when additional
7249 		 * layers are added to the command chain, these values will
7250 		 * have to be re-evaluated for correctness.
7251 		 */
7252 		if (un->un_f_non_devbsize_supported) {
7253 			un->un_buf_chain_type = SD_CHAIN_INFO_RMMEDIA_NO_PM;
7254 		} else {
7255 			un->un_buf_chain_type = SD_CHAIN_INFO_DISK_NO_PM;
7256 		}
7257 		un->un_uscsi_chain_type  = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
7258 	}
7259 
7260 	/*
7261 	 * This property is set to 0 by HA software to avoid retries
7262 	 * on a reserved disk. (The preferred property name is
7263 	 * "retry-on-reservation-conflict") (1189689)
7264 	 *
7265 	 * Note: The use of a global here can have unintended consequences. A
7266 	 * per instance variable is preferrable to match the capabilities of
7267 	 * different underlying hba's (4402600)
7268 	 */
7269 	sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY, devi,
7270 	    DDI_PROP_DONTPASS, "retry-on-reservation-conflict",
7271 	    sd_retry_on_reservation_conflict);
7272 	if (sd_retry_on_reservation_conflict != 0) {
7273 		sd_retry_on_reservation_conflict = ddi_getprop(DDI_DEV_T_ANY,
7274 		    devi, DDI_PROP_DONTPASS, sd_resv_conflict_name,
7275 		    sd_retry_on_reservation_conflict);
7276 	}
7277 
7278 	/* Set up options for QFULL handling. */
7279 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7280 	    "qfull-retries", -1)) != -1) {
7281 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retries",
7282 		    rval, 1);
7283 	}
7284 	if ((rval = ddi_getprop(DDI_DEV_T_ANY, devi, 0,
7285 	    "qfull-retry-interval", -1)) != -1) {
7286 		(void) scsi_ifsetcap(SD_ADDRESS(un), "qfull-retry-interval",
7287 		    rval, 1);
7288 	}
7289 
7290 	/*
7291 	 * This just prints a message that announces the existence of the
7292 	 * device. The message is always printed in the system logfile, but
7293 	 * only appears on the console if the system is booted with the
7294 	 * -v (verbose) argument.
7295 	 */
7296 	ddi_report_dev(devi);
7297 
7298 	un->un_mediastate = DKIO_NONE;
7299 
7300 	cmlb_alloc_handle(&un->un_cmlbhandle);
7301 
7302 #if defined(__i386) || defined(__amd64)
7303 	/*
7304 	 * On x86, compensate for off-by-1 legacy error
7305 	 */
7306 	if (!un->un_f_has_removable_media && !un->un_f_is_hotpluggable &&
7307 	    (lbasize == un->un_sys_blocksize))
7308 		offbyone = CMLB_OFF_BY_ONE;
7309 #endif
7310 
7311 	if (cmlb_attach(devi, &sd_tgops, (int)devp->sd_inq->inq_dtype,
7312 	    un->un_f_has_removable_media, un->un_f_is_hotpluggable,
7313 	    un->un_node_type, offbyone, un->un_cmlbhandle,
7314 	    (void *)SD_PATH_DIRECT) != 0) {
7315 		goto cmlb_attach_failed;
7316 	}
7317 
7318 
7319 	/*
7320 	 * Read and validate the device's geometry (ie, disk label)
7321 	 * A new unformatted drive will not have a valid geometry, but
7322 	 * the driver needs to successfully attach to this device so
7323 	 * the drive can be formatted via ioctls.
7324 	 */
7325 	geom_label_valid = (cmlb_validate(un->un_cmlbhandle, 0,
7326 	    (void *)SD_PATH_DIRECT) == 0) ? 1: 0;
7327 
7328 	mutex_enter(SD_MUTEX(un));
7329 
7330 	/*
7331 	 * Read and initialize the devid for the unit.
7332 	 */
7333 	if (un->un_f_devid_supported) {
7334 		sd_register_devid(un, devi, reservation_flag);
7335 	}
7336 	mutex_exit(SD_MUTEX(un));
7337 
7338 #if (defined(__fibre))
7339 	/*
7340 	 * Register callbacks for fibre only.  You can't do this soley
7341 	 * on the basis of the devid_type because this is hba specific.
7342 	 * We need to query our hba capabilities to find out whether to
7343 	 * register or not.
7344 	 */
7345 	if (un->un_f_is_fibre) {
7346 		if (strcmp(un->un_node_type, DDI_NT_BLOCK_CHAN)) {
7347 			sd_init_event_callbacks(un);
7348 			SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7349 			    "sd_unit_attach: un:0x%p event callbacks inserted",
7350 			    un);
7351 		}
7352 	}
7353 #endif
7354 
7355 	if (un->un_f_opt_disable_cache == TRUE) {
7356 		/*
7357 		 * Disable both read cache and write cache.  This is
7358 		 * the historic behavior of the keywords in the config file.
7359 		 */
7360 		if (sd_cache_control(un, SD_CACHE_DISABLE, SD_CACHE_DISABLE) !=
7361 		    0) {
7362 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7363 			    "sd_unit_attach: un:0x%p Could not disable "
7364 			    "caching", un);
7365 			goto devid_failed;
7366 		}
7367 	}
7368 
7369 	/*
7370 	 * Check the value of the WCE bit now and
7371 	 * set un_f_write_cache_enabled accordingly.
7372 	 */
7373 	(void) sd_get_write_cache_enabled(un, &wc_enabled);
7374 	mutex_enter(SD_MUTEX(un));
7375 	un->un_f_write_cache_enabled = (wc_enabled != 0);
7376 	mutex_exit(SD_MUTEX(un));
7377 
7378 	/*
7379 	 * Check the value of the NV_SUP bit and set
7380 	 * un_f_suppress_cache_flush accordingly.
7381 	 */
7382 	sd_get_nv_sup(un);
7383 
7384 	/*
7385 	 * Find out what type of reservation this disk supports.
7386 	 */
7387 	switch (sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS, 0, NULL)) {
7388 	case 0:
7389 		/*
7390 		 * SCSI-3 reservations are supported.
7391 		 */
7392 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7393 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7394 		    "sd_unit_attach: un:0x%p SCSI-3 reservations\n", un);
7395 		break;
7396 	case ENOTSUP:
7397 		/*
7398 		 * The PERSISTENT RESERVE IN command would not be recognized by
7399 		 * a SCSI-2 device, so assume the reservation type is SCSI-2.
7400 		 */
7401 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7402 		    "sd_unit_attach: un:0x%p SCSI-2 reservations\n", un);
7403 		un->un_reservation_type = SD_SCSI2_RESERVATION;
7404 		break;
7405 	default:
7406 		/*
7407 		 * default to SCSI-3 reservations
7408 		 */
7409 		SD_INFO(SD_LOG_ATTACH_DETACH, un,
7410 		    "sd_unit_attach: un:0x%p default SCSI3 reservations\n", un);
7411 		un->un_reservation_type = SD_SCSI3_RESERVATION;
7412 		break;
7413 	}
7414 
7415 	/*
7416 	 * Set the pstat and error stat values here, so data obtained during the
7417 	 * previous attach-time routines is available.
7418 	 *
7419 	 * Note: This is a critical sequence that needs to be maintained:
7420 	 *	1) Instantiate the kstats before any routines using the iopath
7421 	 *	   (i.e. sd_send_scsi_cmd).
7422 	 *	2) Initialize the error stats (sd_set_errstats) and partition
7423 	 *	   stats (sd_set_pstats)here, following
7424 	 *	   cmlb_validate_geometry(), sd_register_devid(), and
7425 	 *	   sd_cache_control().
7426 	 */
7427 
7428 	if (un->un_f_pkstats_enabled && geom_label_valid) {
7429 		sd_set_pstats(un);
7430 		SD_TRACE(SD_LOG_IO_PARTITION, un,
7431 		    "sd_unit_attach: un:0x%p pstats created and set\n", un);
7432 	}
7433 
7434 	sd_set_errstats(un);
7435 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7436 	    "sd_unit_attach: un:0x%p errstats set\n", un);
7437 
7438 
7439 	/*
7440 	 * After successfully attaching an instance, we record the information
7441 	 * of how many luns have been attached on the relative target and
7442 	 * controller for parallel SCSI. This information is used when sd tries
7443 	 * to set the tagged queuing capability in HBA.
7444 	 */
7445 	if (SD_IS_PARALLEL_SCSI(un) && (tgt >= 0) && (tgt < NTARGETS_WIDE)) {
7446 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_ATTACH);
7447 	}
7448 
7449 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
7450 	    "sd_unit_attach: un:0x%p exit success\n", un);
7451 
7452 	return (DDI_SUCCESS);
7453 
7454 	/*
7455 	 * An error occurred during the attach; clean up & return failure.
7456 	 */
7457 
7458 devid_failed:
7459 
7460 setup_pm_failed:
7461 	ddi_remove_minor_node(devi, NULL);
7462 
7463 cmlb_attach_failed:
7464 	/*
7465 	 * Cleanup from the scsi_ifsetcap() calls (437868)
7466 	 */
7467 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
7468 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
7469 
7470 	/*
7471 	 * Refer to the comments of setting tagged-qing in the beginning of
7472 	 * sd_unit_attach. We can only disable tagged queuing when there is
7473 	 * no lun attached on the target.
7474 	 */
7475 	if (sd_scsi_get_target_lun_count(pdip, tgt) < 1) {
7476 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
7477 	}
7478 
7479 	if (un->un_f_is_fibre == FALSE) {
7480 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
7481 	}
7482 
7483 spinup_failed:
7484 
7485 	mutex_enter(SD_MUTEX(un));
7486 
7487 	/* Cancel callback for SD_PATH_DIRECT_PRIORITY cmd. restart */
7488 	if (un->un_direct_priority_timeid != NULL) {
7489 		timeout_id_t temp_id = un->un_direct_priority_timeid;
7490 		un->un_direct_priority_timeid = NULL;
7491 		mutex_exit(SD_MUTEX(un));
7492 		(void) untimeout(temp_id);
7493 		mutex_enter(SD_MUTEX(un));
7494 	}
7495 
7496 	/* Cancel any pending start/stop timeouts */
7497 	if (un->un_startstop_timeid != NULL) {
7498 		timeout_id_t temp_id = un->un_startstop_timeid;
7499 		un->un_startstop_timeid = NULL;
7500 		mutex_exit(SD_MUTEX(un));
7501 		(void) untimeout(temp_id);
7502 		mutex_enter(SD_MUTEX(un));
7503 	}
7504 
7505 	/* Cancel any pending reset-throttle timeouts */
7506 	if (un->un_reset_throttle_timeid != NULL) {
7507 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
7508 		un->un_reset_throttle_timeid = NULL;
7509 		mutex_exit(SD_MUTEX(un));
7510 		(void) untimeout(temp_id);
7511 		mutex_enter(SD_MUTEX(un));
7512 	}
7513 
7514 	/* Cancel any pending retry timeouts */
7515 	if (un->un_retry_timeid != NULL) {
7516 		timeout_id_t temp_id = un->un_retry_timeid;
7517 		un->un_retry_timeid = NULL;
7518 		mutex_exit(SD_MUTEX(un));
7519 		(void) untimeout(temp_id);
7520 		mutex_enter(SD_MUTEX(un));
7521 	}
7522 
7523 	/* Cancel any pending delayed cv broadcast timeouts */
7524 	if (un->un_dcvb_timeid != NULL) {
7525 		timeout_id_t temp_id = un->un_dcvb_timeid;
7526 		un->un_dcvb_timeid = NULL;
7527 		mutex_exit(SD_MUTEX(un));
7528 		(void) untimeout(temp_id);
7529 		mutex_enter(SD_MUTEX(un));
7530 	}
7531 
7532 	mutex_exit(SD_MUTEX(un));
7533 
7534 	/* There should not be any in-progress I/O so ASSERT this check */
7535 	ASSERT(un->un_ncmds_in_transport == 0);
7536 	ASSERT(un->un_ncmds_in_driver == 0);
7537 
7538 	/* Do not free the softstate if the callback routine is active */
7539 	sd_sync_with_callback(un);
7540 
7541 	/*
7542 	 * Partition stats apparently are not used with removables. These would
7543 	 * not have been created during attach, so no need to clean them up...
7544 	 */
7545 	if (un->un_errstats != NULL) {
7546 		kstat_delete(un->un_errstats);
7547 		un->un_errstats = NULL;
7548 	}
7549 
7550 create_errstats_failed:
7551 
7552 	if (un->un_stats != NULL) {
7553 		kstat_delete(un->un_stats);
7554 		un->un_stats = NULL;
7555 	}
7556 
7557 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
7558 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
7559 
7560 	ddi_prop_remove_all(devi);
7561 	sema_destroy(&un->un_semoclose);
7562 	cv_destroy(&un->un_state_cv);
7563 
7564 getrbuf_failed:
7565 
7566 	sd_free_rqs(un);
7567 
7568 alloc_rqs_failed:
7569 
7570 	devp->sd_private = NULL;
7571 	bzero(un, sizeof (struct sd_lun));	/* Clear any stale data! */
7572 
7573 get_softstate_failed:
7574 	/*
7575 	 * Note: the man pages are unclear as to whether or not doing a
7576 	 * ddi_soft_state_free(sd_state, instance) is the right way to
7577 	 * clean up after the ddi_soft_state_zalloc() if the subsequent
7578 	 * ddi_get_soft_state() fails.  The implication seems to be
7579 	 * that the get_soft_state cannot fail if the zalloc succeeds.
7580 	 */
7581 	ddi_soft_state_free(sd_state, instance);
7582 
7583 probe_failed:
7584 	scsi_unprobe(devp);
7585 
7586 	return (DDI_FAILURE);
7587 }
7588 
7589 
7590 /*
7591  *    Function: sd_unit_detach
7592  *
7593  * Description: Performs DDI_DETACH processing for sddetach().
7594  *
7595  * Return Code: DDI_SUCCESS
7596  *		DDI_FAILURE
7597  *
7598  *     Context: Kernel thread context
7599  */
7600 
7601 static int
7602 sd_unit_detach(dev_info_t *devi)
7603 {
7604 	struct scsi_device	*devp;
7605 	struct sd_lun		*un;
7606 	int			i;
7607 	int			tgt;
7608 	dev_t			dev;
7609 	dev_info_t		*pdip = ddi_get_parent(devi);
7610 	int			instance = ddi_get_instance(devi);
7611 
7612 	mutex_enter(&sd_detach_mutex);
7613 
7614 	/*
7615 	 * Fail the detach for any of the following:
7616 	 *  - Unable to get the sd_lun struct for the instance
7617 	 *  - A layered driver has an outstanding open on the instance
7618 	 *  - Another thread is already detaching this instance
7619 	 *  - Another thread is currently performing an open
7620 	 */
7621 	devp = ddi_get_driver_private(devi);
7622 	if ((devp == NULL) ||
7623 	    ((un = (struct sd_lun *)devp->sd_private) == NULL) ||
7624 	    (un->un_ncmds_in_driver != 0) || (un->un_layer_count != 0) ||
7625 	    (un->un_detach_count != 0) || (un->un_opens_in_progress != 0)) {
7626 		mutex_exit(&sd_detach_mutex);
7627 		return (DDI_FAILURE);
7628 	}
7629 
7630 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: entry 0x%p\n", un);
7631 
7632 	/*
7633 	 * Mark this instance as currently in a detach, to inhibit any
7634 	 * opens from a layered driver.
7635 	 */
7636 	un->un_detach_count++;
7637 	mutex_exit(&sd_detach_mutex);
7638 
7639 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, devi, DDI_PROP_DONTPASS,
7640 	    SCSI_ADDR_PROP_TARGET, -1);
7641 
7642 	dev = sd_make_device(SD_DEVINFO(un));
7643 
7644 #ifndef lint
7645 	_NOTE(COMPETING_THREADS_NOW);
7646 #endif
7647 
7648 	mutex_enter(SD_MUTEX(un));
7649 
7650 	/*
7651 	 * Fail the detach if there are any outstanding layered
7652 	 * opens on this device.
7653 	 */
7654 	for (i = 0; i < NDKMAP; i++) {
7655 		if (un->un_ocmap.lyropen[i] != 0) {
7656 			goto err_notclosed;
7657 		}
7658 	}
7659 
7660 	/*
7661 	 * Verify there are NO outstanding commands issued to this device.
7662 	 * ie, un_ncmds_in_transport == 0.
7663 	 * It's possible to have outstanding commands through the physio
7664 	 * code path, even though everything's closed.
7665 	 */
7666 	if ((un->un_ncmds_in_transport != 0) || (un->un_retry_timeid != NULL) ||
7667 	    (un->un_direct_priority_timeid != NULL) ||
7668 	    (un->un_state == SD_STATE_RWAIT)) {
7669 		mutex_exit(SD_MUTEX(un));
7670 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7671 		    "sd_dr_detach: Detach failure due to outstanding cmds\n");
7672 		goto err_stillbusy;
7673 	}
7674 
7675 	/*
7676 	 * If we have the device reserved, release the reservation.
7677 	 */
7678 	if ((un->un_resvd_status & SD_RESERVE) &&
7679 	    !(un->un_resvd_status & SD_LOST_RESERVE)) {
7680 		mutex_exit(SD_MUTEX(un));
7681 		/*
7682 		 * Note: sd_reserve_release sends a command to the device
7683 		 * via the sd_ioctlcmd() path, and can sleep.
7684 		 */
7685 		if (sd_reserve_release(dev, SD_RELEASE) != 0) {
7686 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7687 			    "sd_dr_detach: Cannot release reservation \n");
7688 		}
7689 	} else {
7690 		mutex_exit(SD_MUTEX(un));
7691 	}
7692 
7693 	/*
7694 	 * Untimeout any reserve recover, throttle reset, restart unit
7695 	 * and delayed broadcast timeout threads. Protect the timeout pointer
7696 	 * from getting nulled by their callback functions.
7697 	 */
7698 	mutex_enter(SD_MUTEX(un));
7699 	if (un->un_resvd_timeid != NULL) {
7700 		timeout_id_t temp_id = un->un_resvd_timeid;
7701 		un->un_resvd_timeid = NULL;
7702 		mutex_exit(SD_MUTEX(un));
7703 		(void) untimeout(temp_id);
7704 		mutex_enter(SD_MUTEX(un));
7705 	}
7706 
7707 	if (un->un_reset_throttle_timeid != NULL) {
7708 		timeout_id_t temp_id = un->un_reset_throttle_timeid;
7709 		un->un_reset_throttle_timeid = NULL;
7710 		mutex_exit(SD_MUTEX(un));
7711 		(void) untimeout(temp_id);
7712 		mutex_enter(SD_MUTEX(un));
7713 	}
7714 
7715 	if (un->un_startstop_timeid != NULL) {
7716 		timeout_id_t temp_id = un->un_startstop_timeid;
7717 		un->un_startstop_timeid = NULL;
7718 		mutex_exit(SD_MUTEX(un));
7719 		(void) untimeout(temp_id);
7720 		mutex_enter(SD_MUTEX(un));
7721 	}
7722 
7723 	if (un->un_dcvb_timeid != NULL) {
7724 		timeout_id_t temp_id = un->un_dcvb_timeid;
7725 		un->un_dcvb_timeid = NULL;
7726 		mutex_exit(SD_MUTEX(un));
7727 		(void) untimeout(temp_id);
7728 	} else {
7729 		mutex_exit(SD_MUTEX(un));
7730 	}
7731 
7732 	/* Remove any pending reservation reclaim requests for this device */
7733 	sd_rmv_resv_reclaim_req(dev);
7734 
7735 	mutex_enter(SD_MUTEX(un));
7736 
7737 	/* Cancel any pending callbacks for SD_PATH_DIRECT_PRIORITY cmd. */
7738 	if (un->un_direct_priority_timeid != NULL) {
7739 		timeout_id_t temp_id = un->un_direct_priority_timeid;
7740 		un->un_direct_priority_timeid = NULL;
7741 		mutex_exit(SD_MUTEX(un));
7742 		(void) untimeout(temp_id);
7743 		mutex_enter(SD_MUTEX(un));
7744 	}
7745 
7746 	/* Cancel any active multi-host disk watch thread requests */
7747 	if (un->un_mhd_token != NULL) {
7748 		mutex_exit(SD_MUTEX(un));
7749 		 _NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_mhd_token));
7750 		if (scsi_watch_request_terminate(un->un_mhd_token,
7751 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
7752 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7753 			    "sd_dr_detach: Cannot cancel mhd watch request\n");
7754 			/*
7755 			 * Note: We are returning here after having removed
7756 			 * some driver timeouts above. This is consistent with
7757 			 * the legacy implementation but perhaps the watch
7758 			 * terminate call should be made with the wait flag set.
7759 			 */
7760 			goto err_stillbusy;
7761 		}
7762 		mutex_enter(SD_MUTEX(un));
7763 		un->un_mhd_token = NULL;
7764 	}
7765 
7766 	if (un->un_swr_token != NULL) {
7767 		mutex_exit(SD_MUTEX(un));
7768 		_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_swr_token));
7769 		if (scsi_watch_request_terminate(un->un_swr_token,
7770 		    SCSI_WATCH_TERMINATE_NOWAIT)) {
7771 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7772 			    "sd_dr_detach: Cannot cancel swr watch request\n");
7773 			/*
7774 			 * Note: We are returning here after having removed
7775 			 * some driver timeouts above. This is consistent with
7776 			 * the legacy implementation but perhaps the watch
7777 			 * terminate call should be made with the wait flag set.
7778 			 */
7779 			goto err_stillbusy;
7780 		}
7781 		mutex_enter(SD_MUTEX(un));
7782 		un->un_swr_token = NULL;
7783 	}
7784 
7785 	mutex_exit(SD_MUTEX(un));
7786 
7787 	/*
7788 	 * Clear any scsi_reset_notifies. We clear the reset notifies
7789 	 * if we have not registered one.
7790 	 * Note: The sd_mhd_reset_notify_cb() fn tries to acquire SD_MUTEX!
7791 	 */
7792 	(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
7793 	    sd_mhd_reset_notify_cb, (caddr_t)un);
7794 
7795 	/*
7796 	 * protect the timeout pointers from getting nulled by
7797 	 * their callback functions during the cancellation process.
7798 	 * In such a scenario untimeout can be invoked with a null value.
7799 	 */
7800 	_NOTE(NO_COMPETING_THREADS_NOW);
7801 
7802 	mutex_enter(&un->un_pm_mutex);
7803 	if (un->un_pm_idle_timeid != NULL) {
7804 		timeout_id_t temp_id = un->un_pm_idle_timeid;
7805 		un->un_pm_idle_timeid = NULL;
7806 		mutex_exit(&un->un_pm_mutex);
7807 
7808 		/*
7809 		 * Timeout is active; cancel it.
7810 		 * Note that it'll never be active on a device
7811 		 * that does not support PM therefore we don't
7812 		 * have to check before calling pm_idle_component.
7813 		 */
7814 		(void) untimeout(temp_id);
7815 		(void) pm_idle_component(SD_DEVINFO(un), 0);
7816 		mutex_enter(&un->un_pm_mutex);
7817 	}
7818 
7819 	/*
7820 	 * Check whether there is already a timeout scheduled for power
7821 	 * management. If yes then don't lower the power here, that's.
7822 	 * the timeout handler's job.
7823 	 */
7824 	if (un->un_pm_timeid != NULL) {
7825 		timeout_id_t temp_id = un->un_pm_timeid;
7826 		un->un_pm_timeid = NULL;
7827 		mutex_exit(&un->un_pm_mutex);
7828 		/*
7829 		 * Timeout is active; cancel it.
7830 		 * Note that it'll never be active on a device
7831 		 * that does not support PM therefore we don't
7832 		 * have to check before calling pm_idle_component.
7833 		 */
7834 		(void) untimeout(temp_id);
7835 		(void) pm_idle_component(SD_DEVINFO(un), 0);
7836 
7837 	} else {
7838 		mutex_exit(&un->un_pm_mutex);
7839 		if ((un->un_f_pm_is_enabled == TRUE) &&
7840 		    (pm_lower_power(SD_DEVINFO(un), 0, SD_SPINDLE_OFF) !=
7841 		    DDI_SUCCESS)) {
7842 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7843 		    "sd_dr_detach: Lower power request failed, ignoring.\n");
7844 			/*
7845 			 * Fix for bug: 4297749, item # 13
7846 			 * The above test now includes a check to see if PM is
7847 			 * supported by this device before call
7848 			 * pm_lower_power().
7849 			 * Note, the following is not dead code. The call to
7850 			 * pm_lower_power above will generate a call back into
7851 			 * our sdpower routine which might result in a timeout
7852 			 * handler getting activated. Therefore the following
7853 			 * code is valid and necessary.
7854 			 */
7855 			mutex_enter(&un->un_pm_mutex);
7856 			if (un->un_pm_timeid != NULL) {
7857 				timeout_id_t temp_id = un->un_pm_timeid;
7858 				un->un_pm_timeid = NULL;
7859 				mutex_exit(&un->un_pm_mutex);
7860 				(void) untimeout(temp_id);
7861 				(void) pm_idle_component(SD_DEVINFO(un), 0);
7862 			} else {
7863 				mutex_exit(&un->un_pm_mutex);
7864 			}
7865 		}
7866 	}
7867 
7868 	/*
7869 	 * Cleanup from the scsi_ifsetcap() calls (437868)
7870 	 * Relocated here from above to be after the call to
7871 	 * pm_lower_power, which was getting errors.
7872 	 */
7873 	(void) scsi_ifsetcap(SD_ADDRESS(un), "lun-reset", 0, 1);
7874 	(void) scsi_ifsetcap(SD_ADDRESS(un), "wide-xfer", 0, 1);
7875 
7876 	/*
7877 	 * Currently, tagged queuing is supported per target based by HBA.
7878 	 * Setting this per lun instance actually sets the capability of this
7879 	 * target in HBA, which affects those luns already attached on the
7880 	 * same target. So during detach, we can only disable this capability
7881 	 * only when this is the only lun left on this target. By doing
7882 	 * this, we assume a target has the same tagged queuing capability
7883 	 * for every lun. The condition can be removed when HBA is changed to
7884 	 * support per lun based tagged queuing capability.
7885 	 */
7886 	if (sd_scsi_get_target_lun_count(pdip, tgt) <= 1) {
7887 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
7888 	}
7889 
7890 	if (un->un_f_is_fibre == FALSE) {
7891 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 0, 1);
7892 	}
7893 
7894 	/*
7895 	 * Remove any event callbacks, fibre only
7896 	 */
7897 	if (un->un_f_is_fibre == TRUE) {
7898 		if ((un->un_insert_event != NULL) &&
7899 		    (ddi_remove_event_handler(un->un_insert_cb_id) !=
7900 		    DDI_SUCCESS)) {
7901 			/*
7902 			 * Note: We are returning here after having done
7903 			 * substantial cleanup above. This is consistent
7904 			 * with the legacy implementation but this may not
7905 			 * be the right thing to do.
7906 			 */
7907 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7908 			    "sd_dr_detach: Cannot cancel insert event\n");
7909 			goto err_remove_event;
7910 		}
7911 		un->un_insert_event = NULL;
7912 
7913 		if ((un->un_remove_event != NULL) &&
7914 		    (ddi_remove_event_handler(un->un_remove_cb_id) !=
7915 		    DDI_SUCCESS)) {
7916 			/*
7917 			 * Note: We are returning here after having done
7918 			 * substantial cleanup above. This is consistent
7919 			 * with the legacy implementation but this may not
7920 			 * be the right thing to do.
7921 			 */
7922 			SD_ERROR(SD_LOG_ATTACH_DETACH, un,
7923 			    "sd_dr_detach: Cannot cancel remove event\n");
7924 			goto err_remove_event;
7925 		}
7926 		un->un_remove_event = NULL;
7927 	}
7928 
7929 	/* Do not free the softstate if the callback routine is active */
7930 	sd_sync_with_callback(un);
7931 
7932 	cmlb_detach(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
7933 	cmlb_free_handle(&un->un_cmlbhandle);
7934 
7935 	/*
7936 	 * Hold the detach mutex here, to make sure that no other threads ever
7937 	 * can access a (partially) freed soft state structure.
7938 	 */
7939 	mutex_enter(&sd_detach_mutex);
7940 
7941 	/*
7942 	 * Clean up the soft state struct.
7943 	 * Cleanup is done in reverse order of allocs/inits.
7944 	 * At this point there should be no competing threads anymore.
7945 	 */
7946 
7947 	/* Unregister and free device id. */
7948 	ddi_devid_unregister(devi);
7949 	if (un->un_devid) {
7950 		ddi_devid_free(un->un_devid);
7951 		un->un_devid = NULL;
7952 	}
7953 
7954 	/*
7955 	 * Destroy wmap cache if it exists.
7956 	 */
7957 	if (un->un_wm_cache != NULL) {
7958 		kmem_cache_destroy(un->un_wm_cache);
7959 		un->un_wm_cache = NULL;
7960 	}
7961 
7962 	/*
7963 	 * kstat cleanup is done in detach for all device types (4363169).
7964 	 * We do not want to fail detach if the device kstats are not deleted
7965 	 * since there is a confusion about the devo_refcnt for the device.
7966 	 * We just delete the kstats and let detach complete successfully.
7967 	 */
7968 	if (un->un_stats != NULL) {
7969 		kstat_delete(un->un_stats);
7970 		un->un_stats = NULL;
7971 	}
7972 	if (un->un_errstats != NULL) {
7973 		kstat_delete(un->un_errstats);
7974 		un->un_errstats = NULL;
7975 	}
7976 
7977 	/* Remove partition stats */
7978 	if (un->un_f_pkstats_enabled) {
7979 		for (i = 0; i < NSDMAP; i++) {
7980 			if (un->un_pstats[i] != NULL) {
7981 				kstat_delete(un->un_pstats[i]);
7982 				un->un_pstats[i] = NULL;
7983 			}
7984 		}
7985 	}
7986 
7987 	/* Remove xbuf registration */
7988 	ddi_xbuf_attr_unregister_devinfo(un->un_xbuf_attr, devi);
7989 	ddi_xbuf_attr_destroy(un->un_xbuf_attr);
7990 
7991 	/* Remove driver properties */
7992 	ddi_prop_remove_all(devi);
7993 
7994 	mutex_destroy(&un->un_pm_mutex);
7995 	cv_destroy(&un->un_pm_busy_cv);
7996 
7997 	cv_destroy(&un->un_wcc_cv);
7998 
7999 	/* Open/close semaphore */
8000 	sema_destroy(&un->un_semoclose);
8001 
8002 	/* Removable media condvar. */
8003 	cv_destroy(&un->un_state_cv);
8004 
8005 	/* Suspend/resume condvar. */
8006 	cv_destroy(&un->un_suspend_cv);
8007 	cv_destroy(&un->un_disk_busy_cv);
8008 
8009 	sd_free_rqs(un);
8010 
8011 	/* Free up soft state */
8012 	devp->sd_private = NULL;
8013 
8014 	bzero(un, sizeof (struct sd_lun));
8015 	ddi_soft_state_free(sd_state, instance);
8016 
8017 	mutex_exit(&sd_detach_mutex);
8018 
8019 	/* This frees up the INQUIRY data associated with the device. */
8020 	scsi_unprobe(devp);
8021 
8022 	/*
8023 	 * After successfully detaching an instance, we update the information
8024 	 * of how many luns have been attached in the relative target and
8025 	 * controller for parallel SCSI. This information is used when sd tries
8026 	 * to set the tagged queuing capability in HBA.
8027 	 * Since un has been released, we can't use SD_IS_PARALLEL_SCSI(un) to
8028 	 * check if the device is parallel SCSI. However, we don't need to
8029 	 * check here because we've already checked during attach. No device
8030 	 * that is not parallel SCSI is in the chain.
8031 	 */
8032 	if ((tgt >= 0) && (tgt < NTARGETS_WIDE)) {
8033 		sd_scsi_update_lun_on_target(pdip, tgt, SD_SCSI_LUN_DETACH);
8034 	}
8035 
8036 	return (DDI_SUCCESS);
8037 
8038 err_notclosed:
8039 	mutex_exit(SD_MUTEX(un));
8040 
8041 err_stillbusy:
8042 	_NOTE(NO_COMPETING_THREADS_NOW);
8043 
8044 err_remove_event:
8045 	mutex_enter(&sd_detach_mutex);
8046 	un->un_detach_count--;
8047 	mutex_exit(&sd_detach_mutex);
8048 
8049 	SD_TRACE(SD_LOG_ATTACH_DETACH, un, "sd_unit_detach: exit failure\n");
8050 	return (DDI_FAILURE);
8051 }
8052 
8053 
8054 /*
8055  *    Function: sd_create_errstats
8056  *
8057  * Description: This routine instantiates the device error stats.
8058  *
8059  *		Note: During attach the stats are instantiated first so they are
8060  *		available for attach-time routines that utilize the driver
8061  *		iopath to send commands to the device. The stats are initialized
8062  *		separately so data obtained during some attach-time routines is
8063  *		available. (4362483)
8064  *
8065  *   Arguments: un - driver soft state (unit) structure
8066  *		instance - driver instance
8067  *
8068  *     Context: Kernel thread context
8069  */
8070 
8071 static void
8072 sd_create_errstats(struct sd_lun *un, int instance)
8073 {
8074 	struct	sd_errstats	*stp;
8075 	char	kstatmodule_err[KSTAT_STRLEN];
8076 	char	kstatname[KSTAT_STRLEN];
8077 	int	ndata = (sizeof (struct sd_errstats) / sizeof (kstat_named_t));
8078 
8079 	ASSERT(un != NULL);
8080 
8081 	if (un->un_errstats != NULL) {
8082 		return;
8083 	}
8084 
8085 	(void) snprintf(kstatmodule_err, sizeof (kstatmodule_err),
8086 	    "%serr", sd_label);
8087 	(void) snprintf(kstatname, sizeof (kstatname),
8088 	    "%s%d,err", sd_label, instance);
8089 
8090 	un->un_errstats = kstat_create(kstatmodule_err, instance, kstatname,
8091 	    "device_error", KSTAT_TYPE_NAMED, ndata, KSTAT_FLAG_PERSISTENT);
8092 
8093 	if (un->un_errstats == NULL) {
8094 		SD_ERROR(SD_LOG_ATTACH_DETACH, un,
8095 		    "sd_create_errstats: Failed kstat_create\n");
8096 		return;
8097 	}
8098 
8099 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8100 	kstat_named_init(&stp->sd_softerrs,	"Soft Errors",
8101 	    KSTAT_DATA_UINT32);
8102 	kstat_named_init(&stp->sd_harderrs,	"Hard Errors",
8103 	    KSTAT_DATA_UINT32);
8104 	kstat_named_init(&stp->sd_transerrs,	"Transport Errors",
8105 	    KSTAT_DATA_UINT32);
8106 	kstat_named_init(&stp->sd_vid,		"Vendor",
8107 	    KSTAT_DATA_CHAR);
8108 	kstat_named_init(&stp->sd_pid,		"Product",
8109 	    KSTAT_DATA_CHAR);
8110 	kstat_named_init(&stp->sd_revision,	"Revision",
8111 	    KSTAT_DATA_CHAR);
8112 	kstat_named_init(&stp->sd_serial,	"Serial No",
8113 	    KSTAT_DATA_CHAR);
8114 	kstat_named_init(&stp->sd_capacity,	"Size",
8115 	    KSTAT_DATA_ULONGLONG);
8116 	kstat_named_init(&stp->sd_rq_media_err,	"Media Error",
8117 	    KSTAT_DATA_UINT32);
8118 	kstat_named_init(&stp->sd_rq_ntrdy_err,	"Device Not Ready",
8119 	    KSTAT_DATA_UINT32);
8120 	kstat_named_init(&stp->sd_rq_nodev_err,	"No Device",
8121 	    KSTAT_DATA_UINT32);
8122 	kstat_named_init(&stp->sd_rq_recov_err,	"Recoverable",
8123 	    KSTAT_DATA_UINT32);
8124 	kstat_named_init(&stp->sd_rq_illrq_err,	"Illegal Request",
8125 	    KSTAT_DATA_UINT32);
8126 	kstat_named_init(&stp->sd_rq_pfa_err,	"Predictive Failure Analysis",
8127 	    KSTAT_DATA_UINT32);
8128 
8129 	un->un_errstats->ks_private = un;
8130 	un->un_errstats->ks_update  = nulldev;
8131 
8132 	kstat_install(un->un_errstats);
8133 }
8134 
8135 
8136 /*
8137  *    Function: sd_set_errstats
8138  *
8139  * Description: This routine sets the value of the vendor id, product id,
8140  *		revision, serial number, and capacity device error stats.
8141  *
8142  *		Note: During attach the stats are instantiated first so they are
8143  *		available for attach-time routines that utilize the driver
8144  *		iopath to send commands to the device. The stats are initialized
8145  *		separately so data obtained during some attach-time routines is
8146  *		available. (4362483)
8147  *
8148  *   Arguments: un - driver soft state (unit) structure
8149  *
8150  *     Context: Kernel thread context
8151  */
8152 
8153 static void
8154 sd_set_errstats(struct sd_lun *un)
8155 {
8156 	struct	sd_errstats	*stp;
8157 
8158 	ASSERT(un != NULL);
8159 	ASSERT(un->un_errstats != NULL);
8160 	stp = (struct sd_errstats *)un->un_errstats->ks_data;
8161 	ASSERT(stp != NULL);
8162 	(void) strncpy(stp->sd_vid.value.c, un->un_sd->sd_inq->inq_vid, 8);
8163 	(void) strncpy(stp->sd_pid.value.c, un->un_sd->sd_inq->inq_pid, 16);
8164 	(void) strncpy(stp->sd_revision.value.c,
8165 	    un->un_sd->sd_inq->inq_revision, 4);
8166 
8167 	/*
8168 	 * All the errstats are persistent across detach/attach,
8169 	 * so reset all the errstats here in case of the hot
8170 	 * replacement of disk drives, except for not changed
8171 	 * Sun qualified drives.
8172 	 */
8173 	if ((bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) != 0) ||
8174 	    (bcmp(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8175 	    sizeof (SD_INQUIRY(un)->inq_serial)) != 0)) {
8176 		stp->sd_softerrs.value.ui32 = 0;
8177 		stp->sd_harderrs.value.ui32 = 0;
8178 		stp->sd_transerrs.value.ui32 = 0;
8179 		stp->sd_rq_media_err.value.ui32 = 0;
8180 		stp->sd_rq_ntrdy_err.value.ui32 = 0;
8181 		stp->sd_rq_nodev_err.value.ui32 = 0;
8182 		stp->sd_rq_recov_err.value.ui32 = 0;
8183 		stp->sd_rq_illrq_err.value.ui32 = 0;
8184 		stp->sd_rq_pfa_err.value.ui32 = 0;
8185 	}
8186 
8187 	/*
8188 	 * Set the "Serial No" kstat for Sun qualified drives (indicated by
8189 	 * "SUN" in bytes 25-27 of the inquiry data (bytes 9-11 of the pid)
8190 	 * (4376302))
8191 	 */
8192 	if (bcmp(&SD_INQUIRY(un)->inq_pid[9], "SUN", 3) == 0) {
8193 		bcopy(&SD_INQUIRY(un)->inq_serial, stp->sd_serial.value.c,
8194 		    sizeof (SD_INQUIRY(un)->inq_serial));
8195 	}
8196 
8197 	if (un->un_f_blockcount_is_valid != TRUE) {
8198 		/*
8199 		 * Set capacity error stat to 0 for no media. This ensures
8200 		 * a valid capacity is displayed in response to 'iostat -E'
8201 		 * when no media is present in the device.
8202 		 */
8203 		stp->sd_capacity.value.ui64 = 0;
8204 	} else {
8205 		/*
8206 		 * Multiply un_blockcount by un->un_sys_blocksize to get
8207 		 * capacity.
8208 		 *
8209 		 * Note: for non-512 blocksize devices "un_blockcount" has been
8210 		 * "scaled" in sd_send_scsi_READ_CAPACITY by multiplying by
8211 		 * (un_tgt_blocksize / un->un_sys_blocksize).
8212 		 */
8213 		stp->sd_capacity.value.ui64 = (uint64_t)
8214 		    ((uint64_t)un->un_blockcount * un->un_sys_blocksize);
8215 	}
8216 }
8217 
8218 
8219 /*
8220  *    Function: sd_set_pstats
8221  *
8222  * Description: This routine instantiates and initializes the partition
8223  *              stats for each partition with more than zero blocks.
8224  *		(4363169)
8225  *
8226  *   Arguments: un - driver soft state (unit) structure
8227  *
8228  *     Context: Kernel thread context
8229  */
8230 
8231 static void
8232 sd_set_pstats(struct sd_lun *un)
8233 {
8234 	char	kstatname[KSTAT_STRLEN];
8235 	int	instance;
8236 	int	i;
8237 	diskaddr_t	nblks = 0;
8238 	char	*partname = NULL;
8239 
8240 	ASSERT(un != NULL);
8241 
8242 	instance = ddi_get_instance(SD_DEVINFO(un));
8243 
8244 	/* Note:x86: is this a VTOC8/VTOC16 difference? */
8245 	for (i = 0; i < NSDMAP; i++) {
8246 
8247 		if (cmlb_partinfo(un->un_cmlbhandle, i,
8248 		    &nblks, NULL, &partname, NULL, (void *)SD_PATH_DIRECT) != 0)
8249 			continue;
8250 		mutex_enter(SD_MUTEX(un));
8251 
8252 		if ((un->un_pstats[i] == NULL) &&
8253 		    (nblks != 0)) {
8254 
8255 			(void) snprintf(kstatname, sizeof (kstatname),
8256 			    "%s%d,%s", sd_label, instance,
8257 			    partname);
8258 
8259 			un->un_pstats[i] = kstat_create(sd_label,
8260 			    instance, kstatname, "partition", KSTAT_TYPE_IO,
8261 			    1, KSTAT_FLAG_PERSISTENT);
8262 			if (un->un_pstats[i] != NULL) {
8263 				un->un_pstats[i]->ks_lock = SD_MUTEX(un);
8264 				kstat_install(un->un_pstats[i]);
8265 			}
8266 		}
8267 		mutex_exit(SD_MUTEX(un));
8268 	}
8269 }
8270 
8271 
8272 #if (defined(__fibre))
8273 /*
8274  *    Function: sd_init_event_callbacks
8275  *
8276  * Description: This routine initializes the insertion and removal event
8277  *		callbacks. (fibre only)
8278  *
8279  *   Arguments: un - driver soft state (unit) structure
8280  *
8281  *     Context: Kernel thread context
8282  */
8283 
8284 static void
8285 sd_init_event_callbacks(struct sd_lun *un)
8286 {
8287 	ASSERT(un != NULL);
8288 
8289 	if ((un->un_insert_event == NULL) &&
8290 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_INSERT_EVENT,
8291 	    &un->un_insert_event) == DDI_SUCCESS)) {
8292 		/*
8293 		 * Add the callback for an insertion event
8294 		 */
8295 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8296 		    un->un_insert_event, sd_event_callback, (void *)un,
8297 		    &(un->un_insert_cb_id));
8298 	}
8299 
8300 	if ((un->un_remove_event == NULL) &&
8301 	    (ddi_get_eventcookie(SD_DEVINFO(un), FCAL_REMOVE_EVENT,
8302 	    &un->un_remove_event) == DDI_SUCCESS)) {
8303 		/*
8304 		 * Add the callback for a removal event
8305 		 */
8306 		(void) ddi_add_event_handler(SD_DEVINFO(un),
8307 		    un->un_remove_event, sd_event_callback, (void *)un,
8308 		    &(un->un_remove_cb_id));
8309 	}
8310 }
8311 
8312 
8313 /*
8314  *    Function: sd_event_callback
8315  *
8316  * Description: This routine handles insert/remove events (photon). The
8317  *		state is changed to OFFLINE which can be used to supress
8318  *		error msgs. (fibre only)
8319  *
8320  *   Arguments: un - driver soft state (unit) structure
8321  *
8322  *     Context: Callout thread context
8323  */
8324 /* ARGSUSED */
8325 static void
8326 sd_event_callback(dev_info_t *dip, ddi_eventcookie_t event, void *arg,
8327     void *bus_impldata)
8328 {
8329 	struct sd_lun *un = (struct sd_lun *)arg;
8330 
8331 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_insert_event));
8332 	if (event == un->un_insert_event) {
8333 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: insert event");
8334 		mutex_enter(SD_MUTEX(un));
8335 		if (un->un_state == SD_STATE_OFFLINE) {
8336 			if (un->un_last_state != SD_STATE_SUSPENDED) {
8337 				un->un_state = un->un_last_state;
8338 			} else {
8339 				/*
8340 				 * We have gone through SUSPEND/RESUME while
8341 				 * we were offline. Restore the last state
8342 				 */
8343 				un->un_state = un->un_save_state;
8344 			}
8345 		}
8346 		mutex_exit(SD_MUTEX(un));
8347 
8348 	_NOTE(DATA_READABLE_WITHOUT_LOCK(sd_lun::un_remove_event));
8349 	} else if (event == un->un_remove_event) {
8350 		SD_TRACE(SD_LOG_COMMON, un, "sd_event_callback: remove event");
8351 		mutex_enter(SD_MUTEX(un));
8352 		/*
8353 		 * We need to handle an event callback that occurs during
8354 		 * the suspend operation, since we don't prevent it.
8355 		 */
8356 		if (un->un_state != SD_STATE_OFFLINE) {
8357 			if (un->un_state != SD_STATE_SUSPENDED) {
8358 				New_state(un, SD_STATE_OFFLINE);
8359 			} else {
8360 				un->un_last_state = SD_STATE_OFFLINE;
8361 			}
8362 		}
8363 		mutex_exit(SD_MUTEX(un));
8364 	} else {
8365 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
8366 		    "!Unknown event\n");
8367 	}
8368 
8369 }
8370 #endif
8371 
8372 /*
8373  *    Function: sd_cache_control()
8374  *
8375  * Description: This routine is the driver entry point for setting
8376  *		read and write caching by modifying the WCE (write cache
8377  *		enable) and RCD (read cache disable) bits of mode
8378  *		page 8 (MODEPAGE_CACHING).
8379  *
8380  *   Arguments: un - driver soft state (unit) structure
8381  *		rcd_flag - flag for controlling the read cache
8382  *		wce_flag - flag for controlling the write cache
8383  *
8384  * Return Code: EIO
8385  *		code returned by sd_send_scsi_MODE_SENSE and
8386  *		sd_send_scsi_MODE_SELECT
8387  *
8388  *     Context: Kernel Thread
8389  */
8390 
8391 static int
8392 sd_cache_control(struct sd_lun *un, int rcd_flag, int wce_flag)
8393 {
8394 	struct mode_caching	*mode_caching_page;
8395 	uchar_t			*header;
8396 	size_t			buflen;
8397 	int			hdrlen;
8398 	int			bd_len;
8399 	int			rval = 0;
8400 	struct mode_header_grp2	*mhp;
8401 
8402 	ASSERT(un != NULL);
8403 
8404 	/*
8405 	 * Do a test unit ready, otherwise a mode sense may not work if this
8406 	 * is the first command sent to the device after boot.
8407 	 */
8408 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
8409 
8410 	if (un->un_f_cfg_is_atapi == TRUE) {
8411 		hdrlen = MODE_HEADER_LENGTH_GRP2;
8412 	} else {
8413 		hdrlen = MODE_HEADER_LENGTH;
8414 	}
8415 
8416 	/*
8417 	 * Allocate memory for the retrieved mode page and its headers.  Set
8418 	 * a pointer to the page itself.  Use mode_cache_scsi3 to insure
8419 	 * we get all of the mode sense data otherwise, the mode select
8420 	 * will fail.  mode_cache_scsi3 is a superset of mode_caching.
8421 	 */
8422 	buflen = hdrlen + MODE_BLK_DESC_LENGTH +
8423 	    sizeof (struct mode_cache_scsi3);
8424 
8425 	header = kmem_zalloc(buflen, KM_SLEEP);
8426 
8427 	/* Get the information from the device. */
8428 	if (un->un_f_cfg_is_atapi == TRUE) {
8429 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
8430 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8431 	} else {
8432 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
8433 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8434 	}
8435 	if (rval != 0) {
8436 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
8437 		    "sd_cache_control: Mode Sense Failed\n");
8438 		kmem_free(header, buflen);
8439 		return (rval);
8440 	}
8441 
8442 	/*
8443 	 * Determine size of Block Descriptors in order to locate
8444 	 * the mode page data. ATAPI devices return 0, SCSI devices
8445 	 * should return MODE_BLK_DESC_LENGTH.
8446 	 */
8447 	if (un->un_f_cfg_is_atapi == TRUE) {
8448 		mhp	= (struct mode_header_grp2 *)header;
8449 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
8450 	} else {
8451 		bd_len  = ((struct mode_header *)header)->bdesc_length;
8452 	}
8453 
8454 	if (bd_len > MODE_BLK_DESC_LENGTH) {
8455 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
8456 		    "sd_cache_control: Mode Sense returned invalid "
8457 		    "block descriptor length\n");
8458 		kmem_free(header, buflen);
8459 		return (EIO);
8460 	}
8461 
8462 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
8463 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
8464 		SD_ERROR(SD_LOG_COMMON, un, "sd_cache_control: Mode Sense"
8465 		    " caching page code mismatch %d\n",
8466 		    mode_caching_page->mode_page.code);
8467 		kmem_free(header, buflen);
8468 		return (EIO);
8469 	}
8470 
8471 	/* Check the relevant bits on successful mode sense. */
8472 	if ((mode_caching_page->rcd && rcd_flag == SD_CACHE_ENABLE) ||
8473 	    (!mode_caching_page->rcd && rcd_flag == SD_CACHE_DISABLE) ||
8474 	    (mode_caching_page->wce && wce_flag == SD_CACHE_DISABLE) ||
8475 	    (!mode_caching_page->wce && wce_flag == SD_CACHE_ENABLE)) {
8476 
8477 		size_t sbuflen;
8478 		uchar_t save_pg;
8479 
8480 		/*
8481 		 * Construct select buffer length based on the
8482 		 * length of the sense data returned.
8483 		 */
8484 		sbuflen =  hdrlen + MODE_BLK_DESC_LENGTH +
8485 		    sizeof (struct mode_page) +
8486 		    (int)mode_caching_page->mode_page.length;
8487 
8488 		/*
8489 		 * Set the caching bits as requested.
8490 		 */
8491 		if (rcd_flag == SD_CACHE_ENABLE)
8492 			mode_caching_page->rcd = 0;
8493 		else if (rcd_flag == SD_CACHE_DISABLE)
8494 			mode_caching_page->rcd = 1;
8495 
8496 		if (wce_flag == SD_CACHE_ENABLE)
8497 			mode_caching_page->wce = 1;
8498 		else if (wce_flag == SD_CACHE_DISABLE)
8499 			mode_caching_page->wce = 0;
8500 
8501 		/*
8502 		 * Save the page if the mode sense says the
8503 		 * drive supports it.
8504 		 */
8505 		save_pg = mode_caching_page->mode_page.ps ?
8506 		    SD_SAVE_PAGE : SD_DONTSAVE_PAGE;
8507 
8508 		/* Clear reserved bits before mode select. */
8509 		mode_caching_page->mode_page.ps = 0;
8510 
8511 		/*
8512 		 * Clear out mode header for mode select.
8513 		 * The rest of the retrieved page will be reused.
8514 		 */
8515 		bzero(header, hdrlen);
8516 
8517 		if (un->un_f_cfg_is_atapi == TRUE) {
8518 			mhp = (struct mode_header_grp2 *)header;
8519 			mhp->bdesc_length_hi = bd_len >> 8;
8520 			mhp->bdesc_length_lo = (uchar_t)bd_len & 0xff;
8521 		} else {
8522 			((struct mode_header *)header)->bdesc_length = bd_len;
8523 		}
8524 
8525 		/* Issue mode select to change the cache settings */
8526 		if (un->un_f_cfg_is_atapi == TRUE) {
8527 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, header,
8528 			    sbuflen, save_pg, SD_PATH_DIRECT);
8529 		} else {
8530 			rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, header,
8531 			    sbuflen, save_pg, SD_PATH_DIRECT);
8532 		}
8533 	}
8534 
8535 	kmem_free(header, buflen);
8536 	return (rval);
8537 }
8538 
8539 
8540 /*
8541  *    Function: sd_get_write_cache_enabled()
8542  *
8543  * Description: This routine is the driver entry point for determining if
8544  *		write caching is enabled.  It examines the WCE (write cache
8545  *		enable) bits of mode page 8 (MODEPAGE_CACHING).
8546  *
8547  *   Arguments: un - driver soft state (unit) structure
8548  *		is_enabled - pointer to int where write cache enabled state
8549  *		is returned (non-zero -> write cache enabled)
8550  *
8551  *
8552  * Return Code: EIO
8553  *		code returned by sd_send_scsi_MODE_SENSE
8554  *
8555  *     Context: Kernel Thread
8556  *
8557  * NOTE: If ioctl is added to disable write cache, this sequence should
8558  * be followed so that no locking is required for accesses to
8559  * un->un_f_write_cache_enabled:
8560  * 	do mode select to clear wce
8561  * 	do synchronize cache to flush cache
8562  * 	set un->un_f_write_cache_enabled = FALSE
8563  *
8564  * Conversely, an ioctl to enable the write cache should be done
8565  * in this order:
8566  * 	set un->un_f_write_cache_enabled = TRUE
8567  * 	do mode select to set wce
8568  */
8569 
8570 static int
8571 sd_get_write_cache_enabled(struct sd_lun *un, int *is_enabled)
8572 {
8573 	struct mode_caching	*mode_caching_page;
8574 	uchar_t			*header;
8575 	size_t			buflen;
8576 	int			hdrlen;
8577 	int			bd_len;
8578 	int			rval = 0;
8579 
8580 	ASSERT(un != NULL);
8581 	ASSERT(is_enabled != NULL);
8582 
8583 	/* in case of error, flag as enabled */
8584 	*is_enabled = TRUE;
8585 
8586 	/*
8587 	 * Do a test unit ready, otherwise a mode sense may not work if this
8588 	 * is the first command sent to the device after boot.
8589 	 */
8590 	(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
8591 
8592 	if (un->un_f_cfg_is_atapi == TRUE) {
8593 		hdrlen = MODE_HEADER_LENGTH_GRP2;
8594 	} else {
8595 		hdrlen = MODE_HEADER_LENGTH;
8596 	}
8597 
8598 	/*
8599 	 * Allocate memory for the retrieved mode page and its headers.  Set
8600 	 * a pointer to the page itself.
8601 	 */
8602 	buflen = hdrlen + MODE_BLK_DESC_LENGTH + sizeof (struct mode_caching);
8603 	header = kmem_zalloc(buflen, KM_SLEEP);
8604 
8605 	/* Get the information from the device. */
8606 	if (un->un_f_cfg_is_atapi == TRUE) {
8607 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, header, buflen,
8608 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8609 	} else {
8610 		rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, header, buflen,
8611 		    MODEPAGE_CACHING, SD_PATH_DIRECT);
8612 	}
8613 	if (rval != 0) {
8614 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
8615 		    "sd_get_write_cache_enabled: Mode Sense Failed\n");
8616 		kmem_free(header, buflen);
8617 		return (rval);
8618 	}
8619 
8620 	/*
8621 	 * Determine size of Block Descriptors in order to locate
8622 	 * the mode page data. ATAPI devices return 0, SCSI devices
8623 	 * should return MODE_BLK_DESC_LENGTH.
8624 	 */
8625 	if (un->un_f_cfg_is_atapi == TRUE) {
8626 		struct mode_header_grp2	*mhp;
8627 		mhp	= (struct mode_header_grp2 *)header;
8628 		bd_len  = (mhp->bdesc_length_hi << 8) | mhp->bdesc_length_lo;
8629 	} else {
8630 		bd_len  = ((struct mode_header *)header)->bdesc_length;
8631 	}
8632 
8633 	if (bd_len > MODE_BLK_DESC_LENGTH) {
8634 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
8635 		    "sd_get_write_cache_enabled: Mode Sense returned invalid "
8636 		    "block descriptor length\n");
8637 		kmem_free(header, buflen);
8638 		return (EIO);
8639 	}
8640 
8641 	mode_caching_page = (struct mode_caching *)(header + hdrlen + bd_len);
8642 	if (mode_caching_page->mode_page.code != MODEPAGE_CACHING) {
8643 		SD_ERROR(SD_LOG_COMMON, un, "sd_cache_control: Mode Sense"
8644 		    " caching page code mismatch %d\n",
8645 		    mode_caching_page->mode_page.code);
8646 		kmem_free(header, buflen);
8647 		return (EIO);
8648 	}
8649 	*is_enabled = mode_caching_page->wce;
8650 
8651 	kmem_free(header, buflen);
8652 	return (0);
8653 }
8654 
8655 /*
8656  *    Function: sd_get_nv_sup()
8657  *
8658  * Description: This routine is the driver entry point for
8659  * determining whether non-volatile cache is supported. This
8660  * determination process works as follows:
8661  *
8662  * 1. sd first queries sd.conf on whether
8663  * suppress_cache_flush bit is set for this device.
8664  *
8665  * 2. if not there, then queries the internal disk table.
8666  *
8667  * 3. if either sd.conf or internal disk table specifies
8668  * cache flush be suppressed, we don't bother checking
8669  * NV_SUP bit.
8670  *
8671  * If SUPPRESS_CACHE_FLUSH bit is not set to 1, sd queries
8672  * the optional INQUIRY VPD page 0x86. If the device
8673  * supports VPD page 0x86, sd examines the NV_SUP
8674  * (non-volatile cache support) bit in the INQUIRY VPD page
8675  * 0x86:
8676  *   o If NV_SUP bit is set, sd assumes the device has a
8677  *   non-volatile cache and set the
8678  *   un_f_sync_nv_supported to TRUE.
8679  *   o Otherwise cache is not non-volatile,
8680  *   un_f_sync_nv_supported is set to FALSE.
8681  *
8682  * Arguments: un - driver soft state (unit) structure
8683  *
8684  * Return Code:
8685  *
8686  *     Context: Kernel Thread
8687  */
8688 
8689 static void
8690 sd_get_nv_sup(struct sd_lun *un)
8691 {
8692 	int		rval		= 0;
8693 	uchar_t		*inq86		= NULL;
8694 	size_t		inq86_len	= MAX_INQUIRY_SIZE;
8695 	size_t		inq86_resid	= 0;
8696 	struct		dk_callback *dkc;
8697 
8698 	ASSERT(un != NULL);
8699 
8700 	mutex_enter(SD_MUTEX(un));
8701 
8702 	/*
8703 	 * Be conservative on the device's support of
8704 	 * SYNC_NV bit: un_f_sync_nv_supported is
8705 	 * initialized to be false.
8706 	 */
8707 	un->un_f_sync_nv_supported = FALSE;
8708 
8709 	/*
8710 	 * If either sd.conf or internal disk table
8711 	 * specifies cache flush be suppressed, then
8712 	 * we don't bother checking NV_SUP bit.
8713 	 */
8714 	if (un->un_f_suppress_cache_flush == TRUE) {
8715 		mutex_exit(SD_MUTEX(un));
8716 		return;
8717 	}
8718 
8719 	if (sd_check_vpd_page_support(un) == 0 &&
8720 	    un->un_vpd_page_mask & SD_VPD_EXTENDED_DATA_PG) {
8721 		mutex_exit(SD_MUTEX(un));
8722 		/* collect page 86 data if available */
8723 		inq86 = kmem_zalloc(inq86_len, KM_SLEEP);
8724 		rval = sd_send_scsi_INQUIRY(un, inq86, inq86_len,
8725 		    0x01, 0x86, &inq86_resid);
8726 
8727 		if (rval == 0 && (inq86_len - inq86_resid > 6)) {
8728 			SD_TRACE(SD_LOG_COMMON, un,
8729 			    "sd_get_nv_sup: \
8730 			    successfully get VPD page: %x \
8731 			    PAGE LENGTH: %x BYTE 6: %x\n",
8732 			    inq86[1], inq86[3], inq86[6]);
8733 
8734 			mutex_enter(SD_MUTEX(un));
8735 			/*
8736 			 * check the value of NV_SUP bit: only if the device
8737 			 * reports NV_SUP bit to be 1, the
8738 			 * un_f_sync_nv_supported bit will be set to true.
8739 			 */
8740 			if (inq86[6] & SD_VPD_NV_SUP) {
8741 				un->un_f_sync_nv_supported = TRUE;
8742 			}
8743 			mutex_exit(SD_MUTEX(un));
8744 		}
8745 		kmem_free(inq86, inq86_len);
8746 	} else {
8747 		mutex_exit(SD_MUTEX(un));
8748 	}
8749 
8750 	/*
8751 	 * Send a SYNC CACHE command to check whether
8752 	 * SYNC_NV bit is supported. This command should have
8753 	 * un_f_sync_nv_supported set to correct value.
8754 	 */
8755 	mutex_enter(SD_MUTEX(un));
8756 	if (un->un_f_sync_nv_supported) {
8757 		mutex_exit(SD_MUTEX(un));
8758 		dkc = kmem_zalloc(sizeof (struct dk_callback), KM_SLEEP);
8759 		dkc->dkc_flag = FLUSH_VOLATILE;
8760 		(void) sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
8761 
8762 		/*
8763 		 * Send a TEST UNIT READY command to the device. This should
8764 		 * clear any outstanding UNIT ATTENTION that may be present.
8765 		 */
8766 		(void) sd_send_scsi_TEST_UNIT_READY(un, SD_DONT_RETRY_TUR);
8767 
8768 		kmem_free(dkc, sizeof (struct dk_callback));
8769 	} else {
8770 		mutex_exit(SD_MUTEX(un));
8771 	}
8772 
8773 	SD_TRACE(SD_LOG_COMMON, un, "sd_get_nv_sup: \
8774 	    un_f_suppress_cache_flush is set to %d\n",
8775 	    un->un_f_suppress_cache_flush);
8776 }
8777 
8778 /*
8779  *    Function: sd_make_device
8780  *
8781  * Description: Utility routine to return the Solaris device number from
8782  *		the data in the device's dev_info structure.
8783  *
8784  * Return Code: The Solaris device number
8785  *
8786  *     Context: Any
8787  */
8788 
8789 static dev_t
8790 sd_make_device(dev_info_t *devi)
8791 {
8792 	return (makedevice(ddi_name_to_major(ddi_get_name(devi)),
8793 	    ddi_get_instance(devi) << SDUNIT_SHIFT));
8794 }
8795 
8796 
8797 /*
8798  *    Function: sd_pm_entry
8799  *
8800  * Description: Called at the start of a new command to manage power
8801  *		and busy status of a device. This includes determining whether
8802  *		the current power state of the device is sufficient for
8803  *		performing the command or whether it must be changed.
8804  *		The PM framework is notified appropriately.
8805  *		Only with a return status of DDI_SUCCESS will the
8806  *		component be busy to the framework.
8807  *
8808  *		All callers of sd_pm_entry must check the return status
8809  *		and only call sd_pm_exit it it was DDI_SUCCESS. A status
8810  *		of DDI_FAILURE indicates the device failed to power up.
8811  *		In this case un_pm_count has been adjusted so the result
8812  *		on exit is still powered down, ie. count is less than 0.
8813  *		Calling sd_pm_exit with this count value hits an ASSERT.
8814  *
8815  * Return Code: DDI_SUCCESS or DDI_FAILURE
8816  *
8817  *     Context: Kernel thread context.
8818  */
8819 
8820 static int
8821 sd_pm_entry(struct sd_lun *un)
8822 {
8823 	int return_status = DDI_SUCCESS;
8824 
8825 	ASSERT(!mutex_owned(SD_MUTEX(un)));
8826 	ASSERT(!mutex_owned(&un->un_pm_mutex));
8827 
8828 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: entry\n");
8829 
8830 	if (un->un_f_pm_is_enabled == FALSE) {
8831 		SD_TRACE(SD_LOG_IO_PM, un,
8832 		    "sd_pm_entry: exiting, PM not enabled\n");
8833 		return (return_status);
8834 	}
8835 
8836 	/*
8837 	 * Just increment a counter if PM is enabled. On the transition from
8838 	 * 0 ==> 1, mark the device as busy.  The iodone side will decrement
8839 	 * the count with each IO and mark the device as idle when the count
8840 	 * hits 0.
8841 	 *
8842 	 * If the count is less than 0 the device is powered down. If a powered
8843 	 * down device is successfully powered up then the count must be
8844 	 * incremented to reflect the power up. Note that it'll get incremented
8845 	 * a second time to become busy.
8846 	 *
8847 	 * Because the following has the potential to change the device state
8848 	 * and must release the un_pm_mutex to do so, only one thread can be
8849 	 * allowed through at a time.
8850 	 */
8851 
8852 	mutex_enter(&un->un_pm_mutex);
8853 	while (un->un_pm_busy == TRUE) {
8854 		cv_wait(&un->un_pm_busy_cv, &un->un_pm_mutex);
8855 	}
8856 	un->un_pm_busy = TRUE;
8857 
8858 	if (un->un_pm_count < 1) {
8859 
8860 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_entry: busy component\n");
8861 
8862 		/*
8863 		 * Indicate we are now busy so the framework won't attempt to
8864 		 * power down the device. This call will only fail if either
8865 		 * we passed a bad component number or the device has no
8866 		 * components. Neither of these should ever happen.
8867 		 */
8868 		mutex_exit(&un->un_pm_mutex);
8869 		return_status = pm_busy_component(SD_DEVINFO(un), 0);
8870 		ASSERT(return_status == DDI_SUCCESS);
8871 
8872 		mutex_enter(&un->un_pm_mutex);
8873 
8874 		if (un->un_pm_count < 0) {
8875 			mutex_exit(&un->un_pm_mutex);
8876 
8877 			SD_TRACE(SD_LOG_IO_PM, un,
8878 			    "sd_pm_entry: power up component\n");
8879 
8880 			/*
8881 			 * pm_raise_power will cause sdpower to be called
8882 			 * which brings the device power level to the
8883 			 * desired state, ON in this case. If successful,
8884 			 * un_pm_count and un_power_level will be updated
8885 			 * appropriately.
8886 			 */
8887 			return_status = pm_raise_power(SD_DEVINFO(un), 0,
8888 			    SD_SPINDLE_ON);
8889 
8890 			mutex_enter(&un->un_pm_mutex);
8891 
8892 			if (return_status != DDI_SUCCESS) {
8893 				/*
8894 				 * Power up failed.
8895 				 * Idle the device and adjust the count
8896 				 * so the result on exit is that we're
8897 				 * still powered down, ie. count is less than 0.
8898 				 */
8899 				SD_TRACE(SD_LOG_IO_PM, un,
8900 				    "sd_pm_entry: power up failed,"
8901 				    " idle the component\n");
8902 
8903 				(void) pm_idle_component(SD_DEVINFO(un), 0);
8904 				un->un_pm_count--;
8905 			} else {
8906 				/*
8907 				 * Device is powered up, verify the
8908 				 * count is non-negative.
8909 				 * This is debug only.
8910 				 */
8911 				ASSERT(un->un_pm_count == 0);
8912 			}
8913 		}
8914 
8915 		if (return_status == DDI_SUCCESS) {
8916 			/*
8917 			 * For performance, now that the device has been tagged
8918 			 * as busy, and it's known to be powered up, update the
8919 			 * chain types to use jump tables that do not include
8920 			 * pm. This significantly lowers the overhead and
8921 			 * therefore improves performance.
8922 			 */
8923 
8924 			mutex_exit(&un->un_pm_mutex);
8925 			mutex_enter(SD_MUTEX(un));
8926 			SD_TRACE(SD_LOG_IO_PM, un,
8927 			    "sd_pm_entry: changing uscsi_chain_type from %d\n",
8928 			    un->un_uscsi_chain_type);
8929 
8930 			if (un->un_f_non_devbsize_supported) {
8931 				un->un_buf_chain_type =
8932 				    SD_CHAIN_INFO_RMMEDIA_NO_PM;
8933 			} else {
8934 				un->un_buf_chain_type =
8935 				    SD_CHAIN_INFO_DISK_NO_PM;
8936 			}
8937 			un->un_uscsi_chain_type = SD_CHAIN_INFO_USCSI_CMD_NO_PM;
8938 
8939 			SD_TRACE(SD_LOG_IO_PM, un,
8940 			    "             changed  uscsi_chain_type to   %d\n",
8941 			    un->un_uscsi_chain_type);
8942 			mutex_exit(SD_MUTEX(un));
8943 			mutex_enter(&un->un_pm_mutex);
8944 
8945 			if (un->un_pm_idle_timeid == NULL) {
8946 				/* 300 ms. */
8947 				un->un_pm_idle_timeid =
8948 				    timeout(sd_pm_idletimeout_handler, un,
8949 				    (drv_usectohz((clock_t)300000)));
8950 				/*
8951 				 * Include an extra call to busy which keeps the
8952 				 * device busy with-respect-to the PM layer
8953 				 * until the timer fires, at which time it'll
8954 				 * get the extra idle call.
8955 				 */
8956 				(void) pm_busy_component(SD_DEVINFO(un), 0);
8957 			}
8958 		}
8959 	}
8960 	un->un_pm_busy = FALSE;
8961 	/* Next... */
8962 	cv_signal(&un->un_pm_busy_cv);
8963 
8964 	un->un_pm_count++;
8965 
8966 	SD_TRACE(SD_LOG_IO_PM, un,
8967 	    "sd_pm_entry: exiting, un_pm_count = %d\n", un->un_pm_count);
8968 
8969 	mutex_exit(&un->un_pm_mutex);
8970 
8971 	return (return_status);
8972 }
8973 
8974 
8975 /*
8976  *    Function: sd_pm_exit
8977  *
8978  * Description: Called at the completion of a command to manage busy
8979  *		status for the device. If the device becomes idle the
8980  *		PM framework is notified.
8981  *
8982  *     Context: Kernel thread context
8983  */
8984 
8985 static void
8986 sd_pm_exit(struct sd_lun *un)
8987 {
8988 	ASSERT(!mutex_owned(SD_MUTEX(un)));
8989 	ASSERT(!mutex_owned(&un->un_pm_mutex));
8990 
8991 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: entry\n");
8992 
8993 	/*
8994 	 * After attach the following flag is only read, so don't
8995 	 * take the penalty of acquiring a mutex for it.
8996 	 */
8997 	if (un->un_f_pm_is_enabled == TRUE) {
8998 
8999 		mutex_enter(&un->un_pm_mutex);
9000 		un->un_pm_count--;
9001 
9002 		SD_TRACE(SD_LOG_IO_PM, un,
9003 		    "sd_pm_exit: un_pm_count = %d\n", un->un_pm_count);
9004 
9005 		ASSERT(un->un_pm_count >= 0);
9006 		if (un->un_pm_count == 0) {
9007 			mutex_exit(&un->un_pm_mutex);
9008 
9009 			SD_TRACE(SD_LOG_IO_PM, un,
9010 			    "sd_pm_exit: idle component\n");
9011 
9012 			(void) pm_idle_component(SD_DEVINFO(un), 0);
9013 
9014 		} else {
9015 			mutex_exit(&un->un_pm_mutex);
9016 		}
9017 	}
9018 
9019 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_exit: exiting\n");
9020 }
9021 
9022 
9023 /*
9024  *    Function: sdopen
9025  *
9026  * Description: Driver's open(9e) entry point function.
9027  *
9028  *   Arguments: dev_i   - pointer to device number
9029  *		flag    - how to open file (FEXCL, FNDELAY, FREAD, FWRITE)
9030  *		otyp    - open type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9031  *		cred_p  - user credential pointer
9032  *
9033  * Return Code: EINVAL
9034  *		ENXIO
9035  *		EIO
9036  *		EROFS
9037  *		EBUSY
9038  *
9039  *     Context: Kernel thread context
9040  */
9041 /* ARGSUSED */
9042 static int
9043 sdopen(dev_t *dev_p, int flag, int otyp, cred_t *cred_p)
9044 {
9045 	struct sd_lun	*un;
9046 	int		nodelay;
9047 	int		part;
9048 	uint64_t	partmask;
9049 	int		instance;
9050 	dev_t		dev;
9051 	int		rval = EIO;
9052 	diskaddr_t	nblks = 0;
9053 	diskaddr_t	label_cap;
9054 
9055 	/* Validate the open type */
9056 	if (otyp >= OTYPCNT) {
9057 		return (EINVAL);
9058 	}
9059 
9060 	dev = *dev_p;
9061 	instance = SDUNIT(dev);
9062 	mutex_enter(&sd_detach_mutex);
9063 
9064 	/*
9065 	 * Fail the open if there is no softstate for the instance, or
9066 	 * if another thread somewhere is trying to detach the instance.
9067 	 */
9068 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
9069 	    (un->un_detach_count != 0)) {
9070 		mutex_exit(&sd_detach_mutex);
9071 		/*
9072 		 * The probe cache only needs to be cleared when open (9e) fails
9073 		 * with ENXIO (4238046).
9074 		 */
9075 		/*
9076 		 * un-conditionally clearing probe cache is ok with
9077 		 * separate sd/ssd binaries
9078 		 * x86 platform can be an issue with both parallel
9079 		 * and fibre in 1 binary
9080 		 */
9081 		sd_scsi_clear_probe_cache();
9082 		return (ENXIO);
9083 	}
9084 
9085 	/*
9086 	 * The un_layer_count is to prevent another thread in specfs from
9087 	 * trying to detach the instance, which can happen when we are
9088 	 * called from a higher-layer driver instead of thru specfs.
9089 	 * This will not be needed when DDI provides a layered driver
9090 	 * interface that allows specfs to know that an instance is in
9091 	 * use by a layered driver & should not be detached.
9092 	 *
9093 	 * Note: the semantics for layered driver opens are exactly one
9094 	 * close for every open.
9095 	 */
9096 	if (otyp == OTYP_LYR) {
9097 		un->un_layer_count++;
9098 	}
9099 
9100 	/*
9101 	 * Keep a count of the current # of opens in progress. This is because
9102 	 * some layered drivers try to call us as a regular open. This can
9103 	 * cause problems that we cannot prevent, however by keeping this count
9104 	 * we can at least keep our open and detach routines from racing against
9105 	 * each other under such conditions.
9106 	 */
9107 	un->un_opens_in_progress++;
9108 	mutex_exit(&sd_detach_mutex);
9109 
9110 	nodelay  = (flag & (FNDELAY | FNONBLOCK));
9111 	part	 = SDPART(dev);
9112 	partmask = 1 << part;
9113 
9114 	/*
9115 	 * We use a semaphore here in order to serialize
9116 	 * open and close requests on the device.
9117 	 */
9118 	sema_p(&un->un_semoclose);
9119 
9120 	mutex_enter(SD_MUTEX(un));
9121 
9122 	/*
9123 	 * All device accesses go thru sdstrategy() where we check
9124 	 * on suspend status but there could be a scsi_poll command,
9125 	 * which bypasses sdstrategy(), so we need to check pm
9126 	 * status.
9127 	 */
9128 
9129 	if (!nodelay) {
9130 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9131 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9132 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9133 		}
9134 
9135 		mutex_exit(SD_MUTEX(un));
9136 		if (sd_pm_entry(un) != DDI_SUCCESS) {
9137 			rval = EIO;
9138 			SD_ERROR(SD_LOG_OPEN_CLOSE, un,
9139 			    "sdopen: sd_pm_entry failed\n");
9140 			goto open_failed_with_pm;
9141 		}
9142 		mutex_enter(SD_MUTEX(un));
9143 	}
9144 
9145 	/* check for previous exclusive open */
9146 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: un=%p\n", (void *)un);
9147 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
9148 	    "sdopen: exclopen=%x, flag=%x, regopen=%x\n",
9149 	    un->un_exclopen, flag, un->un_ocmap.regopen[otyp]);
9150 
9151 	if (un->un_exclopen & (partmask)) {
9152 		goto excl_open_fail;
9153 	}
9154 
9155 	if (flag & FEXCL) {
9156 		int i;
9157 		if (un->un_ocmap.lyropen[part]) {
9158 			goto excl_open_fail;
9159 		}
9160 		for (i = 0; i < (OTYPCNT - 1); i++) {
9161 			if (un->un_ocmap.regopen[i] & (partmask)) {
9162 				goto excl_open_fail;
9163 			}
9164 		}
9165 	}
9166 
9167 	/*
9168 	 * Check the write permission if this is a removable media device,
9169 	 * NDELAY has not been set, and writable permission is requested.
9170 	 *
9171 	 * Note: If NDELAY was set and this is write-protected media the WRITE
9172 	 * attempt will fail with EIO as part of the I/O processing. This is a
9173 	 * more permissive implementation that allows the open to succeed and
9174 	 * WRITE attempts to fail when appropriate.
9175 	 */
9176 	if (un->un_f_chk_wp_open) {
9177 		if ((flag & FWRITE) && (!nodelay)) {
9178 			mutex_exit(SD_MUTEX(un));
9179 			/*
9180 			 * Defer the check for write permission on writable
9181 			 * DVD drive till sdstrategy and will not fail open even
9182 			 * if FWRITE is set as the device can be writable
9183 			 * depending upon the media and the media can change
9184 			 * after the call to open().
9185 			 */
9186 			if (un->un_f_dvdram_writable_device == FALSE) {
9187 				if (ISCD(un) || sr_check_wp(dev)) {
9188 				rval = EROFS;
9189 				mutex_enter(SD_MUTEX(un));
9190 				SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9191 				    "write to cd or write protected media\n");
9192 				goto open_fail;
9193 				}
9194 			}
9195 			mutex_enter(SD_MUTEX(un));
9196 		}
9197 	}
9198 
9199 	/*
9200 	 * If opening in NDELAY/NONBLOCK mode, just return.
9201 	 * Check if disk is ready and has a valid geometry later.
9202 	 */
9203 	if (!nodelay) {
9204 		mutex_exit(SD_MUTEX(un));
9205 		rval = sd_ready_and_valid(un);
9206 		mutex_enter(SD_MUTEX(un));
9207 		/*
9208 		 * Fail if device is not ready or if the number of disk
9209 		 * blocks is zero or negative for non CD devices.
9210 		 */
9211 
9212 		nblks = 0;
9213 
9214 		if (rval == SD_READY_VALID && (!ISCD(un))) {
9215 			/* if cmlb_partinfo fails, nblks remains 0 */
9216 			mutex_exit(SD_MUTEX(un));
9217 			(void) cmlb_partinfo(un->un_cmlbhandle, part, &nblks,
9218 			    NULL, NULL, NULL, (void *)SD_PATH_DIRECT);
9219 			mutex_enter(SD_MUTEX(un));
9220 		}
9221 
9222 		if ((rval != SD_READY_VALID) ||
9223 		    (!ISCD(un) && nblks <= 0)) {
9224 			rval = un->un_f_has_removable_media ? ENXIO : EIO;
9225 			SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9226 			    "device not ready or invalid disk block value\n");
9227 			goto open_fail;
9228 		}
9229 #if defined(__i386) || defined(__amd64)
9230 	} else {
9231 		uchar_t *cp;
9232 		/*
9233 		 * x86 requires special nodelay handling, so that p0 is
9234 		 * always defined and accessible.
9235 		 * Invalidate geometry only if device is not already open.
9236 		 */
9237 		cp = &un->un_ocmap.chkd[0];
9238 		while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9239 			if (*cp != (uchar_t)0) {
9240 				break;
9241 			}
9242 			cp++;
9243 		}
9244 		if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9245 			mutex_exit(SD_MUTEX(un));
9246 			cmlb_invalidate(un->un_cmlbhandle,
9247 			    (void *)SD_PATH_DIRECT);
9248 			mutex_enter(SD_MUTEX(un));
9249 		}
9250 
9251 #endif
9252 	}
9253 
9254 	if (otyp == OTYP_LYR) {
9255 		un->un_ocmap.lyropen[part]++;
9256 	} else {
9257 		un->un_ocmap.regopen[otyp] |= partmask;
9258 	}
9259 
9260 	/* Set up open and exclusive open flags */
9261 	if (flag & FEXCL) {
9262 		un->un_exclopen |= (partmask);
9263 	}
9264 
9265 	/*
9266 	 * If the lun is EFI labeled and lun capacity is greater than the
9267 	 * capacity contained in the label, log a sys-event to notify the
9268 	 * interested module.
9269 	 * To avoid an infinite loop of logging sys-event, we only log the
9270 	 * event when the lun is not opened in NDELAY mode. The event handler
9271 	 * should open the lun in NDELAY mode.
9272 	 */
9273 	if (!(flag & FNDELAY)) {
9274 		mutex_exit(SD_MUTEX(un));
9275 		if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
9276 		    (void*)SD_PATH_DIRECT) == 0) {
9277 			mutex_enter(SD_MUTEX(un));
9278 			if (un->un_f_blockcount_is_valid &&
9279 			    un->un_blockcount > label_cap) {
9280 				mutex_exit(SD_MUTEX(un));
9281 				sd_log_lun_expansion_event(un,
9282 				    (nodelay ? KM_NOSLEEP : KM_SLEEP));
9283 				mutex_enter(SD_MUTEX(un));
9284 			}
9285 		} else {
9286 			mutex_enter(SD_MUTEX(un));
9287 		}
9288 	}
9289 
9290 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: "
9291 	    "open of part %d type %d\n", part, otyp);
9292 
9293 	mutex_exit(SD_MUTEX(un));
9294 	if (!nodelay) {
9295 		sd_pm_exit(un);
9296 	}
9297 
9298 	sema_v(&un->un_semoclose);
9299 
9300 	mutex_enter(&sd_detach_mutex);
9301 	un->un_opens_in_progress--;
9302 	mutex_exit(&sd_detach_mutex);
9303 
9304 	SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdopen: exit success\n");
9305 	return (DDI_SUCCESS);
9306 
9307 excl_open_fail:
9308 	SD_ERROR(SD_LOG_OPEN_CLOSE, un, "sdopen: fail exclusive open\n");
9309 	rval = EBUSY;
9310 
9311 open_fail:
9312 	mutex_exit(SD_MUTEX(un));
9313 
9314 	/*
9315 	 * On a failed open we must exit the pm management.
9316 	 */
9317 	if (!nodelay) {
9318 		sd_pm_exit(un);
9319 	}
9320 open_failed_with_pm:
9321 	sema_v(&un->un_semoclose);
9322 
9323 	mutex_enter(&sd_detach_mutex);
9324 	un->un_opens_in_progress--;
9325 	if (otyp == OTYP_LYR) {
9326 		un->un_layer_count--;
9327 	}
9328 	mutex_exit(&sd_detach_mutex);
9329 
9330 	return (rval);
9331 }
9332 
9333 
9334 /*
9335  *    Function: sdclose
9336  *
9337  * Description: Driver's close(9e) entry point function.
9338  *
9339  *   Arguments: dev    - device number
9340  *		flag   - file status flag, informational only
9341  *		otyp   - close type (OTYP_BLK, OTYP_CHR, OTYP_LYR)
9342  *		cred_p - user credential pointer
9343  *
9344  * Return Code: ENXIO
9345  *
9346  *     Context: Kernel thread context
9347  */
9348 /* ARGSUSED */
9349 static int
9350 sdclose(dev_t dev, int flag, int otyp, cred_t *cred_p)
9351 {
9352 	struct sd_lun	*un;
9353 	uchar_t		*cp;
9354 	int		part;
9355 	int		nodelay;
9356 	int		rval = 0;
9357 
9358 	/* Validate the open type */
9359 	if (otyp >= OTYPCNT) {
9360 		return (ENXIO);
9361 	}
9362 
9363 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9364 		return (ENXIO);
9365 	}
9366 
9367 	part = SDPART(dev);
9368 	nodelay = flag & (FNDELAY | FNONBLOCK);
9369 
9370 	SD_TRACE(SD_LOG_OPEN_CLOSE, un,
9371 	    "sdclose: close of part %d type %d\n", part, otyp);
9372 
9373 	/*
9374 	 * We use a semaphore here in order to serialize
9375 	 * open and close requests on the device.
9376 	 */
9377 	sema_p(&un->un_semoclose);
9378 
9379 	mutex_enter(SD_MUTEX(un));
9380 
9381 	/* Don't proceed if power is being changed. */
9382 	while (un->un_state == SD_STATE_PM_CHANGING) {
9383 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9384 	}
9385 
9386 	if (un->un_exclopen & (1 << part)) {
9387 		un->un_exclopen &= ~(1 << part);
9388 	}
9389 
9390 	/* Update the open partition map */
9391 	if (otyp == OTYP_LYR) {
9392 		un->un_ocmap.lyropen[part] -= 1;
9393 	} else {
9394 		un->un_ocmap.regopen[otyp] &= ~(1 << part);
9395 	}
9396 
9397 	cp = &un->un_ocmap.chkd[0];
9398 	while (cp < &un->un_ocmap.chkd[OCSIZE]) {
9399 		if (*cp != NULL) {
9400 			break;
9401 		}
9402 		cp++;
9403 	}
9404 
9405 	if (cp == &un->un_ocmap.chkd[OCSIZE]) {
9406 		SD_TRACE(SD_LOG_OPEN_CLOSE, un, "sdclose: last close\n");
9407 
9408 		/*
9409 		 * We avoid persistance upon the last close, and set
9410 		 * the throttle back to the maximum.
9411 		 */
9412 		un->un_throttle = un->un_saved_throttle;
9413 
9414 		if (un->un_state == SD_STATE_OFFLINE) {
9415 			if (un->un_f_is_fibre == FALSE) {
9416 				scsi_log(SD_DEVINFO(un), sd_label,
9417 				    CE_WARN, "offline\n");
9418 			}
9419 			mutex_exit(SD_MUTEX(un));
9420 			cmlb_invalidate(un->un_cmlbhandle,
9421 			    (void *)SD_PATH_DIRECT);
9422 			mutex_enter(SD_MUTEX(un));
9423 
9424 		} else {
9425 			/*
9426 			 * Flush any outstanding writes in NVRAM cache.
9427 			 * Note: SYNCHRONIZE CACHE is an optional SCSI-2
9428 			 * cmd, it may not work for non-Pluto devices.
9429 			 * SYNCHRONIZE CACHE is not required for removables,
9430 			 * except DVD-RAM drives.
9431 			 *
9432 			 * Also note: because SYNCHRONIZE CACHE is currently
9433 			 * the only command issued here that requires the
9434 			 * drive be powered up, only do the power up before
9435 			 * sending the Sync Cache command. If additional
9436 			 * commands are added which require a powered up
9437 			 * drive, the following sequence may have to change.
9438 			 *
9439 			 * And finally, note that parallel SCSI on SPARC
9440 			 * only issues a Sync Cache to DVD-RAM, a newly
9441 			 * supported device.
9442 			 */
9443 #if defined(__i386) || defined(__amd64)
9444 			if (un->un_f_sync_cache_supported ||
9445 			    un->un_f_dvdram_writable_device == TRUE) {
9446 #else
9447 			if (un->un_f_dvdram_writable_device == TRUE) {
9448 #endif
9449 				mutex_exit(SD_MUTEX(un));
9450 				if (sd_pm_entry(un) == DDI_SUCCESS) {
9451 					rval =
9452 					    sd_send_scsi_SYNCHRONIZE_CACHE(un,
9453 					    NULL);
9454 					/* ignore error if not supported */
9455 					if (rval == ENOTSUP) {
9456 						rval = 0;
9457 					} else if (rval != 0) {
9458 						rval = EIO;
9459 					}
9460 					sd_pm_exit(un);
9461 				} else {
9462 					rval = EIO;
9463 				}
9464 				mutex_enter(SD_MUTEX(un));
9465 			}
9466 
9467 			/*
9468 			 * For devices which supports DOOR_LOCK, send an ALLOW
9469 			 * MEDIA REMOVAL command, but don't get upset if it
9470 			 * fails. We need to raise the power of the drive before
9471 			 * we can call sd_send_scsi_DOORLOCK()
9472 			 */
9473 			if (un->un_f_doorlock_supported) {
9474 				mutex_exit(SD_MUTEX(un));
9475 				if (sd_pm_entry(un) == DDI_SUCCESS) {
9476 					rval = sd_send_scsi_DOORLOCK(un,
9477 					    SD_REMOVAL_ALLOW, SD_PATH_DIRECT);
9478 
9479 					sd_pm_exit(un);
9480 					if (ISCD(un) && (rval != 0) &&
9481 					    (nodelay != 0)) {
9482 						rval = ENXIO;
9483 					}
9484 				} else {
9485 					rval = EIO;
9486 				}
9487 				mutex_enter(SD_MUTEX(un));
9488 			}
9489 
9490 			/*
9491 			 * If a device has removable media, invalidate all
9492 			 * parameters related to media, such as geometry,
9493 			 * blocksize, and blockcount.
9494 			 */
9495 			if (un->un_f_has_removable_media) {
9496 				sr_ejected(un);
9497 			}
9498 
9499 			/*
9500 			 * Destroy the cache (if it exists) which was
9501 			 * allocated for the write maps since this is
9502 			 * the last close for this media.
9503 			 */
9504 			if (un->un_wm_cache) {
9505 				/*
9506 				 * Check if there are pending commands.
9507 				 * and if there are give a warning and
9508 				 * do not destroy the cache.
9509 				 */
9510 				if (un->un_ncmds_in_driver > 0) {
9511 					scsi_log(SD_DEVINFO(un),
9512 					    sd_label, CE_WARN,
9513 					    "Unable to clean up memory "
9514 					    "because of pending I/O\n");
9515 				} else {
9516 					kmem_cache_destroy(
9517 					    un->un_wm_cache);
9518 					un->un_wm_cache = NULL;
9519 				}
9520 			}
9521 		}
9522 	}
9523 
9524 	mutex_exit(SD_MUTEX(un));
9525 	sema_v(&un->un_semoclose);
9526 
9527 	if (otyp == OTYP_LYR) {
9528 		mutex_enter(&sd_detach_mutex);
9529 		/*
9530 		 * The detach routine may run when the layer count
9531 		 * drops to zero.
9532 		 */
9533 		un->un_layer_count--;
9534 		mutex_exit(&sd_detach_mutex);
9535 	}
9536 
9537 	return (rval);
9538 }
9539 
9540 
9541 /*
9542  *    Function: sd_ready_and_valid
9543  *
9544  * Description: Test if device is ready and has a valid geometry.
9545  *
9546  *   Arguments: dev - device number
9547  *		un  - driver soft state (unit) structure
9548  *
9549  * Return Code: SD_READY_VALID		ready and valid label
9550  *		SD_NOT_READY_VALID	not ready, no label
9551  *		SD_RESERVED_BY_OTHERS	reservation conflict
9552  *
9553  *     Context: Never called at interrupt context.
9554  */
9555 
9556 static int
9557 sd_ready_and_valid(struct sd_lun *un)
9558 {
9559 	struct sd_errstats	*stp;
9560 	uint64_t		capacity;
9561 	uint_t			lbasize;
9562 	int			rval = SD_READY_VALID;
9563 	char			name_str[48];
9564 	int			is_valid;
9565 
9566 	ASSERT(un != NULL);
9567 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9568 
9569 	mutex_enter(SD_MUTEX(un));
9570 	/*
9571 	 * If a device has removable media, we must check if media is
9572 	 * ready when checking if this device is ready and valid.
9573 	 */
9574 	if (un->un_f_has_removable_media) {
9575 		mutex_exit(SD_MUTEX(un));
9576 		if (sd_send_scsi_TEST_UNIT_READY(un, 0) != 0) {
9577 			rval = SD_NOT_READY_VALID;
9578 			mutex_enter(SD_MUTEX(un));
9579 			goto done;
9580 		}
9581 
9582 		is_valid = SD_IS_VALID_LABEL(un);
9583 		mutex_enter(SD_MUTEX(un));
9584 		if (!is_valid ||
9585 		    (un->un_f_blockcount_is_valid == FALSE) ||
9586 		    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
9587 
9588 			/* capacity has to be read every open. */
9589 			mutex_exit(SD_MUTEX(un));
9590 			if (sd_send_scsi_READ_CAPACITY(un, &capacity,
9591 			    &lbasize, SD_PATH_DIRECT) != 0) {
9592 				cmlb_invalidate(un->un_cmlbhandle,
9593 				    (void *)SD_PATH_DIRECT);
9594 				mutex_enter(SD_MUTEX(un));
9595 				rval = SD_NOT_READY_VALID;
9596 				goto done;
9597 			} else {
9598 				mutex_enter(SD_MUTEX(un));
9599 				sd_update_block_info(un, lbasize, capacity);
9600 			}
9601 		}
9602 
9603 		/*
9604 		 * Check if the media in the device is writable or not.
9605 		 */
9606 		if (!is_valid && ISCD(un)) {
9607 			sd_check_for_writable_cd(un, SD_PATH_DIRECT);
9608 		}
9609 
9610 	} else {
9611 		/*
9612 		 * Do a test unit ready to clear any unit attention from non-cd
9613 		 * devices.
9614 		 */
9615 		mutex_exit(SD_MUTEX(un));
9616 		(void) sd_send_scsi_TEST_UNIT_READY(un, 0);
9617 		mutex_enter(SD_MUTEX(un));
9618 	}
9619 
9620 
9621 	/*
9622 	 * If this is a non 512 block device, allocate space for
9623 	 * the wmap cache. This is being done here since every time
9624 	 * a media is changed this routine will be called and the
9625 	 * block size is a function of media rather than device.
9626 	 */
9627 	if (un->un_f_non_devbsize_supported && NOT_DEVBSIZE(un)) {
9628 		if (!(un->un_wm_cache)) {
9629 			(void) snprintf(name_str, sizeof (name_str),
9630 			    "%s%d_cache",
9631 			    ddi_driver_name(SD_DEVINFO(un)),
9632 			    ddi_get_instance(SD_DEVINFO(un)));
9633 			un->un_wm_cache = kmem_cache_create(
9634 			    name_str, sizeof (struct sd_w_map),
9635 			    8, sd_wm_cache_constructor,
9636 			    sd_wm_cache_destructor, NULL,
9637 			    (void *)un, NULL, 0);
9638 			if (!(un->un_wm_cache)) {
9639 					rval = ENOMEM;
9640 					goto done;
9641 			}
9642 		}
9643 	}
9644 
9645 	if (un->un_state == SD_STATE_NORMAL) {
9646 		/*
9647 		 * If the target is not yet ready here (defined by a TUR
9648 		 * failure), invalidate the geometry and print an 'offline'
9649 		 * message. This is a legacy message, as the state of the
9650 		 * target is not actually changed to SD_STATE_OFFLINE.
9651 		 *
9652 		 * If the TUR fails for EACCES (Reservation Conflict),
9653 		 * SD_RESERVED_BY_OTHERS will be returned to indicate
9654 		 * reservation conflict. If the TUR fails for other
9655 		 * reasons, SD_NOT_READY_VALID will be returned.
9656 		 */
9657 		int err;
9658 
9659 		mutex_exit(SD_MUTEX(un));
9660 		err = sd_send_scsi_TEST_UNIT_READY(un, 0);
9661 		mutex_enter(SD_MUTEX(un));
9662 
9663 		if (err != 0) {
9664 			mutex_exit(SD_MUTEX(un));
9665 			cmlb_invalidate(un->un_cmlbhandle,
9666 			    (void *)SD_PATH_DIRECT);
9667 			mutex_enter(SD_MUTEX(un));
9668 			if (err == EACCES) {
9669 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
9670 				    "reservation conflict\n");
9671 				rval = SD_RESERVED_BY_OTHERS;
9672 			} else {
9673 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
9674 				    "drive offline\n");
9675 				rval = SD_NOT_READY_VALID;
9676 			}
9677 			goto done;
9678 		}
9679 	}
9680 
9681 	if (un->un_f_format_in_progress == FALSE) {
9682 		mutex_exit(SD_MUTEX(un));
9683 		if (cmlb_validate(un->un_cmlbhandle, 0,
9684 		    (void *)SD_PATH_DIRECT) != 0) {
9685 			rval = SD_NOT_READY_VALID;
9686 			mutex_enter(SD_MUTEX(un));
9687 			goto done;
9688 		}
9689 		if (un->un_f_pkstats_enabled) {
9690 			sd_set_pstats(un);
9691 			SD_TRACE(SD_LOG_IO_PARTITION, un,
9692 			    "sd_ready_and_valid: un:0x%p pstats created and "
9693 			    "set\n", un);
9694 		}
9695 		mutex_enter(SD_MUTEX(un));
9696 	}
9697 
9698 	/*
9699 	 * If this device supports DOOR_LOCK command, try and send
9700 	 * this command to PREVENT MEDIA REMOVAL, but don't get upset
9701 	 * if it fails. For a CD, however, it is an error
9702 	 */
9703 	if (un->un_f_doorlock_supported) {
9704 		mutex_exit(SD_MUTEX(un));
9705 		if ((sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
9706 		    SD_PATH_DIRECT) != 0) && ISCD(un)) {
9707 			rval = SD_NOT_READY_VALID;
9708 			mutex_enter(SD_MUTEX(un));
9709 			goto done;
9710 		}
9711 		mutex_enter(SD_MUTEX(un));
9712 	}
9713 
9714 	/* The state has changed, inform the media watch routines */
9715 	un->un_mediastate = DKIO_INSERTED;
9716 	cv_broadcast(&un->un_state_cv);
9717 	rval = SD_READY_VALID;
9718 
9719 done:
9720 
9721 	/*
9722 	 * Initialize the capacity kstat value, if no media previously
9723 	 * (capacity kstat is 0) and a media has been inserted
9724 	 * (un_blockcount > 0).
9725 	 */
9726 	if (un->un_errstats != NULL) {
9727 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
9728 		if ((stp->sd_capacity.value.ui64 == 0) &&
9729 		    (un->un_f_blockcount_is_valid == TRUE)) {
9730 			stp->sd_capacity.value.ui64 =
9731 			    (uint64_t)((uint64_t)un->un_blockcount *
9732 			    un->un_sys_blocksize);
9733 		}
9734 	}
9735 
9736 	mutex_exit(SD_MUTEX(un));
9737 	return (rval);
9738 }
9739 
9740 
9741 /*
9742  *    Function: sdmin
9743  *
9744  * Description: Routine to limit the size of a data transfer. Used in
9745  *		conjunction with physio(9F).
9746  *
9747  *   Arguments: bp - pointer to the indicated buf(9S) struct.
9748  *
9749  *     Context: Kernel thread context.
9750  */
9751 
9752 static void
9753 sdmin(struct buf *bp)
9754 {
9755 	struct sd_lun	*un;
9756 	int		instance;
9757 
9758 	instance = SDUNIT(bp->b_edev);
9759 
9760 	un = ddi_get_soft_state(sd_state, instance);
9761 	ASSERT(un != NULL);
9762 
9763 	if (bp->b_bcount > un->un_max_xfer_size) {
9764 		bp->b_bcount = un->un_max_xfer_size;
9765 	}
9766 }
9767 
9768 
9769 /*
9770  *    Function: sdread
9771  *
9772  * Description: Driver's read(9e) entry point function.
9773  *
9774  *   Arguments: dev   - device number
9775  *		uio   - structure pointer describing where data is to be stored
9776  *			in user's space
9777  *		cred_p  - user credential pointer
9778  *
9779  * Return Code: ENXIO
9780  *		EIO
9781  *		EINVAL
9782  *		value returned by physio
9783  *
9784  *     Context: Kernel thread context.
9785  */
9786 /* ARGSUSED */
9787 static int
9788 sdread(dev_t dev, struct uio *uio, cred_t *cred_p)
9789 {
9790 	struct sd_lun	*un = NULL;
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 	 * Read 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 		    "sdread: 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 		    "sdread: transfer length not modulo %d\n",
9839 		    un->un_sys_blocksize);
9840 		err = EINVAL;
9841 	} else {
9842 		err = physio(sdstrategy, NULL, dev, B_READ, sdmin, uio);
9843 	}
9844 	return (err);
9845 }
9846 
9847 
9848 /*
9849  *    Function: sdwrite
9850  *
9851  * Description: Driver's write(9e) entry point function.
9852  *
9853  *   Arguments: dev   - device number
9854  *		uio   - structure pointer describing where data is stored in
9855  *			user's space
9856  *		cred_p  - user credential pointer
9857  *
9858  * Return Code: ENXIO
9859  *		EIO
9860  *		EINVAL
9861  *		value returned by physio
9862  *
9863  *     Context: Kernel thread context.
9864  */
9865 /* ARGSUSED */
9866 static int
9867 sdwrite(dev_t dev, struct uio *uio, cred_t *cred_p)
9868 {
9869 	struct sd_lun	*un = NULL;
9870 	int		secmask;
9871 	int		err;
9872 
9873 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9874 		return (ENXIO);
9875 	}
9876 
9877 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9878 
9879 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9880 		mutex_enter(SD_MUTEX(un));
9881 		/*
9882 		 * Because the call to sd_ready_and_valid will issue I/O we
9883 		 * must wait here if either the device is suspended or
9884 		 * if it's power level is changing.
9885 		 */
9886 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9887 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9888 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9889 		}
9890 		un->un_ncmds_in_driver++;
9891 		mutex_exit(SD_MUTEX(un));
9892 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9893 			mutex_enter(SD_MUTEX(un));
9894 			un->un_ncmds_in_driver--;
9895 			ASSERT(un->un_ncmds_in_driver >= 0);
9896 			mutex_exit(SD_MUTEX(un));
9897 			return (EIO);
9898 		}
9899 		mutex_enter(SD_MUTEX(un));
9900 		un->un_ncmds_in_driver--;
9901 		ASSERT(un->un_ncmds_in_driver >= 0);
9902 		mutex_exit(SD_MUTEX(un));
9903 	}
9904 
9905 	/*
9906 	 * Write requests are restricted to multiples of the system block size.
9907 	 */
9908 	secmask = un->un_sys_blocksize - 1;
9909 
9910 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9911 		SD_ERROR(SD_LOG_READ_WRITE, un,
9912 		    "sdwrite: file offset not modulo %d\n",
9913 		    un->un_sys_blocksize);
9914 		err = EINVAL;
9915 	} else if (uio->uio_iov->iov_len & (secmask)) {
9916 		SD_ERROR(SD_LOG_READ_WRITE, un,
9917 		    "sdwrite: transfer length not modulo %d\n",
9918 		    un->un_sys_blocksize);
9919 		err = EINVAL;
9920 	} else {
9921 		err = physio(sdstrategy, NULL, dev, B_WRITE, sdmin, uio);
9922 	}
9923 	return (err);
9924 }
9925 
9926 
9927 /*
9928  *    Function: sdaread
9929  *
9930  * Description: Driver's aread(9e) entry point function.
9931  *
9932  *   Arguments: dev   - device number
9933  *		aio   - structure pointer describing where data is to be stored
9934  *		cred_p  - user credential pointer
9935  *
9936  * Return Code: ENXIO
9937  *		EIO
9938  *		EINVAL
9939  *		value returned by aphysio
9940  *
9941  *     Context: Kernel thread context.
9942  */
9943 /* ARGSUSED */
9944 static int
9945 sdaread(dev_t dev, struct aio_req *aio, cred_t *cred_p)
9946 {
9947 	struct sd_lun	*un = NULL;
9948 	struct uio	*uio = aio->aio_uio;
9949 	int		secmask;
9950 	int		err;
9951 
9952 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
9953 		return (ENXIO);
9954 	}
9955 
9956 	ASSERT(!mutex_owned(SD_MUTEX(un)));
9957 
9958 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
9959 		mutex_enter(SD_MUTEX(un));
9960 		/*
9961 		 * Because the call to sd_ready_and_valid will issue I/O we
9962 		 * must wait here if either the device is suspended or
9963 		 * if it's power level is changing.
9964 		 */
9965 		while ((un->un_state == SD_STATE_SUSPENDED) ||
9966 		    (un->un_state == SD_STATE_PM_CHANGING)) {
9967 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
9968 		}
9969 		un->un_ncmds_in_driver++;
9970 		mutex_exit(SD_MUTEX(un));
9971 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
9972 			mutex_enter(SD_MUTEX(un));
9973 			un->un_ncmds_in_driver--;
9974 			ASSERT(un->un_ncmds_in_driver >= 0);
9975 			mutex_exit(SD_MUTEX(un));
9976 			return (EIO);
9977 		}
9978 		mutex_enter(SD_MUTEX(un));
9979 		un->un_ncmds_in_driver--;
9980 		ASSERT(un->un_ncmds_in_driver >= 0);
9981 		mutex_exit(SD_MUTEX(un));
9982 	}
9983 
9984 	/*
9985 	 * Read requests are restricted to multiples of the system block size.
9986 	 */
9987 	secmask = un->un_sys_blocksize - 1;
9988 
9989 	if (uio->uio_loffset & ((offset_t)(secmask))) {
9990 		SD_ERROR(SD_LOG_READ_WRITE, un,
9991 		    "sdaread: file offset not modulo %d\n",
9992 		    un->un_sys_blocksize);
9993 		err = EINVAL;
9994 	} else if (uio->uio_iov->iov_len & (secmask)) {
9995 		SD_ERROR(SD_LOG_READ_WRITE, un,
9996 		    "sdaread: transfer length not modulo %d\n",
9997 		    un->un_sys_blocksize);
9998 		err = EINVAL;
9999 	} else {
10000 		err = aphysio(sdstrategy, anocancel, dev, B_READ, sdmin, aio);
10001 	}
10002 	return (err);
10003 }
10004 
10005 
10006 /*
10007  *    Function: sdawrite
10008  *
10009  * Description: Driver's awrite(9e) entry point function.
10010  *
10011  *   Arguments: dev   - device number
10012  *		aio   - structure pointer describing where data is stored
10013  *		cred_p  - user credential pointer
10014  *
10015  * Return Code: ENXIO
10016  *		EIO
10017  *		EINVAL
10018  *		value returned by aphysio
10019  *
10020  *     Context: Kernel thread context.
10021  */
10022 /* ARGSUSED */
10023 static int
10024 sdawrite(dev_t dev, struct aio_req *aio, cred_t *cred_p)
10025 {
10026 	struct sd_lun	*un = NULL;
10027 	struct uio	*uio = aio->aio_uio;
10028 	int		secmask;
10029 	int		err;
10030 
10031 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
10032 		return (ENXIO);
10033 	}
10034 
10035 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10036 
10037 	if (!SD_IS_VALID_LABEL(un) && !ISCD(un)) {
10038 		mutex_enter(SD_MUTEX(un));
10039 		/*
10040 		 * Because the call to sd_ready_and_valid will issue I/O we
10041 		 * must wait here if either the device is suspended or
10042 		 * if it's power level is changing.
10043 		 */
10044 		while ((un->un_state == SD_STATE_SUSPENDED) ||
10045 		    (un->un_state == SD_STATE_PM_CHANGING)) {
10046 			cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10047 		}
10048 		un->un_ncmds_in_driver++;
10049 		mutex_exit(SD_MUTEX(un));
10050 		if ((sd_ready_and_valid(un)) != SD_READY_VALID) {
10051 			mutex_enter(SD_MUTEX(un));
10052 			un->un_ncmds_in_driver--;
10053 			ASSERT(un->un_ncmds_in_driver >= 0);
10054 			mutex_exit(SD_MUTEX(un));
10055 			return (EIO);
10056 		}
10057 		mutex_enter(SD_MUTEX(un));
10058 		un->un_ncmds_in_driver--;
10059 		ASSERT(un->un_ncmds_in_driver >= 0);
10060 		mutex_exit(SD_MUTEX(un));
10061 	}
10062 
10063 	/*
10064 	 * Write requests are restricted to multiples of the system block size.
10065 	 */
10066 	secmask = un->un_sys_blocksize - 1;
10067 
10068 	if (uio->uio_loffset & ((offset_t)(secmask))) {
10069 		SD_ERROR(SD_LOG_READ_WRITE, un,
10070 		    "sdawrite: file offset not modulo %d\n",
10071 		    un->un_sys_blocksize);
10072 		err = EINVAL;
10073 	} else if (uio->uio_iov->iov_len & (secmask)) {
10074 		SD_ERROR(SD_LOG_READ_WRITE, un,
10075 		    "sdawrite: transfer length not modulo %d\n",
10076 		    un->un_sys_blocksize);
10077 		err = EINVAL;
10078 	} else {
10079 		err = aphysio(sdstrategy, anocancel, dev, B_WRITE, sdmin, aio);
10080 	}
10081 	return (err);
10082 }
10083 
10084 
10085 
10086 
10087 
10088 /*
10089  * Driver IO processing follows the following sequence:
10090  *
10091  *     sdioctl(9E)     sdstrategy(9E)         biodone(9F)
10092  *         |                |                     ^
10093  *         v                v                     |
10094  * sd_send_scsi_cmd()  ddi_xbuf_qstrategy()       +-------------------+
10095  *         |                |                     |                   |
10096  *         v                |                     |                   |
10097  * sd_uscsi_strategy() sd_xbuf_strategy()   sd_buf_iodone()   sd_uscsi_iodone()
10098  *         |                |                     ^                   ^
10099  *         v                v                     |                   |
10100  * SD_BEGIN_IOSTART()  SD_BEGIN_IOSTART()         |                   |
10101  *         |                |                     |                   |
10102  *     +---+                |                     +------------+      +-------+
10103  *     |                    |                                  |              |
10104  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10105  *     |                    v                                  |              |
10106  *     |         sd_mapblockaddr_iostart()           sd_mapblockaddr_iodone() |
10107  *     |                    |                                  ^              |
10108  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10109  *     |                    v                                  |              |
10110  *     |         sd_mapblocksize_iostart()           sd_mapblocksize_iodone() |
10111  *     |                    |                                  ^              |
10112  *     |   SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()|              |
10113  *     |                    v                                  |              |
10114  *     |           sd_checksum_iostart()               sd_checksum_iodone()   |
10115  *     |                    |                                  ^              |
10116  *     +-> SD_NEXT_IOSTART()|                  SD_NEXT_IODONE()+------------->+
10117  *     |                    v                                  |              |
10118  *     |              sd_pm_iostart()                     sd_pm_iodone()      |
10119  *     |                    |                                  ^              |
10120  *     |                    |                                  |              |
10121  *     +-> SD_NEXT_IOSTART()|               SD_BEGIN_IODONE()--+--------------+
10122  *                          |                           ^
10123  *                          v                           |
10124  *                   sd_core_iostart()                  |
10125  *                          |                           |
10126  *                          |                           +------>(*destroypkt)()
10127  *                          +-> sd_start_cmds() <-+     |           |
10128  *                          |                     |     |           v
10129  *                          |                     |     |  scsi_destroy_pkt(9F)
10130  *                          |                     |     |
10131  *                          +->(*initpkt)()       +- sdintr()
10132  *                          |  |                        |  |
10133  *                          |  +-> scsi_init_pkt(9F)    |  +-> sd_handle_xxx()
10134  *                          |  +-> scsi_setup_cdb(9F)   |
10135  *                          |                           |
10136  *                          +--> scsi_transport(9F)     |
10137  *                                     |                |
10138  *                                     +----> SCSA ---->+
10139  *
10140  *
10141  * This code is based upon the following presumptions:
10142  *
10143  *   - iostart and iodone functions operate on buf(9S) structures. These
10144  *     functions perform the necessary operations on the buf(9S) and pass
10145  *     them along to the next function in the chain by using the macros
10146  *     SD_NEXT_IOSTART() (for iostart side functions) and SD_NEXT_IODONE()
10147  *     (for iodone side functions).
10148  *
10149  *   - The iostart side functions may sleep. The iodone side functions
10150  *     are called under interrupt context and may NOT sleep. Therefore
10151  *     iodone side functions also may not call iostart side functions.
10152  *     (NOTE: iostart side functions should NOT sleep for memory, as
10153  *     this could result in deadlock.)
10154  *
10155  *   - An iostart side function may call its corresponding iodone side
10156  *     function directly (if necessary).
10157  *
10158  *   - In the event of an error, an iostart side function can return a buf(9S)
10159  *     to its caller by calling SD_BEGIN_IODONE() (after setting B_ERROR and
10160  *     b_error in the usual way of course).
10161  *
10162  *   - The taskq mechanism may be used by the iodone side functions to dispatch
10163  *     requests to the iostart side functions.  The iostart side functions in
10164  *     this case would be called under the context of a taskq thread, so it's
10165  *     OK for them to block/sleep/spin in this case.
10166  *
10167  *   - iostart side functions may allocate "shadow" buf(9S) structs and
10168  *     pass them along to the next function in the chain.  The corresponding
10169  *     iodone side functions must coalesce the "shadow" bufs and return
10170  *     the "original" buf to the next higher layer.
10171  *
10172  *   - The b_private field of the buf(9S) struct holds a pointer to
10173  *     an sd_xbuf struct, which contains information needed to
10174  *     construct the scsi_pkt for the command.
10175  *
10176  *   - The SD_MUTEX(un) is NOT held across calls to the next layer. Each
10177  *     layer must acquire & release the SD_MUTEX(un) as needed.
10178  */
10179 
10180 
10181 /*
10182  * Create taskq for all targets in the system. This is created at
10183  * _init(9E) and destroyed at _fini(9E).
10184  *
10185  * Note: here we set the minalloc to a reasonably high number to ensure that
10186  * we will have an adequate supply of task entries available at interrupt time.
10187  * This is used in conjunction with the TASKQ_PREPOPULATE flag in
10188  * sd_create_taskq().  Since we do not want to sleep for allocations at
10189  * interrupt time, set maxalloc equal to minalloc. That way we will just fail
10190  * the command if we ever try to dispatch more than SD_TASKQ_MAXALLOC taskq
10191  * requests any one instant in time.
10192  */
10193 #define	SD_TASKQ_NUMTHREADS	8
10194 #define	SD_TASKQ_MINALLOC	256
10195 #define	SD_TASKQ_MAXALLOC	256
10196 
10197 static taskq_t	*sd_tq = NULL;
10198 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_tq))
10199 
10200 static int	sd_taskq_minalloc = SD_TASKQ_MINALLOC;
10201 static int	sd_taskq_maxalloc = SD_TASKQ_MAXALLOC;
10202 
10203 /*
10204  * The following task queue is being created for the write part of
10205  * read-modify-write of non-512 block size devices.
10206  * Limit the number of threads to 1 for now. This number has been chosen
10207  * considering the fact that it applies only to dvd ram drives/MO drives
10208  * currently. Performance for which is not main criteria at this stage.
10209  * Note: It needs to be explored if we can use a single taskq in future
10210  */
10211 #define	SD_WMR_TASKQ_NUMTHREADS	1
10212 static taskq_t	*sd_wmr_tq = NULL;
10213 _NOTE(SCHEME_PROTECTS_DATA("stable data", sd_wmr_tq))
10214 
10215 /*
10216  *    Function: sd_taskq_create
10217  *
10218  * Description: Create taskq thread(s) and preallocate task entries
10219  *
10220  * Return Code: Returns a pointer to the allocated taskq_t.
10221  *
10222  *     Context: Can sleep. Requires blockable context.
10223  *
10224  *       Notes: - The taskq() facility currently is NOT part of the DDI.
10225  *		  (definitely NOT recommeded for 3rd-party drivers!) :-)
10226  *		- taskq_create() will block for memory, also it will panic
10227  *		  if it cannot create the requested number of threads.
10228  *		- Currently taskq_create() creates threads that cannot be
10229  *		  swapped.
10230  *		- We use TASKQ_PREPOPULATE to ensure we have an adequate
10231  *		  supply of taskq entries at interrupt time (ie, so that we
10232  *		  do not have to sleep for memory)
10233  */
10234 
10235 static void
10236 sd_taskq_create(void)
10237 {
10238 	char	taskq_name[TASKQ_NAMELEN];
10239 
10240 	ASSERT(sd_tq == NULL);
10241 	ASSERT(sd_wmr_tq == NULL);
10242 
10243 	(void) snprintf(taskq_name, sizeof (taskq_name),
10244 	    "%s_drv_taskq", sd_label);
10245 	sd_tq = (taskq_create(taskq_name, SD_TASKQ_NUMTHREADS,
10246 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10247 	    TASKQ_PREPOPULATE));
10248 
10249 	(void) snprintf(taskq_name, sizeof (taskq_name),
10250 	    "%s_rmw_taskq", sd_label);
10251 	sd_wmr_tq = (taskq_create(taskq_name, SD_WMR_TASKQ_NUMTHREADS,
10252 	    (v.v_maxsyspri - 2), sd_taskq_minalloc, sd_taskq_maxalloc,
10253 	    TASKQ_PREPOPULATE));
10254 }
10255 
10256 
10257 /*
10258  *    Function: sd_taskq_delete
10259  *
10260  * Description: Complementary cleanup routine for sd_taskq_create().
10261  *
10262  *     Context: Kernel thread context.
10263  */
10264 
10265 static void
10266 sd_taskq_delete(void)
10267 {
10268 	ASSERT(sd_tq != NULL);
10269 	ASSERT(sd_wmr_tq != NULL);
10270 	taskq_destroy(sd_tq);
10271 	taskq_destroy(sd_wmr_tq);
10272 	sd_tq = NULL;
10273 	sd_wmr_tq = NULL;
10274 }
10275 
10276 
10277 /*
10278  *    Function: sdstrategy
10279  *
10280  * Description: Driver's strategy (9E) entry point function.
10281  *
10282  *   Arguments: bp - pointer to buf(9S)
10283  *
10284  * Return Code: Always returns zero
10285  *
10286  *     Context: Kernel thread context.
10287  */
10288 
10289 static int
10290 sdstrategy(struct buf *bp)
10291 {
10292 	struct sd_lun *un;
10293 
10294 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
10295 	if (un == NULL) {
10296 		bioerror(bp, EIO);
10297 		bp->b_resid = bp->b_bcount;
10298 		biodone(bp);
10299 		return (0);
10300 	}
10301 	/* As was done in the past, fail new cmds. if state is dumping. */
10302 	if (un->un_state == SD_STATE_DUMPING) {
10303 		bioerror(bp, ENXIO);
10304 		bp->b_resid = bp->b_bcount;
10305 		biodone(bp);
10306 		return (0);
10307 	}
10308 
10309 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10310 
10311 	/*
10312 	 * Commands may sneak in while we released the mutex in
10313 	 * DDI_SUSPEND, we should block new commands. However, old
10314 	 * commands that are still in the driver at this point should
10315 	 * still be allowed to drain.
10316 	 */
10317 	mutex_enter(SD_MUTEX(un));
10318 	/*
10319 	 * Must wait here if either the device is suspended or
10320 	 * if it's power level is changing.
10321 	 */
10322 	while ((un->un_state == SD_STATE_SUSPENDED) ||
10323 	    (un->un_state == SD_STATE_PM_CHANGING)) {
10324 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
10325 	}
10326 
10327 	un->un_ncmds_in_driver++;
10328 
10329 	/*
10330 	 * atapi: Since we are running the CD for now in PIO mode we need to
10331 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
10332 	 * the HBA's init_pkt routine.
10333 	 */
10334 	if (un->un_f_cfg_is_atapi == TRUE) {
10335 		mutex_exit(SD_MUTEX(un));
10336 		bp_mapin(bp);
10337 		mutex_enter(SD_MUTEX(un));
10338 	}
10339 	SD_INFO(SD_LOG_IO, un, "sdstrategy: un_ncmds_in_driver = %ld\n",
10340 	    un->un_ncmds_in_driver);
10341 
10342 	mutex_exit(SD_MUTEX(un));
10343 
10344 	/*
10345 	 * This will (eventually) allocate the sd_xbuf area and
10346 	 * call sd_xbuf_strategy().  We just want to return the
10347 	 * result of ddi_xbuf_qstrategy so that we have an opt-
10348 	 * imized tail call which saves us a stack frame.
10349 	 */
10350 	return (ddi_xbuf_qstrategy(bp, un->un_xbuf_attr));
10351 }
10352 
10353 
10354 /*
10355  *    Function: sd_xbuf_strategy
10356  *
10357  * Description: Function for initiating IO operations via the
10358  *		ddi_xbuf_qstrategy() mechanism.
10359  *
10360  *     Context: Kernel thread context.
10361  */
10362 
10363 static void
10364 sd_xbuf_strategy(struct buf *bp, ddi_xbuf_t xp, void *arg)
10365 {
10366 	struct sd_lun *un = arg;
10367 
10368 	ASSERT(bp != NULL);
10369 	ASSERT(xp != NULL);
10370 	ASSERT(un != NULL);
10371 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10372 
10373 	/*
10374 	 * Initialize the fields in the xbuf and save a pointer to the
10375 	 * xbuf in bp->b_private.
10376 	 */
10377 	sd_xbuf_init(un, bp, xp, SD_CHAIN_BUFIO, NULL);
10378 
10379 	/* Send the buf down the iostart chain */
10380 	SD_BEGIN_IOSTART(((struct sd_xbuf *)xp)->xb_chain_iostart, un, bp);
10381 }
10382 
10383 
10384 /*
10385  *    Function: sd_xbuf_init
10386  *
10387  * Description: Prepare the given sd_xbuf struct for use.
10388  *
10389  *   Arguments: un - ptr to softstate
10390  *		bp - ptr to associated buf(9S)
10391  *		xp - ptr to associated sd_xbuf
10392  *		chain_type - IO chain type to use:
10393  *			SD_CHAIN_NULL
10394  *			SD_CHAIN_BUFIO
10395  *			SD_CHAIN_USCSI
10396  *			SD_CHAIN_DIRECT
10397  *			SD_CHAIN_DIRECT_PRIORITY
10398  *		pktinfop - ptr to private data struct for scsi_pkt(9S)
10399  *			initialization; may be NULL if none.
10400  *
10401  *     Context: Kernel thread context
10402  */
10403 
10404 static void
10405 sd_xbuf_init(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
10406 	uchar_t chain_type, void *pktinfop)
10407 {
10408 	int index;
10409 
10410 	ASSERT(un != NULL);
10411 	ASSERT(bp != NULL);
10412 	ASSERT(xp != NULL);
10413 
10414 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: buf:0x%p chain type:0x%x\n",
10415 	    bp, chain_type);
10416 
10417 	xp->xb_un	= un;
10418 	xp->xb_pktp	= NULL;
10419 	xp->xb_pktinfo	= pktinfop;
10420 	xp->xb_private	= bp->b_private;
10421 	xp->xb_blkno	= (daddr_t)bp->b_blkno;
10422 
10423 	/*
10424 	 * Set up the iostart and iodone chain indexes in the xbuf, based
10425 	 * upon the specified chain type to use.
10426 	 */
10427 	switch (chain_type) {
10428 	case SD_CHAIN_NULL:
10429 		/*
10430 		 * Fall thru to just use the values for the buf type, even
10431 		 * tho for the NULL chain these values will never be used.
10432 		 */
10433 		/* FALLTHRU */
10434 	case SD_CHAIN_BUFIO:
10435 		index = un->un_buf_chain_type;
10436 		break;
10437 	case SD_CHAIN_USCSI:
10438 		index = un->un_uscsi_chain_type;
10439 		break;
10440 	case SD_CHAIN_DIRECT:
10441 		index = un->un_direct_chain_type;
10442 		break;
10443 	case SD_CHAIN_DIRECT_PRIORITY:
10444 		index = un->un_priority_chain_type;
10445 		break;
10446 	default:
10447 		/* We're really broken if we ever get here... */
10448 		panic("sd_xbuf_init: illegal chain type!");
10449 		/*NOTREACHED*/
10450 	}
10451 
10452 	xp->xb_chain_iostart = sd_chain_index_map[index].sci_iostart_index;
10453 	xp->xb_chain_iodone = sd_chain_index_map[index].sci_iodone_index;
10454 
10455 	/*
10456 	 * It might be a bit easier to simply bzero the entire xbuf above,
10457 	 * but it turns out that since we init a fair number of members anyway,
10458 	 * we save a fair number cycles by doing explicit assignment of zero.
10459 	 */
10460 	xp->xb_pkt_flags	= 0;
10461 	xp->xb_dma_resid	= 0;
10462 	xp->xb_retry_count	= 0;
10463 	xp->xb_victim_retry_count = 0;
10464 	xp->xb_ua_retry_count	= 0;
10465 	xp->xb_nr_retry_count	= 0;
10466 	xp->xb_sense_bp		= NULL;
10467 	xp->xb_sense_status	= 0;
10468 	xp->xb_sense_state	= 0;
10469 	xp->xb_sense_resid	= 0;
10470 
10471 	bp->b_private	= xp;
10472 	bp->b_flags	&= ~(B_DONE | B_ERROR);
10473 	bp->b_resid	= 0;
10474 	bp->av_forw	= NULL;
10475 	bp->av_back	= NULL;
10476 	bioerror(bp, 0);
10477 
10478 	SD_INFO(SD_LOG_IO, un, "sd_xbuf_init: done.\n");
10479 }
10480 
10481 
10482 /*
10483  *    Function: sd_uscsi_strategy
10484  *
10485  * Description: Wrapper for calling into the USCSI chain via physio(9F)
10486  *
10487  *   Arguments: bp - buf struct ptr
10488  *
10489  * Return Code: Always returns 0
10490  *
10491  *     Context: Kernel thread context
10492  */
10493 
10494 static int
10495 sd_uscsi_strategy(struct buf *bp)
10496 {
10497 	struct sd_lun		*un;
10498 	struct sd_uscsi_info	*uip;
10499 	struct sd_xbuf		*xp;
10500 	uchar_t			chain_type;
10501 
10502 	ASSERT(bp != NULL);
10503 
10504 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
10505 	if (un == NULL) {
10506 		bioerror(bp, EIO);
10507 		bp->b_resid = bp->b_bcount;
10508 		biodone(bp);
10509 		return (0);
10510 	}
10511 
10512 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10513 
10514 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: entry: buf:0x%p\n", bp);
10515 
10516 	mutex_enter(SD_MUTEX(un));
10517 	/*
10518 	 * atapi: Since we are running the CD for now in PIO mode we need to
10519 	 * call bp_mapin here to avoid bp_mapin called interrupt context under
10520 	 * the HBA's init_pkt routine.
10521 	 */
10522 	if (un->un_f_cfg_is_atapi == TRUE) {
10523 		mutex_exit(SD_MUTEX(un));
10524 		bp_mapin(bp);
10525 		mutex_enter(SD_MUTEX(un));
10526 	}
10527 	un->un_ncmds_in_driver++;
10528 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_strategy: un_ncmds_in_driver = %ld\n",
10529 	    un->un_ncmds_in_driver);
10530 	mutex_exit(SD_MUTEX(un));
10531 
10532 	/*
10533 	 * A pointer to a struct sd_uscsi_info is expected in bp->b_private
10534 	 */
10535 	ASSERT(bp->b_private != NULL);
10536 	uip = (struct sd_uscsi_info *)bp->b_private;
10537 
10538 	switch (uip->ui_flags) {
10539 	case SD_PATH_DIRECT:
10540 		chain_type = SD_CHAIN_DIRECT;
10541 		break;
10542 	case SD_PATH_DIRECT_PRIORITY:
10543 		chain_type = SD_CHAIN_DIRECT_PRIORITY;
10544 		break;
10545 	default:
10546 		chain_type = SD_CHAIN_USCSI;
10547 		break;
10548 	}
10549 
10550 	/*
10551 	 * We may allocate extra buf for external USCSI commands. If the
10552 	 * application asks for bigger than 20-byte sense data via USCSI,
10553 	 * SCSA layer will allocate 252 bytes sense buf for that command.
10554 	 */
10555 	if (((struct uscsi_cmd *)(uip->ui_cmdp))->uscsi_rqlen >
10556 	    SENSE_LENGTH) {
10557 		xp = kmem_zalloc(sizeof (struct sd_xbuf) - SENSE_LENGTH +
10558 		    MAX_SENSE_LENGTH, KM_SLEEP);
10559 	} else {
10560 		xp = kmem_zalloc(sizeof (struct sd_xbuf), KM_SLEEP);
10561 	}
10562 
10563 	sd_xbuf_init(un, bp, xp, chain_type, uip->ui_cmdp);
10564 
10565 	/* Use the index obtained within xbuf_init */
10566 	SD_BEGIN_IOSTART(xp->xb_chain_iostart, un, bp);
10567 
10568 	SD_TRACE(SD_LOG_IO, un, "sd_uscsi_strategy: exit: buf:0x%p\n", bp);
10569 
10570 	return (0);
10571 }
10572 
10573 /*
10574  *    Function: sd_send_scsi_cmd
10575  *
10576  * Description: Runs a USCSI command for user (when called thru sdioctl),
10577  *		or for the driver
10578  *
10579  *   Arguments: dev - the dev_t for the device
10580  *		incmd - ptr to a valid uscsi_cmd struct
10581  *		flag - bit flag, indicating open settings, 32/64 bit type
10582  *		dataspace - UIO_USERSPACE or UIO_SYSSPACE
10583  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
10584  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
10585  *			to use the USCSI "direct" chain and bypass the normal
10586  *			command waitq.
10587  *
10588  * Return Code: 0 -  successful completion of the given command
10589  *		EIO - scsi_uscsi_handle_command() failed
10590  *		ENXIO  - soft state not found for specified dev
10591  *		EINVAL
10592  *		EFAULT - copyin/copyout error
10593  *		return code of scsi_uscsi_handle_command():
10594  *			EIO
10595  *			ENXIO
10596  *			EACCES
10597  *
10598  *     Context: Waits for command to complete. Can sleep.
10599  */
10600 
10601 static int
10602 sd_send_scsi_cmd(dev_t dev, struct uscsi_cmd *incmd, int flag,
10603 	enum uio_seg dataspace, int path_flag)
10604 {
10605 	struct sd_uscsi_info	*uip;
10606 	struct uscsi_cmd	*uscmd;
10607 	struct sd_lun	*un;
10608 	int	format = 0;
10609 	int	rval;
10610 
10611 	un = ddi_get_soft_state(sd_state, SDUNIT(dev));
10612 	if (un == NULL) {
10613 		return (ENXIO);
10614 	}
10615 
10616 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10617 
10618 #ifdef SDDEBUG
10619 	switch (dataspace) {
10620 	case UIO_USERSPACE:
10621 		SD_TRACE(SD_LOG_IO, un,
10622 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_USERSPACE\n", un);
10623 		break;
10624 	case UIO_SYSSPACE:
10625 		SD_TRACE(SD_LOG_IO, un,
10626 		    "sd_send_scsi_cmd: entry: un:0x%p UIO_SYSSPACE\n", un);
10627 		break;
10628 	default:
10629 		SD_TRACE(SD_LOG_IO, un,
10630 		    "sd_send_scsi_cmd: entry: un:0x%p UNEXPECTED SPACE\n", un);
10631 		break;
10632 	}
10633 #endif
10634 
10635 	rval = scsi_uscsi_alloc_and_copyin((intptr_t)incmd, flag,
10636 	    SD_ADDRESS(un), &uscmd);
10637 	if (rval != 0) {
10638 		SD_TRACE(SD_LOG_IO, un, "sd_sense_scsi_cmd: "
10639 		    "scsi_uscsi_alloc_and_copyin failed\n", un);
10640 		return (rval);
10641 	}
10642 
10643 	if ((uscmd->uscsi_cdb != NULL) &&
10644 	    (uscmd->uscsi_cdb[0] == SCMD_FORMAT)) {
10645 		mutex_enter(SD_MUTEX(un));
10646 		un->un_f_format_in_progress = TRUE;
10647 		mutex_exit(SD_MUTEX(un));
10648 		format = 1;
10649 	}
10650 
10651 	/*
10652 	 * Allocate an sd_uscsi_info struct and fill it with the info
10653 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
10654 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
10655 	 * since we allocate the buf here in this function, we do not
10656 	 * need to preserve the prior contents of b_private.
10657 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
10658 	 */
10659 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
10660 	uip->ui_flags = path_flag;
10661 	uip->ui_cmdp = uscmd;
10662 
10663 	/*
10664 	 * Commands sent with priority are intended for error recovery
10665 	 * situations, and do not have retries performed.
10666 	 */
10667 	if (path_flag == SD_PATH_DIRECT_PRIORITY) {
10668 		uscmd->uscsi_flags |= USCSI_DIAGNOSE;
10669 	}
10670 	uscmd->uscsi_flags &= ~USCSI_NOINTR;
10671 
10672 	rval = scsi_uscsi_handle_cmd(dev, dataspace, uscmd,
10673 	    sd_uscsi_strategy, NULL, uip);
10674 
10675 #ifdef SDDEBUG
10676 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10677 	    "uscsi_status: 0x%02x  uscsi_resid:0x%x\n",
10678 	    uscmd->uscsi_status, uscmd->uscsi_resid);
10679 	if (uscmd->uscsi_bufaddr != NULL) {
10680 		SD_INFO(SD_LOG_IO, un, "sd_send_scsi_cmd: "
10681 		    "uscmd->uscsi_bufaddr: 0x%p  uscmd->uscsi_buflen:%d\n",
10682 		    uscmd->uscsi_bufaddr, uscmd->uscsi_buflen);
10683 		if (dataspace == UIO_SYSSPACE) {
10684 			SD_DUMP_MEMORY(un, SD_LOG_IO,
10685 			    "data", (uchar_t *)uscmd->uscsi_bufaddr,
10686 			    uscmd->uscsi_buflen, SD_LOG_HEX);
10687 		}
10688 	}
10689 #endif
10690 
10691 	if (format == 1) {
10692 		mutex_enter(SD_MUTEX(un));
10693 		un->un_f_format_in_progress = FALSE;
10694 		mutex_exit(SD_MUTEX(un));
10695 	}
10696 
10697 	(void) scsi_uscsi_copyout_and_free((intptr_t)incmd, uscmd);
10698 	kmem_free(uip, sizeof (struct sd_uscsi_info));
10699 
10700 	return (rval);
10701 }
10702 
10703 
10704 /*
10705  *    Function: sd_buf_iodone
10706  *
10707  * Description: Frees the sd_xbuf & returns the buf to its originator.
10708  *
10709  *     Context: May be called from interrupt context.
10710  */
10711 /* ARGSUSED */
10712 static void
10713 sd_buf_iodone(int index, struct sd_lun *un, struct buf *bp)
10714 {
10715 	struct sd_xbuf *xp;
10716 
10717 	ASSERT(un != NULL);
10718 	ASSERT(bp != NULL);
10719 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10720 
10721 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: entry.\n");
10722 
10723 	xp = SD_GET_XBUF(bp);
10724 	ASSERT(xp != NULL);
10725 
10726 	mutex_enter(SD_MUTEX(un));
10727 
10728 	/*
10729 	 * Grab time when the cmd completed.
10730 	 * This is used for determining if the system has been
10731 	 * idle long enough to make it idle to the PM framework.
10732 	 * This is for lowering the overhead, and therefore improving
10733 	 * performance per I/O operation.
10734 	 */
10735 	un->un_pm_idle_time = ddi_get_time();
10736 
10737 	un->un_ncmds_in_driver--;
10738 	ASSERT(un->un_ncmds_in_driver >= 0);
10739 	SD_INFO(SD_LOG_IO, un, "sd_buf_iodone: un_ncmds_in_driver = %ld\n",
10740 	    un->un_ncmds_in_driver);
10741 
10742 	mutex_exit(SD_MUTEX(un));
10743 
10744 	ddi_xbuf_done(bp, un->un_xbuf_attr);	/* xbuf is gone after this */
10745 	biodone(bp);				/* bp is gone after this */
10746 
10747 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_buf_iodone: exit.\n");
10748 }
10749 
10750 
10751 /*
10752  *    Function: sd_uscsi_iodone
10753  *
10754  * Description: Frees the sd_xbuf & returns the buf to its originator.
10755  *
10756  *     Context: May be called from interrupt context.
10757  */
10758 /* ARGSUSED */
10759 static void
10760 sd_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
10761 {
10762 	struct sd_xbuf *xp;
10763 
10764 	ASSERT(un != NULL);
10765 	ASSERT(bp != NULL);
10766 
10767 	xp = SD_GET_XBUF(bp);
10768 	ASSERT(xp != NULL);
10769 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10770 
10771 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: entry.\n");
10772 
10773 	bp->b_private = xp->xb_private;
10774 
10775 	mutex_enter(SD_MUTEX(un));
10776 
10777 	/*
10778 	 * Grab time when the cmd completed.
10779 	 * This is used for determining if the system has been
10780 	 * idle long enough to make it idle to the PM framework.
10781 	 * This is for lowering the overhead, and therefore improving
10782 	 * performance per I/O operation.
10783 	 */
10784 	un->un_pm_idle_time = ddi_get_time();
10785 
10786 	un->un_ncmds_in_driver--;
10787 	ASSERT(un->un_ncmds_in_driver >= 0);
10788 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: un_ncmds_in_driver = %ld\n",
10789 	    un->un_ncmds_in_driver);
10790 
10791 	mutex_exit(SD_MUTEX(un));
10792 
10793 	if (((struct uscsi_cmd *)(xp->xb_pktinfo))->uscsi_rqlen >
10794 	    SENSE_LENGTH) {
10795 		kmem_free(xp, sizeof (struct sd_xbuf) - SENSE_LENGTH +
10796 		    MAX_SENSE_LENGTH);
10797 	} else {
10798 		kmem_free(xp, sizeof (struct sd_xbuf));
10799 	}
10800 
10801 	biodone(bp);
10802 
10803 	SD_INFO(SD_LOG_IO, un, "sd_uscsi_iodone: exit.\n");
10804 }
10805 
10806 
10807 /*
10808  *    Function: sd_mapblockaddr_iostart
10809  *
10810  * Description: Verify request lies within the partition limits for
10811  *		the indicated minor device.  Issue "overrun" buf if
10812  *		request would exceed partition range.  Converts
10813  *		partition-relative block address to absolute.
10814  *
10815  *     Context: Can sleep
10816  *
10817  *      Issues: This follows what the old code did, in terms of accessing
10818  *		some of the partition info in the unit struct without holding
10819  *		the mutext.  This is a general issue, if the partition info
10820  *		can be altered while IO is in progress... as soon as we send
10821  *		a buf, its partitioning can be invalid before it gets to the
10822  *		device.  Probably the right fix is to move partitioning out
10823  *		of the driver entirely.
10824  */
10825 
10826 static void
10827 sd_mapblockaddr_iostart(int index, struct sd_lun *un, struct buf *bp)
10828 {
10829 	diskaddr_t	nblocks;	/* #blocks in the given partition */
10830 	daddr_t	blocknum;	/* Block number specified by the buf */
10831 	size_t	requested_nblocks;
10832 	size_t	available_nblocks;
10833 	int	partition;
10834 	diskaddr_t	partition_offset;
10835 	struct sd_xbuf *xp;
10836 
10837 
10838 	ASSERT(un != NULL);
10839 	ASSERT(bp != NULL);
10840 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10841 
10842 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10843 	    "sd_mapblockaddr_iostart: entry: buf:0x%p\n", bp);
10844 
10845 	xp = SD_GET_XBUF(bp);
10846 	ASSERT(xp != NULL);
10847 
10848 	/*
10849 	 * If the geometry is not indicated as valid, attempt to access
10850 	 * the unit & verify the geometry/label. This can be the case for
10851 	 * removable-media devices, of if the device was opened in
10852 	 * NDELAY/NONBLOCK mode.
10853 	 */
10854 	if (!SD_IS_VALID_LABEL(un) &&
10855 	    (sd_ready_and_valid(un) != SD_READY_VALID)) {
10856 		/*
10857 		 * For removable devices it is possible to start an I/O
10858 		 * without a media by opening the device in nodelay mode.
10859 		 * Also for writable CDs there can be many scenarios where
10860 		 * there is no geometry yet but volume manager is trying to
10861 		 * issue a read() just because it can see TOC on the CD. So
10862 		 * do not print a message for removables.
10863 		 */
10864 		if (!un->un_f_has_removable_media) {
10865 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
10866 			    "i/o to invalid geometry\n");
10867 		}
10868 		bioerror(bp, EIO);
10869 		bp->b_resid = bp->b_bcount;
10870 		SD_BEGIN_IODONE(index, un, bp);
10871 		return;
10872 	}
10873 
10874 	partition = SDPART(bp->b_edev);
10875 
10876 	nblocks = 0;
10877 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
10878 	    &nblocks, &partition_offset, NULL, NULL, (void *)SD_PATH_DIRECT);
10879 
10880 	/*
10881 	 * blocknum is the starting block number of the request. At this
10882 	 * point it is still relative to the start of the minor device.
10883 	 */
10884 	blocknum = xp->xb_blkno;
10885 
10886 	/*
10887 	 * Legacy: If the starting block number is one past the last block
10888 	 * in the partition, do not set B_ERROR in the buf.
10889 	 */
10890 	if (blocknum == nblocks)  {
10891 		goto error_exit;
10892 	}
10893 
10894 	/*
10895 	 * Confirm that the first block of the request lies within the
10896 	 * partition limits. Also the requested number of bytes must be
10897 	 * a multiple of the system block size.
10898 	 */
10899 	if ((blocknum < 0) || (blocknum >= nblocks) ||
10900 	    ((bp->b_bcount & (un->un_sys_blocksize - 1)) != 0)) {
10901 		bp->b_flags |= B_ERROR;
10902 		goto error_exit;
10903 	}
10904 
10905 	/*
10906 	 * If the requsted # blocks exceeds the available # blocks, that
10907 	 * is an overrun of the partition.
10908 	 */
10909 	requested_nblocks = SD_BYTES2SYSBLOCKS(un, bp->b_bcount);
10910 	available_nblocks = (size_t)(nblocks - blocknum);
10911 	ASSERT(nblocks >= blocknum);
10912 
10913 	if (requested_nblocks > available_nblocks) {
10914 		/*
10915 		 * Allocate an "overrun" buf to allow the request to proceed
10916 		 * for the amount of space available in the partition. The
10917 		 * amount not transferred will be added into the b_resid
10918 		 * when the operation is complete. The overrun buf
10919 		 * replaces the original buf here, and the original buf
10920 		 * is saved inside the overrun buf, for later use.
10921 		 */
10922 		size_t resid = SD_SYSBLOCKS2BYTES(un,
10923 		    (offset_t)(requested_nblocks - available_nblocks));
10924 		size_t count = bp->b_bcount - resid;
10925 		/*
10926 		 * Note: count is an unsigned entity thus it'll NEVER
10927 		 * be less than 0 so ASSERT the original values are
10928 		 * correct.
10929 		 */
10930 		ASSERT(bp->b_bcount >= resid);
10931 
10932 		bp = sd_bioclone_alloc(bp, count, blocknum,
10933 		    (int (*)(struct buf *)) sd_mapblockaddr_iodone);
10934 		xp = SD_GET_XBUF(bp); /* Update for 'new' bp! */
10935 		ASSERT(xp != NULL);
10936 	}
10937 
10938 	/* At this point there should be no residual for this buf. */
10939 	ASSERT(bp->b_resid == 0);
10940 
10941 	/* Convert the block number to an absolute address. */
10942 	xp->xb_blkno += partition_offset;
10943 
10944 	SD_NEXT_IOSTART(index, un, bp);
10945 
10946 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10947 	    "sd_mapblockaddr_iostart: exit 0: buf:0x%p\n", bp);
10948 
10949 	return;
10950 
10951 error_exit:
10952 	bp->b_resid = bp->b_bcount;
10953 	SD_BEGIN_IODONE(index, un, bp);
10954 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10955 	    "sd_mapblockaddr_iostart: exit 1: buf:0x%p\n", bp);
10956 }
10957 
10958 
10959 /*
10960  *    Function: sd_mapblockaddr_iodone
10961  *
10962  * Description: Completion-side processing for partition management.
10963  *
10964  *     Context: May be called under interrupt context
10965  */
10966 
10967 static void
10968 sd_mapblockaddr_iodone(int index, struct sd_lun *un, struct buf *bp)
10969 {
10970 	/* int	partition; */	/* Not used, see below. */
10971 	ASSERT(un != NULL);
10972 	ASSERT(bp != NULL);
10973 	ASSERT(!mutex_owned(SD_MUTEX(un)));
10974 
10975 	SD_TRACE(SD_LOG_IO_PARTITION, un,
10976 	    "sd_mapblockaddr_iodone: entry: buf:0x%p\n", bp);
10977 
10978 	if (bp->b_iodone == (int (*)(struct buf *)) sd_mapblockaddr_iodone) {
10979 		/*
10980 		 * We have an "overrun" buf to deal with...
10981 		 */
10982 		struct sd_xbuf	*xp;
10983 		struct buf	*obp;	/* ptr to the original buf */
10984 
10985 		xp = SD_GET_XBUF(bp);
10986 		ASSERT(xp != NULL);
10987 
10988 		/* Retrieve the pointer to the original buf */
10989 		obp = (struct buf *)xp->xb_private;
10990 		ASSERT(obp != NULL);
10991 
10992 		obp->b_resid = obp->b_bcount - (bp->b_bcount - bp->b_resid);
10993 		bioerror(obp, bp->b_error);
10994 
10995 		sd_bioclone_free(bp);
10996 
10997 		/*
10998 		 * Get back the original buf.
10999 		 * Note that since the restoration of xb_blkno below
11000 		 * was removed, the sd_xbuf is not needed.
11001 		 */
11002 		bp = obp;
11003 		/*
11004 		 * xp = SD_GET_XBUF(bp);
11005 		 * ASSERT(xp != NULL);
11006 		 */
11007 	}
11008 
11009 	/*
11010 	 * Convert sd->xb_blkno back to a minor-device relative value.
11011 	 * Note: this has been commented out, as it is not needed in the
11012 	 * current implementation of the driver (ie, since this function
11013 	 * is at the top of the layering chains, so the info will be
11014 	 * discarded) and it is in the "hot" IO path.
11015 	 *
11016 	 * partition = getminor(bp->b_edev) & SDPART_MASK;
11017 	 * xp->xb_blkno -= un->un_offset[partition];
11018 	 */
11019 
11020 	SD_NEXT_IODONE(index, un, bp);
11021 
11022 	SD_TRACE(SD_LOG_IO_PARTITION, un,
11023 	    "sd_mapblockaddr_iodone: exit: buf:0x%p\n", bp);
11024 }
11025 
11026 
11027 /*
11028  *    Function: sd_mapblocksize_iostart
11029  *
11030  * Description: Convert between system block size (un->un_sys_blocksize)
11031  *		and target block size (un->un_tgt_blocksize).
11032  *
11033  *     Context: Can sleep to allocate resources.
11034  *
11035  * Assumptions: A higher layer has already performed any partition validation,
11036  *		and converted the xp->xb_blkno to an absolute value relative
11037  *		to the start of the device.
11038  *
11039  *		It is also assumed that the higher layer has implemented
11040  *		an "overrun" mechanism for the case where the request would
11041  *		read/write beyond the end of a partition.  In this case we
11042  *		assume (and ASSERT) that bp->b_resid == 0.
11043  *
11044  *		Note: The implementation for this routine assumes the target
11045  *		block size remains constant between allocation and transport.
11046  */
11047 
11048 static void
11049 sd_mapblocksize_iostart(int index, struct sd_lun *un, struct buf *bp)
11050 {
11051 	struct sd_mapblocksize_info	*bsp;
11052 	struct sd_xbuf			*xp;
11053 	offset_t first_byte;
11054 	daddr_t	start_block, end_block;
11055 	daddr_t	request_bytes;
11056 	ushort_t is_aligned = FALSE;
11057 
11058 	ASSERT(un != NULL);
11059 	ASSERT(bp != NULL);
11060 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11061 	ASSERT(bp->b_resid == 0);
11062 
11063 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11064 	    "sd_mapblocksize_iostart: entry: buf:0x%p\n", bp);
11065 
11066 	/*
11067 	 * For a non-writable CD, a write request is an error
11068 	 */
11069 	if (ISCD(un) && ((bp->b_flags & B_READ) == 0) &&
11070 	    (un->un_f_mmc_writable_media == FALSE)) {
11071 		bioerror(bp, EIO);
11072 		bp->b_resid = bp->b_bcount;
11073 		SD_BEGIN_IODONE(index, un, bp);
11074 		return;
11075 	}
11076 
11077 	/*
11078 	 * We do not need a shadow buf if the device is using
11079 	 * un->un_sys_blocksize as its block size or if bcount == 0.
11080 	 * In this case there is no layer-private data block allocated.
11081 	 */
11082 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
11083 	    (bp->b_bcount == 0)) {
11084 		goto done;
11085 	}
11086 
11087 #if defined(__i386) || defined(__amd64)
11088 	/* We do not support non-block-aligned transfers for ROD devices */
11089 	ASSERT(!ISROD(un));
11090 #endif
11091 
11092 	xp = SD_GET_XBUF(bp);
11093 	ASSERT(xp != NULL);
11094 
11095 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11096 	    "tgt_blocksize:0x%x sys_blocksize: 0x%x\n",
11097 	    un->un_tgt_blocksize, un->un_sys_blocksize);
11098 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11099 	    "request start block:0x%x\n", xp->xb_blkno);
11100 	SD_INFO(SD_LOG_IO_RMMEDIA, un, "sd_mapblocksize_iostart: "
11101 	    "request len:0x%x\n", bp->b_bcount);
11102 
11103 	/*
11104 	 * Allocate the layer-private data area for the mapblocksize layer.
11105 	 * Layers are allowed to use the xp_private member of the sd_xbuf
11106 	 * struct to store the pointer to their layer-private data block, but
11107 	 * each layer also has the responsibility of restoring the prior
11108 	 * contents of xb_private before returning the buf/xbuf to the
11109 	 * higher layer that sent it.
11110 	 *
11111 	 * Here we save the prior contents of xp->xb_private into the
11112 	 * bsp->mbs_oprivate field of our layer-private data area. This value
11113 	 * is restored by sd_mapblocksize_iodone() just prior to freeing up
11114 	 * the layer-private area and returning the buf/xbuf to the layer
11115 	 * that sent it.
11116 	 *
11117 	 * Note that here we use kmem_zalloc for the allocation as there are
11118 	 * parts of the mapblocksize code that expect certain fields to be
11119 	 * zero unless explicitly set to a required value.
11120 	 */
11121 	bsp = kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
11122 	bsp->mbs_oprivate = xp->xb_private;
11123 	xp->xb_private = bsp;
11124 
11125 	/*
11126 	 * This treats the data on the disk (target) as an array of bytes.
11127 	 * first_byte is the byte offset, from the beginning of the device,
11128 	 * to the location of the request. This is converted from a
11129 	 * un->un_sys_blocksize block address to a byte offset, and then back
11130 	 * to a block address based upon a un->un_tgt_blocksize block size.
11131 	 *
11132 	 * xp->xb_blkno should be absolute upon entry into this function,
11133 	 * but, but it is based upon partitions that use the "system"
11134 	 * block size. It must be adjusted to reflect the block size of
11135 	 * the target.
11136 	 *
11137 	 * Note that end_block is actually the block that follows the last
11138 	 * block of the request, but that's what is needed for the computation.
11139 	 */
11140 	first_byte  = SD_SYSBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
11141 	start_block = xp->xb_blkno = first_byte / un->un_tgt_blocksize;
11142 	end_block   = (first_byte + bp->b_bcount + un->un_tgt_blocksize - 1) /
11143 	    un->un_tgt_blocksize;
11144 
11145 	/* request_bytes is rounded up to a multiple of the target block size */
11146 	request_bytes = (end_block - start_block) * un->un_tgt_blocksize;
11147 
11148 	/*
11149 	 * See if the starting address of the request and the request
11150 	 * length are aligned on a un->un_tgt_blocksize boundary. If aligned
11151 	 * then we do not need to allocate a shadow buf to handle the request.
11152 	 */
11153 	if (((first_byte   % un->un_tgt_blocksize) == 0) &&
11154 	    ((bp->b_bcount % un->un_tgt_blocksize) == 0)) {
11155 		is_aligned = TRUE;
11156 	}
11157 
11158 	if ((bp->b_flags & B_READ) == 0) {
11159 		/*
11160 		 * Lock the range for a write operation. An aligned request is
11161 		 * considered a simple write; otherwise the request must be a
11162 		 * read-modify-write.
11163 		 */
11164 		bsp->mbs_wmp = sd_range_lock(un, start_block, end_block - 1,
11165 		    (is_aligned == TRUE) ? SD_WTYPE_SIMPLE : SD_WTYPE_RMW);
11166 	}
11167 
11168 	/*
11169 	 * Alloc a shadow buf if the request is not aligned. Also, this is
11170 	 * where the READ command is generated for a read-modify-write. (The
11171 	 * write phase is deferred until after the read completes.)
11172 	 */
11173 	if (is_aligned == FALSE) {
11174 
11175 		struct sd_mapblocksize_info	*shadow_bsp;
11176 		struct sd_xbuf	*shadow_xp;
11177 		struct buf	*shadow_bp;
11178 
11179 		/*
11180 		 * Allocate the shadow buf and it associated xbuf. Note that
11181 		 * after this call the xb_blkno value in both the original
11182 		 * buf's sd_xbuf _and_ the shadow buf's sd_xbuf will be the
11183 		 * same: absolute relative to the start of the device, and
11184 		 * adjusted for the target block size. The b_blkno in the
11185 		 * shadow buf will also be set to this value. We should never
11186 		 * change b_blkno in the original bp however.
11187 		 *
11188 		 * Note also that the shadow buf will always need to be a
11189 		 * READ command, regardless of whether the incoming command
11190 		 * is a READ or a WRITE.
11191 		 */
11192 		shadow_bp = sd_shadow_buf_alloc(bp, request_bytes, B_READ,
11193 		    xp->xb_blkno,
11194 		    (int (*)(struct buf *)) sd_mapblocksize_iodone);
11195 
11196 		shadow_xp = SD_GET_XBUF(shadow_bp);
11197 
11198 		/*
11199 		 * Allocate the layer-private data for the shadow buf.
11200 		 * (No need to preserve xb_private in the shadow xbuf.)
11201 		 */
11202 		shadow_xp->xb_private = shadow_bsp =
11203 		    kmem_zalloc(sizeof (struct sd_mapblocksize_info), KM_SLEEP);
11204 
11205 		/*
11206 		 * bsp->mbs_copy_offset is used later by sd_mapblocksize_iodone
11207 		 * to figure out where the start of the user data is (based upon
11208 		 * the system block size) in the data returned by the READ
11209 		 * command (which will be based upon the target blocksize). Note
11210 		 * that this is only really used if the request is unaligned.
11211 		 */
11212 		bsp->mbs_copy_offset = (ssize_t)(first_byte -
11213 		    ((offset_t)xp->xb_blkno * un->un_tgt_blocksize));
11214 		ASSERT((bsp->mbs_copy_offset >= 0) &&
11215 		    (bsp->mbs_copy_offset < un->un_tgt_blocksize));
11216 
11217 		shadow_bsp->mbs_copy_offset = bsp->mbs_copy_offset;
11218 
11219 		shadow_bsp->mbs_layer_index = bsp->mbs_layer_index = index;
11220 
11221 		/* Transfer the wmap (if any) to the shadow buf */
11222 		shadow_bsp->mbs_wmp = bsp->mbs_wmp;
11223 		bsp->mbs_wmp = NULL;
11224 
11225 		/*
11226 		 * The shadow buf goes on from here in place of the
11227 		 * original buf.
11228 		 */
11229 		shadow_bsp->mbs_orig_bp = bp;
11230 		bp = shadow_bp;
11231 	}
11232 
11233 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11234 	    "sd_mapblocksize_iostart: tgt start block:0x%x\n", xp->xb_blkno);
11235 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11236 	    "sd_mapblocksize_iostart: tgt request len:0x%x\n",
11237 	    request_bytes);
11238 	SD_INFO(SD_LOG_IO_RMMEDIA, un,
11239 	    "sd_mapblocksize_iostart: shadow buf:0x%x\n", bp);
11240 
11241 done:
11242 	SD_NEXT_IOSTART(index, un, bp);
11243 
11244 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11245 	    "sd_mapblocksize_iostart: exit: buf:0x%p\n", bp);
11246 }
11247 
11248 
11249 /*
11250  *    Function: sd_mapblocksize_iodone
11251  *
11252  * Description: Completion side processing for block-size mapping.
11253  *
11254  *     Context: May be called under interrupt context
11255  */
11256 
11257 static void
11258 sd_mapblocksize_iodone(int index, struct sd_lun *un, struct buf *bp)
11259 {
11260 	struct sd_mapblocksize_info	*bsp;
11261 	struct sd_xbuf	*xp;
11262 	struct sd_xbuf	*orig_xp;	/* sd_xbuf for the original buf */
11263 	struct buf	*orig_bp;	/* ptr to the original buf */
11264 	offset_t	shadow_end;
11265 	offset_t	request_end;
11266 	offset_t	shadow_start;
11267 	ssize_t		copy_offset;
11268 	size_t		copy_length;
11269 	size_t		shortfall;
11270 	uint_t		is_write;	/* TRUE if this bp is a WRITE */
11271 	uint_t		has_wmap;	/* TRUE is this bp has a wmap */
11272 
11273 	ASSERT(un != NULL);
11274 	ASSERT(bp != NULL);
11275 
11276 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
11277 	    "sd_mapblocksize_iodone: entry: buf:0x%p\n", bp);
11278 
11279 	/*
11280 	 * There is no shadow buf or layer-private data if the target is
11281 	 * using un->un_sys_blocksize as its block size or if bcount == 0.
11282 	 */
11283 	if ((un->un_tgt_blocksize == un->un_sys_blocksize) ||
11284 	    (bp->b_bcount == 0)) {
11285 		goto exit;
11286 	}
11287 
11288 	xp = SD_GET_XBUF(bp);
11289 	ASSERT(xp != NULL);
11290 
11291 	/* Retrieve the pointer to the layer-private data area from the xbuf. */
11292 	bsp = xp->xb_private;
11293 
11294 	is_write = ((bp->b_flags & B_READ) == 0) ? TRUE : FALSE;
11295 	has_wmap = (bsp->mbs_wmp != NULL) ? TRUE : FALSE;
11296 
11297 	if (is_write) {
11298 		/*
11299 		 * For a WRITE request we must free up the block range that
11300 		 * we have locked up.  This holds regardless of whether this is
11301 		 * an aligned write request or a read-modify-write request.
11302 		 */
11303 		sd_range_unlock(un, bsp->mbs_wmp);
11304 		bsp->mbs_wmp = NULL;
11305 	}
11306 
11307 	if ((bp->b_iodone != (int(*)(struct buf *))sd_mapblocksize_iodone)) {
11308 		/*
11309 		 * An aligned read or write command will have no shadow buf;
11310 		 * there is not much else to do with it.
11311 		 */
11312 		goto done;
11313 	}
11314 
11315 	orig_bp = bsp->mbs_orig_bp;
11316 	ASSERT(orig_bp != NULL);
11317 	orig_xp = SD_GET_XBUF(orig_bp);
11318 	ASSERT(orig_xp != NULL);
11319 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11320 
11321 	if (!is_write && has_wmap) {
11322 		/*
11323 		 * A READ with a wmap means this is the READ phase of a
11324 		 * read-modify-write. If an error occurred on the READ then
11325 		 * we do not proceed with the WRITE phase or copy any data.
11326 		 * Just release the write maps and return with an error.
11327 		 */
11328 		if ((bp->b_resid != 0) || (bp->b_error != 0)) {
11329 			orig_bp->b_resid = orig_bp->b_bcount;
11330 			bioerror(orig_bp, bp->b_error);
11331 			sd_range_unlock(un, bsp->mbs_wmp);
11332 			goto freebuf_done;
11333 		}
11334 	}
11335 
11336 	/*
11337 	 * Here is where we set up to copy the data from the shadow buf
11338 	 * into the space associated with the original buf.
11339 	 *
11340 	 * To deal with the conversion between block sizes, these
11341 	 * computations treat the data as an array of bytes, with the
11342 	 * first byte (byte 0) corresponding to the first byte in the
11343 	 * first block on the disk.
11344 	 */
11345 
11346 	/*
11347 	 * shadow_start and shadow_len indicate the location and size of
11348 	 * the data returned with the shadow IO request.
11349 	 */
11350 	shadow_start  = SD_TGTBLOCKS2BYTES(un, (offset_t)xp->xb_blkno);
11351 	shadow_end    = shadow_start + bp->b_bcount - bp->b_resid;
11352 
11353 	/*
11354 	 * copy_offset gives the offset (in bytes) from the start of the first
11355 	 * block of the READ request to the beginning of the data.  We retrieve
11356 	 * this value from xb_pktp in the ORIGINAL xbuf, as it has been saved
11357 	 * there by sd_mapblockize_iostart(). copy_length gives the amount of
11358 	 * data to be copied (in bytes).
11359 	 */
11360 	copy_offset  = bsp->mbs_copy_offset;
11361 	ASSERT((copy_offset >= 0) && (copy_offset < un->un_tgt_blocksize));
11362 	copy_length  = orig_bp->b_bcount;
11363 	request_end  = shadow_start + copy_offset + orig_bp->b_bcount;
11364 
11365 	/*
11366 	 * Set up the resid and error fields of orig_bp as appropriate.
11367 	 */
11368 	if (shadow_end >= request_end) {
11369 		/* We got all the requested data; set resid to zero */
11370 		orig_bp->b_resid = 0;
11371 	} else {
11372 		/*
11373 		 * We failed to get enough data to fully satisfy the original
11374 		 * request. Just copy back whatever data we got and set
11375 		 * up the residual and error code as required.
11376 		 *
11377 		 * 'shortfall' is the amount by which the data received with the
11378 		 * shadow buf has "fallen short" of the requested amount.
11379 		 */
11380 		shortfall = (size_t)(request_end - shadow_end);
11381 
11382 		if (shortfall > orig_bp->b_bcount) {
11383 			/*
11384 			 * We did not get enough data to even partially
11385 			 * fulfill the original request.  The residual is
11386 			 * equal to the amount requested.
11387 			 */
11388 			orig_bp->b_resid = orig_bp->b_bcount;
11389 		} else {
11390 			/*
11391 			 * We did not get all the data that we requested
11392 			 * from the device, but we will try to return what
11393 			 * portion we did get.
11394 			 */
11395 			orig_bp->b_resid = shortfall;
11396 		}
11397 		ASSERT(copy_length >= orig_bp->b_resid);
11398 		copy_length  -= orig_bp->b_resid;
11399 	}
11400 
11401 	/* Propagate the error code from the shadow buf to the original buf */
11402 	bioerror(orig_bp, bp->b_error);
11403 
11404 	if (is_write) {
11405 		goto freebuf_done;	/* No data copying for a WRITE */
11406 	}
11407 
11408 	if (has_wmap) {
11409 		/*
11410 		 * This is a READ command from the READ phase of a
11411 		 * read-modify-write request. We have to copy the data given
11412 		 * by the user OVER the data returned by the READ command,
11413 		 * then convert the command from a READ to a WRITE and send
11414 		 * it back to the target.
11415 		 */
11416 		bcopy(orig_bp->b_un.b_addr, bp->b_un.b_addr + copy_offset,
11417 		    copy_length);
11418 
11419 		bp->b_flags &= ~((int)B_READ);	/* Convert to a WRITE */
11420 
11421 		/*
11422 		 * Dispatch the WRITE command to the taskq thread, which
11423 		 * will in turn send the command to the target. When the
11424 		 * WRITE command completes, we (sd_mapblocksize_iodone())
11425 		 * will get called again as part of the iodone chain
11426 		 * processing for it. Note that we will still be dealing
11427 		 * with the shadow buf at that point.
11428 		 */
11429 		if (taskq_dispatch(sd_wmr_tq, sd_read_modify_write_task, bp,
11430 		    KM_NOSLEEP) != 0) {
11431 			/*
11432 			 * Dispatch was successful so we are done. Return
11433 			 * without going any higher up the iodone chain. Do
11434 			 * not free up any layer-private data until after the
11435 			 * WRITE completes.
11436 			 */
11437 			return;
11438 		}
11439 
11440 		/*
11441 		 * Dispatch of the WRITE command failed; set up the error
11442 		 * condition and send this IO back up the iodone chain.
11443 		 */
11444 		bioerror(orig_bp, EIO);
11445 		orig_bp->b_resid = orig_bp->b_bcount;
11446 
11447 	} else {
11448 		/*
11449 		 * This is a regular READ request (ie, not a RMW). Copy the
11450 		 * data from the shadow buf into the original buf. The
11451 		 * copy_offset compensates for any "misalignment" between the
11452 		 * shadow buf (with its un->un_tgt_blocksize blocks) and the
11453 		 * original buf (with its un->un_sys_blocksize blocks).
11454 		 */
11455 		bcopy(bp->b_un.b_addr + copy_offset, orig_bp->b_un.b_addr,
11456 		    copy_length);
11457 	}
11458 
11459 freebuf_done:
11460 
11461 	/*
11462 	 * At this point we still have both the shadow buf AND the original
11463 	 * buf to deal with, as well as the layer-private data area in each.
11464 	 * Local variables are as follows:
11465 	 *
11466 	 * bp -- points to shadow buf
11467 	 * xp -- points to xbuf of shadow buf
11468 	 * bsp -- points to layer-private data area of shadow buf
11469 	 * orig_bp -- points to original buf
11470 	 *
11471 	 * First free the shadow buf and its associated xbuf, then free the
11472 	 * layer-private data area from the shadow buf. There is no need to
11473 	 * restore xb_private in the shadow xbuf.
11474 	 */
11475 	sd_shadow_buf_free(bp);
11476 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11477 
11478 	/*
11479 	 * Now update the local variables to point to the original buf, xbuf,
11480 	 * and layer-private area.
11481 	 */
11482 	bp = orig_bp;
11483 	xp = SD_GET_XBUF(bp);
11484 	ASSERT(xp != NULL);
11485 	ASSERT(xp == orig_xp);
11486 	bsp = xp->xb_private;
11487 	ASSERT(bsp != NULL);
11488 
11489 done:
11490 	/*
11491 	 * Restore xb_private to whatever it was set to by the next higher
11492 	 * layer in the chain, then free the layer-private data area.
11493 	 */
11494 	xp->xb_private = bsp->mbs_oprivate;
11495 	kmem_free(bsp, sizeof (struct sd_mapblocksize_info));
11496 
11497 exit:
11498 	SD_TRACE(SD_LOG_IO_RMMEDIA, SD_GET_UN(bp),
11499 	    "sd_mapblocksize_iodone: calling SD_NEXT_IODONE: buf:0x%p\n", bp);
11500 
11501 	SD_NEXT_IODONE(index, un, bp);
11502 }
11503 
11504 
11505 /*
11506  *    Function: sd_checksum_iostart
11507  *
11508  * Description: A stub function for a layer that's currently not used.
11509  *		For now just a placeholder.
11510  *
11511  *     Context: Kernel thread context
11512  */
11513 
11514 static void
11515 sd_checksum_iostart(int index, struct sd_lun *un, struct buf *bp)
11516 {
11517 	ASSERT(un != NULL);
11518 	ASSERT(bp != NULL);
11519 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11520 	SD_NEXT_IOSTART(index, un, bp);
11521 }
11522 
11523 
11524 /*
11525  *    Function: sd_checksum_iodone
11526  *
11527  * Description: A stub function for a layer that's currently not used.
11528  *		For now just a placeholder.
11529  *
11530  *     Context: May be called under interrupt context
11531  */
11532 
11533 static void
11534 sd_checksum_iodone(int index, struct sd_lun *un, struct buf *bp)
11535 {
11536 	ASSERT(un != NULL);
11537 	ASSERT(bp != NULL);
11538 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11539 	SD_NEXT_IODONE(index, un, bp);
11540 }
11541 
11542 
11543 /*
11544  *    Function: sd_checksum_uscsi_iostart
11545  *
11546  * Description: A stub function for a layer that's currently not used.
11547  *		For now just a placeholder.
11548  *
11549  *     Context: Kernel thread context
11550  */
11551 
11552 static void
11553 sd_checksum_uscsi_iostart(int index, struct sd_lun *un, struct buf *bp)
11554 {
11555 	ASSERT(un != NULL);
11556 	ASSERT(bp != NULL);
11557 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11558 	SD_NEXT_IOSTART(index, un, bp);
11559 }
11560 
11561 
11562 /*
11563  *    Function: sd_checksum_uscsi_iodone
11564  *
11565  * Description: A stub function for a layer that's currently not used.
11566  *		For now just a placeholder.
11567  *
11568  *     Context: May be called under interrupt context
11569  */
11570 
11571 static void
11572 sd_checksum_uscsi_iodone(int index, struct sd_lun *un, struct buf *bp)
11573 {
11574 	ASSERT(un != NULL);
11575 	ASSERT(bp != NULL);
11576 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11577 	SD_NEXT_IODONE(index, un, bp);
11578 }
11579 
11580 
11581 /*
11582  *    Function: sd_pm_iostart
11583  *
11584  * Description: iostart-side routine for Power mangement.
11585  *
11586  *     Context: Kernel thread context
11587  */
11588 
11589 static void
11590 sd_pm_iostart(int index, struct sd_lun *un, struct buf *bp)
11591 {
11592 	ASSERT(un != NULL);
11593 	ASSERT(bp != NULL);
11594 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11595 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11596 
11597 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: entry\n");
11598 
11599 	if (sd_pm_entry(un) != DDI_SUCCESS) {
11600 		/*
11601 		 * Set up to return the failed buf back up the 'iodone'
11602 		 * side of the calling chain.
11603 		 */
11604 		bioerror(bp, EIO);
11605 		bp->b_resid = bp->b_bcount;
11606 
11607 		SD_BEGIN_IODONE(index, un, bp);
11608 
11609 		SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11610 		return;
11611 	}
11612 
11613 	SD_NEXT_IOSTART(index, un, bp);
11614 
11615 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iostart: exit\n");
11616 }
11617 
11618 
11619 /*
11620  *    Function: sd_pm_iodone
11621  *
11622  * Description: iodone-side routine for power mangement.
11623  *
11624  *     Context: may be called from interrupt context
11625  */
11626 
11627 static void
11628 sd_pm_iodone(int index, struct sd_lun *un, struct buf *bp)
11629 {
11630 	ASSERT(un != NULL);
11631 	ASSERT(bp != NULL);
11632 	ASSERT(!mutex_owned(&un->un_pm_mutex));
11633 
11634 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: entry\n");
11635 
11636 	/*
11637 	 * After attach the following flag is only read, so don't
11638 	 * take the penalty of acquiring a mutex for it.
11639 	 */
11640 	if (un->un_f_pm_is_enabled == TRUE) {
11641 		sd_pm_exit(un);
11642 	}
11643 
11644 	SD_NEXT_IODONE(index, un, bp);
11645 
11646 	SD_TRACE(SD_LOG_IO_PM, un, "sd_pm_iodone: exit\n");
11647 }
11648 
11649 
11650 /*
11651  *    Function: sd_core_iostart
11652  *
11653  * Description: Primary driver function for enqueuing buf(9S) structs from
11654  *		the system and initiating IO to the target device
11655  *
11656  *     Context: Kernel thread context. Can sleep.
11657  *
11658  * Assumptions:  - The given xp->xb_blkno is absolute
11659  *		   (ie, relative to the start of the device).
11660  *		 - The IO is to be done using the native blocksize of
11661  *		   the device, as specified in un->un_tgt_blocksize.
11662  */
11663 /* ARGSUSED */
11664 static void
11665 sd_core_iostart(int index, struct sd_lun *un, struct buf *bp)
11666 {
11667 	struct sd_xbuf *xp;
11668 
11669 	ASSERT(un != NULL);
11670 	ASSERT(bp != NULL);
11671 	ASSERT(!mutex_owned(SD_MUTEX(un)));
11672 	ASSERT(bp->b_resid == 0);
11673 
11674 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: entry: bp:0x%p\n", bp);
11675 
11676 	xp = SD_GET_XBUF(bp);
11677 	ASSERT(xp != NULL);
11678 
11679 	mutex_enter(SD_MUTEX(un));
11680 
11681 	/*
11682 	 * If we are currently in the failfast state, fail any new IO
11683 	 * that has B_FAILFAST set, then return.
11684 	 */
11685 	if ((bp->b_flags & B_FAILFAST) &&
11686 	    (un->un_failfast_state == SD_FAILFAST_ACTIVE)) {
11687 		mutex_exit(SD_MUTEX(un));
11688 		bioerror(bp, EIO);
11689 		bp->b_resid = bp->b_bcount;
11690 		SD_BEGIN_IODONE(index, un, bp);
11691 		return;
11692 	}
11693 
11694 	if (SD_IS_DIRECT_PRIORITY(xp)) {
11695 		/*
11696 		 * Priority command -- transport it immediately.
11697 		 *
11698 		 * Note: We may want to assert that USCSI_DIAGNOSE is set,
11699 		 * because all direct priority commands should be associated
11700 		 * with error recovery actions which we don't want to retry.
11701 		 */
11702 		sd_start_cmds(un, bp);
11703 	} else {
11704 		/*
11705 		 * Normal command -- add it to the wait queue, then start
11706 		 * transporting commands from the wait queue.
11707 		 */
11708 		sd_add_buf_to_waitq(un, bp);
11709 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
11710 		sd_start_cmds(un, NULL);
11711 	}
11712 
11713 	mutex_exit(SD_MUTEX(un));
11714 
11715 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_core_iostart: exit: bp:0x%p\n", bp);
11716 }
11717 
11718 
11719 /*
11720  *    Function: sd_init_cdb_limits
11721  *
11722  * Description: This is to handle scsi_pkt initialization differences
11723  *		between the driver platforms.
11724  *
11725  *		Legacy behaviors:
11726  *
11727  *		If the block number or the sector count exceeds the
11728  *		capabilities of a Group 0 command, shift over to a
11729  *		Group 1 command. We don't blindly use Group 1
11730  *		commands because a) some drives (CDC Wren IVs) get a
11731  *		bit confused, and b) there is probably a fair amount
11732  *		of speed difference for a target to receive and decode
11733  *		a 10 byte command instead of a 6 byte command.
11734  *
11735  *		The xfer time difference of 6 vs 10 byte CDBs is
11736  *		still significant so this code is still worthwhile.
11737  *		10 byte CDBs are very inefficient with the fas HBA driver
11738  *		and older disks. Each CDB byte took 1 usec with some
11739  *		popular disks.
11740  *
11741  *     Context: Must be called at attach time
11742  */
11743 
11744 static void
11745 sd_init_cdb_limits(struct sd_lun *un)
11746 {
11747 	int hba_cdb_limit;
11748 
11749 	/*
11750 	 * Use CDB_GROUP1 commands for most devices except for
11751 	 * parallel SCSI fixed drives in which case we get better
11752 	 * performance using CDB_GROUP0 commands (where applicable).
11753 	 */
11754 	un->un_mincdb = SD_CDB_GROUP1;
11755 #if !defined(__fibre)
11756 	if (!un->un_f_is_fibre && !un->un_f_cfg_is_atapi && !ISROD(un) &&
11757 	    !un->un_f_has_removable_media) {
11758 		un->un_mincdb = SD_CDB_GROUP0;
11759 	}
11760 #endif
11761 
11762 	/*
11763 	 * Try to read the max-cdb-length supported by HBA.
11764 	 */
11765 	un->un_max_hba_cdb = scsi_ifgetcap(SD_ADDRESS(un), "max-cdb-length", 1);
11766 	if (0 >= un->un_max_hba_cdb) {
11767 		un->un_max_hba_cdb = CDB_GROUP4;
11768 		hba_cdb_limit = SD_CDB_GROUP4;
11769 	} else if (0 < un->un_max_hba_cdb &&
11770 	    un->un_max_hba_cdb < CDB_GROUP1) {
11771 		hba_cdb_limit = SD_CDB_GROUP0;
11772 	} else if (CDB_GROUP1 <= un->un_max_hba_cdb &&
11773 	    un->un_max_hba_cdb < CDB_GROUP5) {
11774 		hba_cdb_limit = SD_CDB_GROUP1;
11775 	} else if (CDB_GROUP5 <= un->un_max_hba_cdb &&
11776 	    un->un_max_hba_cdb < CDB_GROUP4) {
11777 		hba_cdb_limit = SD_CDB_GROUP5;
11778 	} else {
11779 		hba_cdb_limit = SD_CDB_GROUP4;
11780 	}
11781 
11782 	/*
11783 	 * Use CDB_GROUP5 commands for removable devices.  Use CDB_GROUP4
11784 	 * commands for fixed disks unless we are building for a 32 bit
11785 	 * kernel.
11786 	 */
11787 #ifdef _LP64
11788 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11789 	    min(hba_cdb_limit, SD_CDB_GROUP4);
11790 #else
11791 	un->un_maxcdb = (un->un_f_has_removable_media) ? SD_CDB_GROUP5 :
11792 	    min(hba_cdb_limit, SD_CDB_GROUP1);
11793 #endif
11794 
11795 	un->un_status_len = (int)((un->un_f_arq_enabled == TRUE)
11796 	    ? sizeof (struct scsi_arq_status) : 1);
11797 	un->un_cmd_timeout = (ushort_t)sd_io_time;
11798 	un->un_uscsi_timeout = ((ISCD(un)) ? 2 : 1) * un->un_cmd_timeout;
11799 }
11800 
11801 
11802 /*
11803  *    Function: sd_initpkt_for_buf
11804  *
11805  * Description: Allocate and initialize for transport a scsi_pkt struct,
11806  *		based upon the info specified in the given buf struct.
11807  *
11808  *		Assumes the xb_blkno in the request is absolute (ie,
11809  *		relative to the start of the device (NOT partition!).
11810  *		Also assumes that the request is using the native block
11811  *		size of the device (as returned by the READ CAPACITY
11812  *		command).
11813  *
11814  * Return Code: SD_PKT_ALLOC_SUCCESS
11815  *		SD_PKT_ALLOC_FAILURE
11816  *		SD_PKT_ALLOC_FAILURE_NO_DMA
11817  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11818  *
11819  *     Context: Kernel thread and may be called from software interrupt context
11820  *		as part of a sdrunout callback. This function may not block or
11821  *		call routines that block
11822  */
11823 
11824 static int
11825 sd_initpkt_for_buf(struct buf *bp, struct scsi_pkt **pktpp)
11826 {
11827 	struct sd_xbuf	*xp;
11828 	struct scsi_pkt *pktp = NULL;
11829 	struct sd_lun	*un;
11830 	size_t		blockcount;
11831 	daddr_t		startblock;
11832 	int		rval;
11833 	int		cmd_flags;
11834 
11835 	ASSERT(bp != NULL);
11836 	ASSERT(pktpp != NULL);
11837 	xp = SD_GET_XBUF(bp);
11838 	ASSERT(xp != NULL);
11839 	un = SD_GET_UN(bp);
11840 	ASSERT(un != NULL);
11841 	ASSERT(mutex_owned(SD_MUTEX(un)));
11842 	ASSERT(bp->b_resid == 0);
11843 
11844 	SD_TRACE(SD_LOG_IO_CORE, un,
11845 	    "sd_initpkt_for_buf: entry: buf:0x%p\n", bp);
11846 
11847 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11848 	if (xp->xb_pkt_flags & SD_XB_DMA_FREED) {
11849 		/*
11850 		 * Already have a scsi_pkt -- just need DMA resources.
11851 		 * We must recompute the CDB in case the mapping returns
11852 		 * a nonzero pkt_resid.
11853 		 * Note: if this is a portion of a PKT_DMA_PARTIAL transfer
11854 		 * that is being retried, the unmap/remap of the DMA resouces
11855 		 * will result in the entire transfer starting over again
11856 		 * from the very first block.
11857 		 */
11858 		ASSERT(xp->xb_pktp != NULL);
11859 		pktp = xp->xb_pktp;
11860 	} else {
11861 		pktp = NULL;
11862 	}
11863 #endif /* __i386 || __amd64 */
11864 
11865 	startblock = xp->xb_blkno;	/* Absolute block num. */
11866 	blockcount = SD_BYTES2TGTBLOCKS(un, bp->b_bcount);
11867 
11868 	cmd_flags = un->un_pkt_flags | (xp->xb_pkt_flags & SD_XB_INITPKT_MASK);
11869 
11870 	/*
11871 	 * sd_setup_rw_pkt will determine the appropriate CDB group to use,
11872 	 * call scsi_init_pkt, and build the CDB.
11873 	 */
11874 	rval = sd_setup_rw_pkt(un, &pktp, bp,
11875 	    cmd_flags, sdrunout, (caddr_t)un,
11876 	    startblock, blockcount);
11877 
11878 	if (rval == 0) {
11879 		/*
11880 		 * Success.
11881 		 *
11882 		 * If partial DMA is being used and required for this transfer.
11883 		 * set it up here.
11884 		 */
11885 		if ((un->un_pkt_flags & PKT_DMA_PARTIAL) != 0 &&
11886 		    (pktp->pkt_resid != 0)) {
11887 
11888 			/*
11889 			 * Save the CDB length and pkt_resid for the
11890 			 * next xfer
11891 			 */
11892 			xp->xb_dma_resid = pktp->pkt_resid;
11893 
11894 			/* rezero resid */
11895 			pktp->pkt_resid = 0;
11896 
11897 		} else {
11898 			xp->xb_dma_resid = 0;
11899 		}
11900 
11901 		pktp->pkt_flags = un->un_tagflags;
11902 		pktp->pkt_time  = un->un_cmd_timeout;
11903 		pktp->pkt_comp  = sdintr;
11904 
11905 		pktp->pkt_private = bp;
11906 		*pktpp = pktp;
11907 
11908 		SD_TRACE(SD_LOG_IO_CORE, un,
11909 		    "sd_initpkt_for_buf: exit: buf:0x%p\n", bp);
11910 
11911 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
11912 		xp->xb_pkt_flags &= ~SD_XB_DMA_FREED;
11913 #endif
11914 
11915 		return (SD_PKT_ALLOC_SUCCESS);
11916 
11917 	}
11918 
11919 	/*
11920 	 * SD_PKT_ALLOC_FAILURE is the only expected failure code
11921 	 * from sd_setup_rw_pkt.
11922 	 */
11923 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
11924 
11925 	if (rval == SD_PKT_ALLOC_FAILURE) {
11926 		*pktpp = NULL;
11927 		/*
11928 		 * Set the driver state to RWAIT to indicate the driver
11929 		 * is waiting on resource allocations. The driver will not
11930 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
11931 		 */
11932 		New_state(un, SD_STATE_RWAIT);
11933 
11934 		SD_ERROR(SD_LOG_IO_CORE, un,
11935 		    "sd_initpkt_for_buf: No pktp. exit bp:0x%p\n", bp);
11936 
11937 		if ((bp->b_flags & B_ERROR) != 0) {
11938 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
11939 		}
11940 		return (SD_PKT_ALLOC_FAILURE);
11941 	} else {
11942 		/*
11943 		 * PKT_ALLOC_FAILURE_CDB_TOO_SMALL
11944 		 *
11945 		 * This should never happen.  Maybe someone messed with the
11946 		 * kernel's minphys?
11947 		 */
11948 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
11949 		    "Request rejected: too large for CDB: "
11950 		    "lba:0x%08lx  len:0x%08lx\n", startblock, blockcount);
11951 		SD_ERROR(SD_LOG_IO_CORE, un,
11952 		    "sd_initpkt_for_buf: No cp. exit bp:0x%p\n", bp);
11953 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
11954 
11955 	}
11956 }
11957 
11958 
11959 /*
11960  *    Function: sd_destroypkt_for_buf
11961  *
11962  * Description: Free the scsi_pkt(9S) for the given bp (buf IO processing).
11963  *
11964  *     Context: Kernel thread or interrupt context
11965  */
11966 
11967 static void
11968 sd_destroypkt_for_buf(struct buf *bp)
11969 {
11970 	ASSERT(bp != NULL);
11971 	ASSERT(SD_GET_UN(bp) != NULL);
11972 
11973 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11974 	    "sd_destroypkt_for_buf: entry: buf:0x%p\n", bp);
11975 
11976 	ASSERT(SD_GET_PKTP(bp) != NULL);
11977 	scsi_destroy_pkt(SD_GET_PKTP(bp));
11978 
11979 	SD_TRACE(SD_LOG_IO_CORE, SD_GET_UN(bp),
11980 	    "sd_destroypkt_for_buf: exit: buf:0x%p\n", bp);
11981 }
11982 
11983 /*
11984  *    Function: sd_setup_rw_pkt
11985  *
11986  * Description: Determines appropriate CDB group for the requested LBA
11987  *		and transfer length, calls scsi_init_pkt, and builds
11988  *		the CDB.  Do not use for partial DMA transfers except
11989  *		for the initial transfer since the CDB size must
11990  *		remain constant.
11991  *
11992  *     Context: Kernel thread and may be called from software interrupt
11993  *		context as part of a sdrunout callback. This function may not
11994  *		block or call routines that block
11995  */
11996 
11997 
11998 int
11999 sd_setup_rw_pkt(struct sd_lun *un,
12000     struct scsi_pkt **pktpp, struct buf *bp, int flags,
12001     int (*callback)(caddr_t), caddr_t callback_arg,
12002     diskaddr_t lba, uint32_t blockcount)
12003 {
12004 	struct scsi_pkt *return_pktp;
12005 	union scsi_cdb *cdbp;
12006 	struct sd_cdbinfo *cp = NULL;
12007 	int i;
12008 
12009 	/*
12010 	 * See which size CDB to use, based upon the request.
12011 	 */
12012 	for (i = un->un_mincdb; i <= un->un_maxcdb; i++) {
12013 
12014 		/*
12015 		 * Check lba and block count against sd_cdbtab limits.
12016 		 * In the partial DMA case, we have to use the same size
12017 		 * CDB for all the transfers.  Check lba + blockcount
12018 		 * against the max LBA so we know that segment of the
12019 		 * transfer can use the CDB we select.
12020 		 */
12021 		if ((lba + blockcount - 1 <= sd_cdbtab[i].sc_maxlba) &&
12022 		    (blockcount <= sd_cdbtab[i].sc_maxlen)) {
12023 
12024 			/*
12025 			 * The command will fit into the CDB type
12026 			 * specified by sd_cdbtab[i].
12027 			 */
12028 			cp = sd_cdbtab + i;
12029 
12030 			/*
12031 			 * Call scsi_init_pkt so we can fill in the
12032 			 * CDB.
12033 			 */
12034 			return_pktp = scsi_init_pkt(SD_ADDRESS(un), *pktpp,
12035 			    bp, cp->sc_grpcode, un->un_status_len, 0,
12036 			    flags, callback, callback_arg);
12037 
12038 			if (return_pktp != NULL) {
12039 
12040 				/*
12041 				 * Return new value of pkt
12042 				 */
12043 				*pktpp = return_pktp;
12044 
12045 				/*
12046 				 * To be safe, zero the CDB insuring there is
12047 				 * no leftover data from a previous command.
12048 				 */
12049 				bzero(return_pktp->pkt_cdbp, cp->sc_grpcode);
12050 
12051 				/*
12052 				 * Handle partial DMA mapping
12053 				 */
12054 				if (return_pktp->pkt_resid != 0) {
12055 
12056 					/*
12057 					 * Not going to xfer as many blocks as
12058 					 * originally expected
12059 					 */
12060 					blockcount -=
12061 					    SD_BYTES2TGTBLOCKS(un,
12062 					    return_pktp->pkt_resid);
12063 				}
12064 
12065 				cdbp = (union scsi_cdb *)return_pktp->pkt_cdbp;
12066 
12067 				/*
12068 				 * Set command byte based on the CDB
12069 				 * type we matched.
12070 				 */
12071 				cdbp->scc_cmd = cp->sc_grpmask |
12072 				    ((bp->b_flags & B_READ) ?
12073 				    SCMD_READ : SCMD_WRITE);
12074 
12075 				SD_FILL_SCSI1_LUN(un, return_pktp);
12076 
12077 				/*
12078 				 * Fill in LBA and length
12079 				 */
12080 				ASSERT((cp->sc_grpcode == CDB_GROUP1) ||
12081 				    (cp->sc_grpcode == CDB_GROUP4) ||
12082 				    (cp->sc_grpcode == CDB_GROUP0) ||
12083 				    (cp->sc_grpcode == CDB_GROUP5));
12084 
12085 				if (cp->sc_grpcode == CDB_GROUP1) {
12086 					FORMG1ADDR(cdbp, lba);
12087 					FORMG1COUNT(cdbp, blockcount);
12088 					return (0);
12089 				} else if (cp->sc_grpcode == CDB_GROUP4) {
12090 					FORMG4LONGADDR(cdbp, lba);
12091 					FORMG4COUNT(cdbp, blockcount);
12092 					return (0);
12093 				} else if (cp->sc_grpcode == CDB_GROUP0) {
12094 					FORMG0ADDR(cdbp, lba);
12095 					FORMG0COUNT(cdbp, blockcount);
12096 					return (0);
12097 				} else if (cp->sc_grpcode == CDB_GROUP5) {
12098 					FORMG5ADDR(cdbp, lba);
12099 					FORMG5COUNT(cdbp, blockcount);
12100 					return (0);
12101 				}
12102 
12103 				/*
12104 				 * It should be impossible to not match one
12105 				 * of the CDB types above, so we should never
12106 				 * reach this point.  Set the CDB command byte
12107 				 * to test-unit-ready to avoid writing
12108 				 * to somewhere we don't intend.
12109 				 */
12110 				cdbp->scc_cmd = SCMD_TEST_UNIT_READY;
12111 				return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12112 			} else {
12113 				/*
12114 				 * Couldn't get scsi_pkt
12115 				 */
12116 				return (SD_PKT_ALLOC_FAILURE);
12117 			}
12118 		}
12119 	}
12120 
12121 	/*
12122 	 * None of the available CDB types were suitable.  This really
12123 	 * should never happen:  on a 64 bit system we support
12124 	 * READ16/WRITE16 which will hold an entire 64 bit disk address
12125 	 * and on a 32 bit system we will refuse to bind to a device
12126 	 * larger than 2TB so addresses will never be larger than 32 bits.
12127 	 */
12128 	return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12129 }
12130 
12131 /*
12132  *    Function: sd_setup_next_rw_pkt
12133  *
12134  * Description: Setup packet for partial DMA transfers, except for the
12135  * 		initial transfer.  sd_setup_rw_pkt should be used for
12136  *		the initial transfer.
12137  *
12138  *     Context: Kernel thread and may be called from interrupt context.
12139  */
12140 
12141 int
12142 sd_setup_next_rw_pkt(struct sd_lun *un,
12143     struct scsi_pkt *pktp, struct buf *bp,
12144     diskaddr_t lba, uint32_t blockcount)
12145 {
12146 	uchar_t com;
12147 	union scsi_cdb *cdbp;
12148 	uchar_t cdb_group_id;
12149 
12150 	ASSERT(pktp != NULL);
12151 	ASSERT(pktp->pkt_cdbp != NULL);
12152 
12153 	cdbp = (union scsi_cdb *)pktp->pkt_cdbp;
12154 	com = cdbp->scc_cmd;
12155 	cdb_group_id = CDB_GROUPID(com);
12156 
12157 	ASSERT((cdb_group_id == CDB_GROUPID_0) ||
12158 	    (cdb_group_id == CDB_GROUPID_1) ||
12159 	    (cdb_group_id == CDB_GROUPID_4) ||
12160 	    (cdb_group_id == CDB_GROUPID_5));
12161 
12162 	/*
12163 	 * Move pkt to the next portion of the xfer.
12164 	 * func is NULL_FUNC so we do not have to release
12165 	 * the disk mutex here.
12166 	 */
12167 	if (scsi_init_pkt(SD_ADDRESS(un), pktp, bp, 0, 0, 0, 0,
12168 	    NULL_FUNC, NULL) == pktp) {
12169 		/* Success.  Handle partial DMA */
12170 		if (pktp->pkt_resid != 0) {
12171 			blockcount -=
12172 			    SD_BYTES2TGTBLOCKS(un, pktp->pkt_resid);
12173 		}
12174 
12175 		cdbp->scc_cmd = com;
12176 		SD_FILL_SCSI1_LUN(un, pktp);
12177 		if (cdb_group_id == CDB_GROUPID_1) {
12178 			FORMG1ADDR(cdbp, lba);
12179 			FORMG1COUNT(cdbp, blockcount);
12180 			return (0);
12181 		} else if (cdb_group_id == CDB_GROUPID_4) {
12182 			FORMG4LONGADDR(cdbp, lba);
12183 			FORMG4COUNT(cdbp, blockcount);
12184 			return (0);
12185 		} else if (cdb_group_id == CDB_GROUPID_0) {
12186 			FORMG0ADDR(cdbp, lba);
12187 			FORMG0COUNT(cdbp, blockcount);
12188 			return (0);
12189 		} else if (cdb_group_id == CDB_GROUPID_5) {
12190 			FORMG5ADDR(cdbp, lba);
12191 			FORMG5COUNT(cdbp, blockcount);
12192 			return (0);
12193 		}
12194 
12195 		/* Unreachable */
12196 		return (SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL);
12197 	}
12198 
12199 	/*
12200 	 * Error setting up next portion of cmd transfer.
12201 	 * Something is definitely very wrong and this
12202 	 * should not happen.
12203 	 */
12204 	return (SD_PKT_ALLOC_FAILURE);
12205 }
12206 
12207 /*
12208  *    Function: sd_initpkt_for_uscsi
12209  *
12210  * Description: Allocate and initialize for transport a scsi_pkt struct,
12211  *		based upon the info specified in the given uscsi_cmd struct.
12212  *
12213  * Return Code: SD_PKT_ALLOC_SUCCESS
12214  *		SD_PKT_ALLOC_FAILURE
12215  *		SD_PKT_ALLOC_FAILURE_NO_DMA
12216  *		SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL
12217  *
12218  *     Context: Kernel thread and may be called from software interrupt context
12219  *		as part of a sdrunout callback. This function may not block or
12220  *		call routines that block
12221  */
12222 
12223 static int
12224 sd_initpkt_for_uscsi(struct buf *bp, struct scsi_pkt **pktpp)
12225 {
12226 	struct uscsi_cmd *uscmd;
12227 	struct sd_xbuf	*xp;
12228 	struct scsi_pkt	*pktp;
12229 	struct sd_lun	*un;
12230 	uint32_t	flags = 0;
12231 
12232 	ASSERT(bp != NULL);
12233 	ASSERT(pktpp != NULL);
12234 	xp = SD_GET_XBUF(bp);
12235 	ASSERT(xp != NULL);
12236 	un = SD_GET_UN(bp);
12237 	ASSERT(un != NULL);
12238 	ASSERT(mutex_owned(SD_MUTEX(un)));
12239 
12240 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12241 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12242 	ASSERT(uscmd != NULL);
12243 
12244 	SD_TRACE(SD_LOG_IO_CORE, un,
12245 	    "sd_initpkt_for_uscsi: entry: buf:0x%p\n", bp);
12246 
12247 	/*
12248 	 * Allocate the scsi_pkt for the command.
12249 	 * Note: If PKT_DMA_PARTIAL flag is set, scsi_vhci binds a path
12250 	 *	 during scsi_init_pkt time and will continue to use the
12251 	 *	 same path as long as the same scsi_pkt is used without
12252 	 *	 intervening scsi_dma_free(). Since uscsi command does
12253 	 *	 not call scsi_dmafree() before retry failed command, it
12254 	 *	 is necessary to make sure PKT_DMA_PARTIAL flag is NOT
12255 	 *	 set such that scsi_vhci can use other available path for
12256 	 *	 retry. Besides, ucsci command does not allow DMA breakup,
12257 	 *	 so there is no need to set PKT_DMA_PARTIAL flag.
12258 	 */
12259 	if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
12260 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
12261 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
12262 		    ((int)(uscmd->uscsi_rqlen) + sizeof (struct scsi_arq_status)
12263 		    - sizeof (struct scsi_extended_sense)), 0,
12264 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL) | PKT_XARQ,
12265 		    sdrunout, (caddr_t)un);
12266 	} else {
12267 		pktp = scsi_init_pkt(SD_ADDRESS(un), NULL,
12268 		    ((bp->b_bcount != 0) ? bp : NULL), uscmd->uscsi_cdblen,
12269 		    sizeof (struct scsi_arq_status), 0,
12270 		    (un->un_pkt_flags & ~PKT_DMA_PARTIAL),
12271 		    sdrunout, (caddr_t)un);
12272 	}
12273 
12274 	if (pktp == NULL) {
12275 		*pktpp = NULL;
12276 		/*
12277 		 * Set the driver state to RWAIT to indicate the driver
12278 		 * is waiting on resource allocations. The driver will not
12279 		 * suspend, pm_suspend, or detatch while the state is RWAIT.
12280 		 */
12281 		New_state(un, SD_STATE_RWAIT);
12282 
12283 		SD_ERROR(SD_LOG_IO_CORE, un,
12284 		    "sd_initpkt_for_uscsi: No pktp. exit bp:0x%p\n", bp);
12285 
12286 		if ((bp->b_flags & B_ERROR) != 0) {
12287 			return (SD_PKT_ALLOC_FAILURE_NO_DMA);
12288 		}
12289 		return (SD_PKT_ALLOC_FAILURE);
12290 	}
12291 
12292 	/*
12293 	 * We do not do DMA breakup for USCSI commands, so return failure
12294 	 * here if all the needed DMA resources were not allocated.
12295 	 */
12296 	if ((un->un_pkt_flags & PKT_DMA_PARTIAL) &&
12297 	    (bp->b_bcount != 0) && (pktp->pkt_resid != 0)) {
12298 		scsi_destroy_pkt(pktp);
12299 		SD_ERROR(SD_LOG_IO_CORE, un, "sd_initpkt_for_uscsi: "
12300 		    "No partial DMA for USCSI. exit: buf:0x%p\n", bp);
12301 		return (SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL);
12302 	}
12303 
12304 	/* Init the cdb from the given uscsi struct */
12305 	(void) scsi_setup_cdb((union scsi_cdb *)pktp->pkt_cdbp,
12306 	    uscmd->uscsi_cdb[0], 0, 0, 0);
12307 
12308 	SD_FILL_SCSI1_LUN(un, pktp);
12309 
12310 	/*
12311 	 * Set up the optional USCSI flags. See the uscsi (7I) man page
12312 	 * for listing of the supported flags.
12313 	 */
12314 
12315 	if (uscmd->uscsi_flags & USCSI_SILENT) {
12316 		flags |= FLAG_SILENT;
12317 	}
12318 
12319 	if (uscmd->uscsi_flags & USCSI_DIAGNOSE) {
12320 		flags |= FLAG_DIAGNOSE;
12321 	}
12322 
12323 	if (uscmd->uscsi_flags & USCSI_ISOLATE) {
12324 		flags |= FLAG_ISOLATE;
12325 	}
12326 
12327 	if (un->un_f_is_fibre == FALSE) {
12328 		if (uscmd->uscsi_flags & USCSI_RENEGOT) {
12329 			flags |= FLAG_RENEGOTIATE_WIDE_SYNC;
12330 		}
12331 	}
12332 
12333 	/*
12334 	 * Set the pkt flags here so we save time later.
12335 	 * Note: These flags are NOT in the uscsi man page!!!
12336 	 */
12337 	if (uscmd->uscsi_flags & USCSI_HEAD) {
12338 		flags |= FLAG_HEAD;
12339 	}
12340 
12341 	if (uscmd->uscsi_flags & USCSI_NOINTR) {
12342 		flags |= FLAG_NOINTR;
12343 	}
12344 
12345 	/*
12346 	 * For tagged queueing, things get a bit complicated.
12347 	 * Check first for head of queue and last for ordered queue.
12348 	 * If neither head nor order, use the default driver tag flags.
12349 	 */
12350 	if ((uscmd->uscsi_flags & USCSI_NOTAG) == 0) {
12351 		if (uscmd->uscsi_flags & USCSI_HTAG) {
12352 			flags |= FLAG_HTAG;
12353 		} else if (uscmd->uscsi_flags & USCSI_OTAG) {
12354 			flags |= FLAG_OTAG;
12355 		} else {
12356 			flags |= un->un_tagflags & FLAG_TAGMASK;
12357 		}
12358 	}
12359 
12360 	if (uscmd->uscsi_flags & USCSI_NODISCON) {
12361 		flags = (flags & ~FLAG_TAGMASK) | FLAG_NODISCON;
12362 	}
12363 
12364 	pktp->pkt_flags = flags;
12365 
12366 	/* Transfer uscsi information to scsi_pkt */
12367 	(void) scsi_uscsi_pktinit(uscmd, pktp);
12368 
12369 	/* Copy the caller's CDB into the pkt... */
12370 	bcopy(uscmd->uscsi_cdb, pktp->pkt_cdbp, uscmd->uscsi_cdblen);
12371 
12372 	if (uscmd->uscsi_timeout == 0) {
12373 		pktp->pkt_time = un->un_uscsi_timeout;
12374 	} else {
12375 		pktp->pkt_time = uscmd->uscsi_timeout;
12376 	}
12377 
12378 	/* need it later to identify USCSI request in sdintr */
12379 	xp->xb_pkt_flags |= SD_XB_USCSICMD;
12380 
12381 	xp->xb_sense_resid = uscmd->uscsi_rqresid;
12382 
12383 	pktp->pkt_private = bp;
12384 	pktp->pkt_comp = sdintr;
12385 	*pktpp = pktp;
12386 
12387 	SD_TRACE(SD_LOG_IO_CORE, un,
12388 	    "sd_initpkt_for_uscsi: exit: buf:0x%p\n", bp);
12389 
12390 	return (SD_PKT_ALLOC_SUCCESS);
12391 }
12392 
12393 
12394 /*
12395  *    Function: sd_destroypkt_for_uscsi
12396  *
12397  * Description: Free the scsi_pkt(9S) struct for the given bp, for uscsi
12398  *		IOs.. Also saves relevant info into the associated uscsi_cmd
12399  *		struct.
12400  *
12401  *     Context: May be called under interrupt context
12402  */
12403 
12404 static void
12405 sd_destroypkt_for_uscsi(struct buf *bp)
12406 {
12407 	struct uscsi_cmd *uscmd;
12408 	struct sd_xbuf	*xp;
12409 	struct scsi_pkt	*pktp;
12410 	struct sd_lun	*un;
12411 
12412 	ASSERT(bp != NULL);
12413 	xp = SD_GET_XBUF(bp);
12414 	ASSERT(xp != NULL);
12415 	un = SD_GET_UN(bp);
12416 	ASSERT(un != NULL);
12417 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12418 	pktp = SD_GET_PKTP(bp);
12419 	ASSERT(pktp != NULL);
12420 
12421 	SD_TRACE(SD_LOG_IO_CORE, un,
12422 	    "sd_destroypkt_for_uscsi: entry: buf:0x%p\n", bp);
12423 
12424 	/* The pointer to the uscsi_cmd struct is expected in xb_pktinfo */
12425 	uscmd = (struct uscsi_cmd *)xp->xb_pktinfo;
12426 	ASSERT(uscmd != NULL);
12427 
12428 	/* Save the status and the residual into the uscsi_cmd struct */
12429 	uscmd->uscsi_status = ((*(pktp)->pkt_scbp) & STATUS_MASK);
12430 	uscmd->uscsi_resid  = bp->b_resid;
12431 
12432 	/* Transfer scsi_pkt information to uscsi */
12433 	(void) scsi_uscsi_pktfini(pktp, uscmd);
12434 
12435 	/*
12436 	 * If enabled, copy any saved sense data into the area specified
12437 	 * by the uscsi command.
12438 	 */
12439 	if (((uscmd->uscsi_flags & USCSI_RQENABLE) != 0) &&
12440 	    (uscmd->uscsi_rqlen != 0) && (uscmd->uscsi_rqbuf != NULL)) {
12441 		/*
12442 		 * Note: uscmd->uscsi_rqbuf should always point to a buffer
12443 		 * at least SENSE_LENGTH bytes in size (see sd_send_scsi_cmd())
12444 		 */
12445 		uscmd->uscsi_rqstatus = xp->xb_sense_status;
12446 		uscmd->uscsi_rqresid  = xp->xb_sense_resid;
12447 		if (uscmd->uscsi_rqlen > SENSE_LENGTH) {
12448 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
12449 			    MAX_SENSE_LENGTH);
12450 		} else {
12451 			bcopy(xp->xb_sense_data, uscmd->uscsi_rqbuf,
12452 			    SENSE_LENGTH);
12453 		}
12454 	}
12455 
12456 	/* We are done with the scsi_pkt; free it now */
12457 	ASSERT(SD_GET_PKTP(bp) != NULL);
12458 	scsi_destroy_pkt(SD_GET_PKTP(bp));
12459 
12460 	SD_TRACE(SD_LOG_IO_CORE, un,
12461 	    "sd_destroypkt_for_uscsi: exit: buf:0x%p\n", bp);
12462 }
12463 
12464 
12465 /*
12466  *    Function: sd_bioclone_alloc
12467  *
12468  * Description: Allocate a buf(9S) and init it as per the given buf
12469  *		and the various arguments.  The associated sd_xbuf
12470  *		struct is (nearly) duplicated.  The struct buf *bp
12471  *		argument is saved in new_xp->xb_private.
12472  *
12473  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12474  *		datalen - size of data area for the shadow bp
12475  *		blkno - starting LBA
12476  *		func - function pointer for b_iodone in the shadow buf. (May
12477  *			be NULL if none.)
12478  *
12479  * Return Code: Pointer to allocates buf(9S) struct
12480  *
12481  *     Context: Can sleep.
12482  */
12483 
12484 static struct buf *
12485 sd_bioclone_alloc(struct buf *bp, size_t datalen,
12486 	daddr_t blkno, int (*func)(struct buf *))
12487 {
12488 	struct	sd_lun	*un;
12489 	struct	sd_xbuf	*xp;
12490 	struct	sd_xbuf	*new_xp;
12491 	struct	buf	*new_bp;
12492 
12493 	ASSERT(bp != NULL);
12494 	xp = SD_GET_XBUF(bp);
12495 	ASSERT(xp != NULL);
12496 	un = SD_GET_UN(bp);
12497 	ASSERT(un != NULL);
12498 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12499 
12500 	new_bp = bioclone(bp, 0, datalen, SD_GET_DEV(un), blkno, func,
12501 	    NULL, KM_SLEEP);
12502 
12503 	new_bp->b_lblkno	= blkno;
12504 
12505 	/*
12506 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12507 	 * original xbuf into it.
12508 	 */
12509 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12510 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12511 
12512 	/*
12513 	 * The given bp is automatically saved in the xb_private member
12514 	 * of the new xbuf.  Callers are allowed to depend on this.
12515 	 */
12516 	new_xp->xb_private = bp;
12517 
12518 	new_bp->b_private  = new_xp;
12519 
12520 	return (new_bp);
12521 }
12522 
12523 /*
12524  *    Function: sd_shadow_buf_alloc
12525  *
12526  * Description: Allocate a buf(9S) and init it as per the given buf
12527  *		and the various arguments.  The associated sd_xbuf
12528  *		struct is (nearly) duplicated.  The struct buf *bp
12529  *		argument is saved in new_xp->xb_private.
12530  *
12531  *   Arguments: bp - ptr the the buf(9S) to be "shadowed"
12532  *		datalen - size of data area for the shadow bp
12533  *		bflags - B_READ or B_WRITE (pseudo flag)
12534  *		blkno - starting LBA
12535  *		func - function pointer for b_iodone in the shadow buf. (May
12536  *			be NULL if none.)
12537  *
12538  * Return Code: Pointer to allocates buf(9S) struct
12539  *
12540  *     Context: Can sleep.
12541  */
12542 
12543 static struct buf *
12544 sd_shadow_buf_alloc(struct buf *bp, size_t datalen, uint_t bflags,
12545 	daddr_t blkno, int (*func)(struct buf *))
12546 {
12547 	struct	sd_lun	*un;
12548 	struct	sd_xbuf	*xp;
12549 	struct	sd_xbuf	*new_xp;
12550 	struct	buf	*new_bp;
12551 
12552 	ASSERT(bp != NULL);
12553 	xp = SD_GET_XBUF(bp);
12554 	ASSERT(xp != NULL);
12555 	un = SD_GET_UN(bp);
12556 	ASSERT(un != NULL);
12557 	ASSERT(!mutex_owned(SD_MUTEX(un)));
12558 
12559 	if (bp->b_flags & (B_PAGEIO | B_PHYS)) {
12560 		bp_mapin(bp);
12561 	}
12562 
12563 	bflags &= (B_READ | B_WRITE);
12564 #if defined(__i386) || defined(__amd64)
12565 	new_bp = getrbuf(KM_SLEEP);
12566 	new_bp->b_un.b_addr = kmem_zalloc(datalen, KM_SLEEP);
12567 	new_bp->b_bcount = datalen;
12568 	new_bp->b_flags = bflags |
12569 	    (bp->b_flags & ~(B_PAGEIO | B_PHYS | B_REMAPPED | B_SHADOW));
12570 #else
12571 	new_bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), NULL,
12572 	    datalen, bflags, SLEEP_FUNC, NULL);
12573 #endif
12574 	new_bp->av_forw	= NULL;
12575 	new_bp->av_back	= NULL;
12576 	new_bp->b_dev	= bp->b_dev;
12577 	new_bp->b_blkno	= blkno;
12578 	new_bp->b_iodone = func;
12579 	new_bp->b_edev	= bp->b_edev;
12580 	new_bp->b_resid	= 0;
12581 
12582 	/* We need to preserve the B_FAILFAST flag */
12583 	if (bp->b_flags & B_FAILFAST) {
12584 		new_bp->b_flags |= B_FAILFAST;
12585 	}
12586 
12587 	/*
12588 	 * Allocate an xbuf for the shadow bp and copy the contents of the
12589 	 * original xbuf into it.
12590 	 */
12591 	new_xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
12592 	bcopy(xp, new_xp, sizeof (struct sd_xbuf));
12593 
12594 	/* Need later to copy data between the shadow buf & original buf! */
12595 	new_xp->xb_pkt_flags |= PKT_CONSISTENT;
12596 
12597 	/*
12598 	 * The given bp is automatically saved in the xb_private member
12599 	 * of the new xbuf.  Callers are allowed to depend on this.
12600 	 */
12601 	new_xp->xb_private = bp;
12602 
12603 	new_bp->b_private  = new_xp;
12604 
12605 	return (new_bp);
12606 }
12607 
12608 /*
12609  *    Function: sd_bioclone_free
12610  *
12611  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations
12612  *		in the larger than partition operation.
12613  *
12614  *     Context: May be called under interrupt context
12615  */
12616 
12617 static void
12618 sd_bioclone_free(struct buf *bp)
12619 {
12620 	struct sd_xbuf	*xp;
12621 
12622 	ASSERT(bp != NULL);
12623 	xp = SD_GET_XBUF(bp);
12624 	ASSERT(xp != NULL);
12625 
12626 	/*
12627 	 * Call bp_mapout() before freeing the buf,  in case a lower
12628 	 * layer or HBA  had done a bp_mapin().  we must do this here
12629 	 * as we are the "originator" of the shadow buf.
12630 	 */
12631 	bp_mapout(bp);
12632 
12633 	/*
12634 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12635 	 * never gets confused by a stale value in this field. (Just a little
12636 	 * extra defensiveness here.)
12637 	 */
12638 	bp->b_iodone = NULL;
12639 
12640 	freerbuf(bp);
12641 
12642 	kmem_free(xp, sizeof (struct sd_xbuf));
12643 }
12644 
12645 /*
12646  *    Function: sd_shadow_buf_free
12647  *
12648  * Description: Deallocate a buf(9S) that was used for 'shadow' IO operations.
12649  *
12650  *     Context: May be called under interrupt context
12651  */
12652 
12653 static void
12654 sd_shadow_buf_free(struct buf *bp)
12655 {
12656 	struct sd_xbuf	*xp;
12657 
12658 	ASSERT(bp != NULL);
12659 	xp = SD_GET_XBUF(bp);
12660 	ASSERT(xp != NULL);
12661 
12662 #if defined(__sparc)
12663 	/*
12664 	 * Call bp_mapout() before freeing the buf,  in case a lower
12665 	 * layer or HBA  had done a bp_mapin().  we must do this here
12666 	 * as we are the "originator" of the shadow buf.
12667 	 */
12668 	bp_mapout(bp);
12669 #endif
12670 
12671 	/*
12672 	 * Null out b_iodone before freeing the bp, to ensure that the driver
12673 	 * never gets confused by a stale value in this field. (Just a little
12674 	 * extra defensiveness here.)
12675 	 */
12676 	bp->b_iodone = NULL;
12677 
12678 #if defined(__i386) || defined(__amd64)
12679 	kmem_free(bp->b_un.b_addr, bp->b_bcount);
12680 	freerbuf(bp);
12681 #else
12682 	scsi_free_consistent_buf(bp);
12683 #endif
12684 
12685 	kmem_free(xp, sizeof (struct sd_xbuf));
12686 }
12687 
12688 
12689 /*
12690  *    Function: sd_print_transport_rejected_message
12691  *
12692  * Description: This implements the ludicrously complex rules for printing
12693  *		a "transport rejected" message.  This is to address the
12694  *		specific problem of having a flood of this error message
12695  *		produced when a failover occurs.
12696  *
12697  *     Context: Any.
12698  */
12699 
12700 static void
12701 sd_print_transport_rejected_message(struct sd_lun *un, struct sd_xbuf *xp,
12702 	int code)
12703 {
12704 	ASSERT(un != NULL);
12705 	ASSERT(mutex_owned(SD_MUTEX(un)));
12706 	ASSERT(xp != NULL);
12707 
12708 	/*
12709 	 * Print the "transport rejected" message under the following
12710 	 * conditions:
12711 	 *
12712 	 * - Whenever the SD_LOGMASK_DIAG bit of sd_level_mask is set
12713 	 * - The error code from scsi_transport() is NOT a TRAN_FATAL_ERROR.
12714 	 * - If the error code IS a TRAN_FATAL_ERROR, then the message is
12715 	 *   printed the FIRST time a TRAN_FATAL_ERROR is returned from
12716 	 *   scsi_transport(9F) (which indicates that the target might have
12717 	 *   gone off-line).  This uses the un->un_tran_fatal_count
12718 	 *   count, which is incremented whenever a TRAN_FATAL_ERROR is
12719 	 *   received, and reset to zero whenver a TRAN_ACCEPT is returned
12720 	 *   from scsi_transport().
12721 	 *
12722 	 * The FLAG_SILENT in the scsi_pkt must be CLEARED in ALL of
12723 	 * the preceeding cases in order for the message to be printed.
12724 	 */
12725 	if ((xp->xb_pktp->pkt_flags & FLAG_SILENT) == 0) {
12726 		if ((sd_level_mask & SD_LOGMASK_DIAG) ||
12727 		    (code != TRAN_FATAL_ERROR) ||
12728 		    (un->un_tran_fatal_count == 1)) {
12729 			switch (code) {
12730 			case TRAN_BADPKT:
12731 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12732 				    "transport rejected bad packet\n");
12733 				break;
12734 			case TRAN_FATAL_ERROR:
12735 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12736 				    "transport rejected fatal error\n");
12737 				break;
12738 			default:
12739 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
12740 				    "transport rejected (%d)\n", code);
12741 				break;
12742 			}
12743 		}
12744 	}
12745 }
12746 
12747 
12748 /*
12749  *    Function: sd_add_buf_to_waitq
12750  *
12751  * Description: Add the given buf(9S) struct to the wait queue for the
12752  *		instance.  If sorting is enabled, then the buf is added
12753  *		to the queue via an elevator sort algorithm (a la
12754  *		disksort(9F)).  The SD_GET_BLKNO(bp) is used as the sort key.
12755  *		If sorting is not enabled, then the buf is just added
12756  *		to the end of the wait queue.
12757  *
12758  * Return Code: void
12759  *
12760  *     Context: Does not sleep/block, therefore technically can be called
12761  *		from any context.  However if sorting is enabled then the
12762  *		execution time is indeterminate, and may take long if
12763  *		the wait queue grows large.
12764  */
12765 
12766 static void
12767 sd_add_buf_to_waitq(struct sd_lun *un, struct buf *bp)
12768 {
12769 	struct buf *ap;
12770 
12771 	ASSERT(bp != NULL);
12772 	ASSERT(un != NULL);
12773 	ASSERT(mutex_owned(SD_MUTEX(un)));
12774 
12775 	/* If the queue is empty, add the buf as the only entry & return. */
12776 	if (un->un_waitq_headp == NULL) {
12777 		ASSERT(un->un_waitq_tailp == NULL);
12778 		un->un_waitq_headp = un->un_waitq_tailp = bp;
12779 		bp->av_forw = NULL;
12780 		return;
12781 	}
12782 
12783 	ASSERT(un->un_waitq_tailp != NULL);
12784 
12785 	/*
12786 	 * If sorting is disabled, just add the buf to the tail end of
12787 	 * the wait queue and return.
12788 	 */
12789 	if (un->un_f_disksort_disabled) {
12790 		un->un_waitq_tailp->av_forw = bp;
12791 		un->un_waitq_tailp = bp;
12792 		bp->av_forw = NULL;
12793 		return;
12794 	}
12795 
12796 	/*
12797 	 * Sort thru the list of requests currently on the wait queue
12798 	 * and add the new buf request at the appropriate position.
12799 	 *
12800 	 * The un->un_waitq_headp is an activity chain pointer on which
12801 	 * we keep two queues, sorted in ascending SD_GET_BLKNO() order. The
12802 	 * first queue holds those requests which are positioned after
12803 	 * the current SD_GET_BLKNO() (in the first request); the second holds
12804 	 * requests which came in after their SD_GET_BLKNO() number was passed.
12805 	 * Thus we implement a one way scan, retracting after reaching
12806 	 * the end of the drive to the first request on the second
12807 	 * queue, at which time it becomes the first queue.
12808 	 * A one-way scan is natural because of the way UNIX read-ahead
12809 	 * blocks are allocated.
12810 	 *
12811 	 * If we lie after the first request, then we must locate the
12812 	 * second request list and add ourselves to it.
12813 	 */
12814 	ap = un->un_waitq_headp;
12815 	if (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap)) {
12816 		while (ap->av_forw != NULL) {
12817 			/*
12818 			 * Look for an "inversion" in the (normally
12819 			 * ascending) block numbers. This indicates
12820 			 * the start of the second request list.
12821 			 */
12822 			if (SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) {
12823 				/*
12824 				 * Search the second request list for the
12825 				 * first request at a larger block number.
12826 				 * We go before that; however if there is
12827 				 * no such request, we go at the end.
12828 				 */
12829 				do {
12830 					if (SD_GET_BLKNO(bp) <
12831 					    SD_GET_BLKNO(ap->av_forw)) {
12832 						goto insert;
12833 					}
12834 					ap = ap->av_forw;
12835 				} while (ap->av_forw != NULL);
12836 				goto insert;		/* after last */
12837 			}
12838 			ap = ap->av_forw;
12839 		}
12840 
12841 		/*
12842 		 * No inversions... we will go after the last, and
12843 		 * be the first request in the second request list.
12844 		 */
12845 		goto insert;
12846 	}
12847 
12848 	/*
12849 	 * Request is at/after the current request...
12850 	 * sort in the first request list.
12851 	 */
12852 	while (ap->av_forw != NULL) {
12853 		/*
12854 		 * We want to go after the current request (1) if
12855 		 * there is an inversion after it (i.e. it is the end
12856 		 * of the first request list), or (2) if the next
12857 		 * request is a larger block no. than our request.
12858 		 */
12859 		if ((SD_GET_BLKNO(ap->av_forw) < SD_GET_BLKNO(ap)) ||
12860 		    (SD_GET_BLKNO(bp) < SD_GET_BLKNO(ap->av_forw))) {
12861 			goto insert;
12862 		}
12863 		ap = ap->av_forw;
12864 	}
12865 
12866 	/*
12867 	 * Neither a second list nor a larger request, therefore
12868 	 * we go at the end of the first list (which is the same
12869 	 * as the end of the whole schebang).
12870 	 */
12871 insert:
12872 	bp->av_forw = ap->av_forw;
12873 	ap->av_forw = bp;
12874 
12875 	/*
12876 	 * If we inserted onto the tail end of the waitq, make sure the
12877 	 * tail pointer is updated.
12878 	 */
12879 	if (ap == un->un_waitq_tailp) {
12880 		un->un_waitq_tailp = bp;
12881 	}
12882 }
12883 
12884 
12885 /*
12886  *    Function: sd_start_cmds
12887  *
12888  * Description: Remove and transport cmds from the driver queues.
12889  *
12890  *   Arguments: un - pointer to the unit (soft state) struct for the target.
12891  *
12892  *		immed_bp - ptr to a buf to be transported immediately. Only
12893  *		the immed_bp is transported; bufs on the waitq are not
12894  *		processed and the un_retry_bp is not checked.  If immed_bp is
12895  *		NULL, then normal queue processing is performed.
12896  *
12897  *     Context: May be called from kernel thread context, interrupt context,
12898  *		or runout callback context. This function may not block or
12899  *		call routines that block.
12900  */
12901 
12902 static void
12903 sd_start_cmds(struct sd_lun *un, struct buf *immed_bp)
12904 {
12905 	struct	sd_xbuf	*xp;
12906 	struct	buf	*bp;
12907 	void	(*statp)(kstat_io_t *);
12908 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12909 	void	(*saved_statp)(kstat_io_t *);
12910 #endif
12911 	int	rval;
12912 
12913 	ASSERT(un != NULL);
12914 	ASSERT(mutex_owned(SD_MUTEX(un)));
12915 	ASSERT(un->un_ncmds_in_transport >= 0);
12916 	ASSERT(un->un_throttle >= 0);
12917 
12918 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: entry\n");
12919 
12920 	do {
12921 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12922 		saved_statp = NULL;
12923 #endif
12924 
12925 		/*
12926 		 * If we are syncing or dumping, fail the command to
12927 		 * avoid recursively calling back into scsi_transport().
12928 		 * The dump I/O itself uses a separate code path so this
12929 		 * only prevents non-dump I/O from being sent while dumping.
12930 		 * File system sync takes place before dumping begins.
12931 		 * During panic, filesystem I/O is allowed provided
12932 		 * un_in_callback is <= 1.  This is to prevent recursion
12933 		 * such as sd_start_cmds -> scsi_transport -> sdintr ->
12934 		 * sd_start_cmds and so on.  See panic.c for more information
12935 		 * about the states the system can be in during panic.
12936 		 */
12937 		if ((un->un_state == SD_STATE_DUMPING) ||
12938 		    (ddi_in_panic() && (un->un_in_callback > 1))) {
12939 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
12940 			    "sd_start_cmds: panicking\n");
12941 			goto exit;
12942 		}
12943 
12944 		if ((bp = immed_bp) != NULL) {
12945 			/*
12946 			 * We have a bp that must be transported immediately.
12947 			 * It's OK to transport the immed_bp here without doing
12948 			 * the throttle limit check because the immed_bp is
12949 			 * always used in a retry/recovery case. This means
12950 			 * that we know we are not at the throttle limit by
12951 			 * virtue of the fact that to get here we must have
12952 			 * already gotten a command back via sdintr(). This also
12953 			 * relies on (1) the command on un_retry_bp preventing
12954 			 * further commands from the waitq from being issued;
12955 			 * and (2) the code in sd_retry_command checking the
12956 			 * throttle limit before issuing a delayed or immediate
12957 			 * retry. This holds even if the throttle limit is
12958 			 * currently ratcheted down from its maximum value.
12959 			 */
12960 			statp = kstat_runq_enter;
12961 			if (bp == un->un_retry_bp) {
12962 				ASSERT((un->un_retry_statp == NULL) ||
12963 				    (un->un_retry_statp == kstat_waitq_enter) ||
12964 				    (un->un_retry_statp ==
12965 				    kstat_runq_back_to_waitq));
12966 				/*
12967 				 * If the waitq kstat was incremented when
12968 				 * sd_set_retry_bp() queued this bp for a retry,
12969 				 * then we must set up statp so that the waitq
12970 				 * count will get decremented correctly below.
12971 				 * Also we must clear un->un_retry_statp to
12972 				 * ensure that we do not act on a stale value
12973 				 * in this field.
12974 				 */
12975 				if ((un->un_retry_statp == kstat_waitq_enter) ||
12976 				    (un->un_retry_statp ==
12977 				    kstat_runq_back_to_waitq)) {
12978 					statp = kstat_waitq_to_runq;
12979 				}
12980 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
12981 				saved_statp = un->un_retry_statp;
12982 #endif
12983 				un->un_retry_statp = NULL;
12984 
12985 				SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
12986 				    "sd_start_cmds: un:0x%p: GOT retry_bp:0x%p "
12987 				    "un_throttle:%d un_ncmds_in_transport:%d\n",
12988 				    un, un->un_retry_bp, un->un_throttle,
12989 				    un->un_ncmds_in_transport);
12990 			} else {
12991 				SD_TRACE(SD_LOG_IO_CORE, un, "sd_start_cmds: "
12992 				    "processing priority bp:0x%p\n", bp);
12993 			}
12994 
12995 		} else if ((bp = un->un_waitq_headp) != NULL) {
12996 			/*
12997 			 * A command on the waitq is ready to go, but do not
12998 			 * send it if:
12999 			 *
13000 			 * (1) the throttle limit has been reached, or
13001 			 * (2) a retry is pending, or
13002 			 * (3) a START_STOP_UNIT callback pending, or
13003 			 * (4) a callback for a SD_PATH_DIRECT_PRIORITY
13004 			 *	command is pending.
13005 			 *
13006 			 * For all of these conditions, IO processing will
13007 			 * restart after the condition is cleared.
13008 			 */
13009 			if (un->un_ncmds_in_transport >= un->un_throttle) {
13010 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13011 				    "sd_start_cmds: exiting, "
13012 				    "throttle limit reached!\n");
13013 				goto exit;
13014 			}
13015 			if (un->un_retry_bp != NULL) {
13016 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13017 				    "sd_start_cmds: exiting, retry pending!\n");
13018 				goto exit;
13019 			}
13020 			if (un->un_startstop_timeid != NULL) {
13021 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13022 				    "sd_start_cmds: exiting, "
13023 				    "START_STOP pending!\n");
13024 				goto exit;
13025 			}
13026 			if (un->un_direct_priority_timeid != NULL) {
13027 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13028 				    "sd_start_cmds: exiting, "
13029 				    "SD_PATH_DIRECT_PRIORITY cmd. pending!\n");
13030 				goto exit;
13031 			}
13032 
13033 			/* Dequeue the command */
13034 			un->un_waitq_headp = bp->av_forw;
13035 			if (un->un_waitq_headp == NULL) {
13036 				un->un_waitq_tailp = NULL;
13037 			}
13038 			bp->av_forw = NULL;
13039 			statp = kstat_waitq_to_runq;
13040 			SD_TRACE(SD_LOG_IO_CORE, un,
13041 			    "sd_start_cmds: processing waitq bp:0x%p\n", bp);
13042 
13043 		} else {
13044 			/* No work to do so bail out now */
13045 			SD_TRACE(SD_LOG_IO_CORE, un,
13046 			    "sd_start_cmds: no more work, exiting!\n");
13047 			goto exit;
13048 		}
13049 
13050 		/*
13051 		 * Reset the state to normal. This is the mechanism by which
13052 		 * the state transitions from either SD_STATE_RWAIT or
13053 		 * SD_STATE_OFFLINE to SD_STATE_NORMAL.
13054 		 * If state is SD_STATE_PM_CHANGING then this command is
13055 		 * part of the device power control and the state must
13056 		 * not be put back to normal. Doing so would would
13057 		 * allow new commands to proceed when they shouldn't,
13058 		 * the device may be going off.
13059 		 */
13060 		if ((un->un_state != SD_STATE_SUSPENDED) &&
13061 		    (un->un_state != SD_STATE_PM_CHANGING)) {
13062 			New_state(un, SD_STATE_NORMAL);
13063 		}
13064 
13065 		xp = SD_GET_XBUF(bp);
13066 		ASSERT(xp != NULL);
13067 
13068 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13069 		/*
13070 		 * Allocate the scsi_pkt if we need one, or attach DMA
13071 		 * resources if we have a scsi_pkt that needs them. The
13072 		 * latter should only occur for commands that are being
13073 		 * retried.
13074 		 */
13075 		if ((xp->xb_pktp == NULL) ||
13076 		    ((xp->xb_pkt_flags & SD_XB_DMA_FREED) != 0)) {
13077 #else
13078 		if (xp->xb_pktp == NULL) {
13079 #endif
13080 			/*
13081 			 * There is no scsi_pkt allocated for this buf. Call
13082 			 * the initpkt function to allocate & init one.
13083 			 *
13084 			 * The scsi_init_pkt runout callback functionality is
13085 			 * implemented as follows:
13086 			 *
13087 			 * 1) The initpkt function always calls
13088 			 *    scsi_init_pkt(9F) with sdrunout specified as the
13089 			 *    callback routine.
13090 			 * 2) A successful packet allocation is initialized and
13091 			 *    the I/O is transported.
13092 			 * 3) The I/O associated with an allocation resource
13093 			 *    failure is left on its queue to be retried via
13094 			 *    runout or the next I/O.
13095 			 * 4) The I/O associated with a DMA error is removed
13096 			 *    from the queue and failed with EIO. Processing of
13097 			 *    the transport queues is also halted to be
13098 			 *    restarted via runout or the next I/O.
13099 			 * 5) The I/O associated with a CDB size or packet
13100 			 *    size error is removed from the queue and failed
13101 			 *    with EIO. Processing of the transport queues is
13102 			 *    continued.
13103 			 *
13104 			 * Note: there is no interface for canceling a runout
13105 			 * callback. To prevent the driver from detaching or
13106 			 * suspending while a runout is pending the driver
13107 			 * state is set to SD_STATE_RWAIT
13108 			 *
13109 			 * Note: using the scsi_init_pkt callback facility can
13110 			 * result in an I/O request persisting at the head of
13111 			 * the list which cannot be satisfied even after
13112 			 * multiple retries. In the future the driver may
13113 			 * implement some kind of maximum runout count before
13114 			 * failing an I/O.
13115 			 *
13116 			 * Note: the use of funcp below may seem superfluous,
13117 			 * but it helps warlock figure out the correct
13118 			 * initpkt function calls (see [s]sd.wlcmd).
13119 			 */
13120 			struct scsi_pkt	*pktp;
13121 			int (*funcp)(struct buf *bp, struct scsi_pkt **pktp);
13122 
13123 			ASSERT(bp != un->un_rqs_bp);
13124 
13125 			funcp = sd_initpkt_map[xp->xb_chain_iostart];
13126 			switch ((*funcp)(bp, &pktp)) {
13127 			case  SD_PKT_ALLOC_SUCCESS:
13128 				xp->xb_pktp = pktp;
13129 				SD_TRACE(SD_LOG_IO_CORE, un,
13130 				    "sd_start_cmd: SD_PKT_ALLOC_SUCCESS 0x%p\n",
13131 				    pktp);
13132 				goto got_pkt;
13133 
13134 			case SD_PKT_ALLOC_FAILURE:
13135 				/*
13136 				 * Temporary (hopefully) resource depletion.
13137 				 * Since retries and RQS commands always have a
13138 				 * scsi_pkt allocated, these cases should never
13139 				 * get here. So the only cases this needs to
13140 				 * handle is a bp from the waitq (which we put
13141 				 * back onto the waitq for sdrunout), or a bp
13142 				 * sent as an immed_bp (which we just fail).
13143 				 */
13144 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13145 				    "sd_start_cmds: SD_PKT_ALLOC_FAILURE\n");
13146 
13147 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13148 
13149 				if (bp == immed_bp) {
13150 					/*
13151 					 * If SD_XB_DMA_FREED is clear, then
13152 					 * this is a failure to allocate a
13153 					 * scsi_pkt, and we must fail the
13154 					 * command.
13155 					 */
13156 					if ((xp->xb_pkt_flags &
13157 					    SD_XB_DMA_FREED) == 0) {
13158 						break;
13159 					}
13160 
13161 					/*
13162 					 * If this immediate command is NOT our
13163 					 * un_retry_bp, then we must fail it.
13164 					 */
13165 					if (bp != un->un_retry_bp) {
13166 						break;
13167 					}
13168 
13169 					/*
13170 					 * We get here if this cmd is our
13171 					 * un_retry_bp that was DMAFREED, but
13172 					 * scsi_init_pkt() failed to reallocate
13173 					 * DMA resources when we attempted to
13174 					 * retry it. This can happen when an
13175 					 * mpxio failover is in progress, but
13176 					 * we don't want to just fail the
13177 					 * command in this case.
13178 					 *
13179 					 * Use timeout(9F) to restart it after
13180 					 * a 100ms delay.  We don't want to
13181 					 * let sdrunout() restart it, because
13182 					 * sdrunout() is just supposed to start
13183 					 * commands that are sitting on the
13184 					 * wait queue.  The un_retry_bp stays
13185 					 * set until the command completes, but
13186 					 * sdrunout can be called many times
13187 					 * before that happens.  Since sdrunout
13188 					 * cannot tell if the un_retry_bp is
13189 					 * already in the transport, it could
13190 					 * end up calling scsi_transport() for
13191 					 * the un_retry_bp multiple times.
13192 					 *
13193 					 * Also: don't schedule the callback
13194 					 * if some other callback is already
13195 					 * pending.
13196 					 */
13197 					if (un->un_retry_statp == NULL) {
13198 						/*
13199 						 * restore the kstat pointer to
13200 						 * keep kstat counts coherent
13201 						 * when we do retry the command.
13202 						 */
13203 						un->un_retry_statp =
13204 						    saved_statp;
13205 					}
13206 
13207 					if ((un->un_startstop_timeid == NULL) &&
13208 					    (un->un_retry_timeid == NULL) &&
13209 					    (un->un_direct_priority_timeid ==
13210 					    NULL)) {
13211 
13212 						un->un_retry_timeid =
13213 						    timeout(
13214 						    sd_start_retry_command,
13215 						    un, SD_RESTART_TIMEOUT);
13216 					}
13217 					goto exit;
13218 				}
13219 
13220 #else
13221 				if (bp == immed_bp) {
13222 					break;	/* Just fail the command */
13223 				}
13224 #endif
13225 
13226 				/* Add the buf back to the head of the waitq */
13227 				bp->av_forw = un->un_waitq_headp;
13228 				un->un_waitq_headp = bp;
13229 				if (un->un_waitq_tailp == NULL) {
13230 					un->un_waitq_tailp = bp;
13231 				}
13232 				goto exit;
13233 
13234 			case SD_PKT_ALLOC_FAILURE_NO_DMA:
13235 				/*
13236 				 * HBA DMA resource failure. Fail the command
13237 				 * and continue processing of the queues.
13238 				 */
13239 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13240 				    "sd_start_cmds: "
13241 				    "SD_PKT_ALLOC_FAILURE_NO_DMA\n");
13242 				break;
13243 
13244 			case SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL:
13245 				/*
13246 				 * Note:x86: Partial DMA mapping not supported
13247 				 * for USCSI commands, and all the needed DMA
13248 				 * resources were not allocated.
13249 				 */
13250 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13251 				    "sd_start_cmds: "
13252 				    "SD_PKT_ALLOC_FAILURE_PKT_TOO_SMALL\n");
13253 				break;
13254 
13255 			case SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL:
13256 				/*
13257 				 * Note:x86: Request cannot fit into CDB based
13258 				 * on lba and len.
13259 				 */
13260 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13261 				    "sd_start_cmds: "
13262 				    "SD_PKT_ALLOC_FAILURE_CDB_TOO_SMALL\n");
13263 				break;
13264 
13265 			default:
13266 				/* Should NEVER get here! */
13267 				panic("scsi_initpkt error");
13268 				/*NOTREACHED*/
13269 			}
13270 
13271 			/*
13272 			 * Fatal error in allocating a scsi_pkt for this buf.
13273 			 * Update kstats & return the buf with an error code.
13274 			 * We must use sd_return_failed_command_no_restart() to
13275 			 * avoid a recursive call back into sd_start_cmds().
13276 			 * However this also means that we must keep processing
13277 			 * the waitq here in order to avoid stalling.
13278 			 */
13279 			if (statp == kstat_waitq_to_runq) {
13280 				SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
13281 			}
13282 			sd_return_failed_command_no_restart(un, bp, EIO);
13283 			if (bp == immed_bp) {
13284 				/* immed_bp is gone by now, so clear this */
13285 				immed_bp = NULL;
13286 			}
13287 			continue;
13288 		}
13289 got_pkt:
13290 		if (bp == immed_bp) {
13291 			/* goto the head of the class.... */
13292 			xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13293 		}
13294 
13295 		un->un_ncmds_in_transport++;
13296 		SD_UPDATE_KSTATS(un, statp, bp);
13297 
13298 		/*
13299 		 * Call scsi_transport() to send the command to the target.
13300 		 * According to SCSA architecture, we must drop the mutex here
13301 		 * before calling scsi_transport() in order to avoid deadlock.
13302 		 * Note that the scsi_pkt's completion routine can be executed
13303 		 * (from interrupt context) even before the call to
13304 		 * scsi_transport() returns.
13305 		 */
13306 		SD_TRACE(SD_LOG_IO_CORE, un,
13307 		    "sd_start_cmds: calling scsi_transport()\n");
13308 		DTRACE_PROBE1(scsi__transport__dispatch, struct buf *, bp);
13309 
13310 		mutex_exit(SD_MUTEX(un));
13311 		rval = scsi_transport(xp->xb_pktp);
13312 		mutex_enter(SD_MUTEX(un));
13313 
13314 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13315 		    "sd_start_cmds: scsi_transport() returned %d\n", rval);
13316 
13317 		switch (rval) {
13318 		case TRAN_ACCEPT:
13319 			/* Clear this with every pkt accepted by the HBA */
13320 			un->un_tran_fatal_count = 0;
13321 			break;	/* Success; try the next cmd (if any) */
13322 
13323 		case TRAN_BUSY:
13324 			un->un_ncmds_in_transport--;
13325 			ASSERT(un->un_ncmds_in_transport >= 0);
13326 
13327 			/*
13328 			 * Don't retry request sense, the sense data
13329 			 * is lost when another request is sent.
13330 			 * Free up the rqs buf and retry
13331 			 * the original failed cmd.  Update kstat.
13332 			 */
13333 			if (bp == un->un_rqs_bp) {
13334 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13335 				bp = sd_mark_rqs_idle(un, xp);
13336 				sd_retry_command(un, bp, SD_RETRIES_STANDARD,
13337 				    NULL, NULL, EIO, SD_BSY_TIMEOUT / 500,
13338 				    kstat_waitq_enter);
13339 				goto exit;
13340 			}
13341 
13342 #if defined(__i386) || defined(__amd64)	/* DMAFREE for x86 only */
13343 			/*
13344 			 * Free the DMA resources for the  scsi_pkt. This will
13345 			 * allow mpxio to select another path the next time
13346 			 * we call scsi_transport() with this scsi_pkt.
13347 			 * See sdintr() for the rationalization behind this.
13348 			 */
13349 			if ((un->un_f_is_fibre == TRUE) &&
13350 			    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
13351 			    ((xp->xb_pktp->pkt_flags & FLAG_SENSING) == 0)) {
13352 				scsi_dmafree(xp->xb_pktp);
13353 				xp->xb_pkt_flags |= SD_XB_DMA_FREED;
13354 			}
13355 #endif
13356 
13357 			if (SD_IS_DIRECT_PRIORITY(SD_GET_XBUF(bp))) {
13358 				/*
13359 				 * Commands that are SD_PATH_DIRECT_PRIORITY
13360 				 * are for error recovery situations. These do
13361 				 * not use the normal command waitq, so if they
13362 				 * get a TRAN_BUSY we cannot put them back onto
13363 				 * the waitq for later retry. One possible
13364 				 * problem is that there could already be some
13365 				 * other command on un_retry_bp that is waiting
13366 				 * for this one to complete, so we would be
13367 				 * deadlocked if we put this command back onto
13368 				 * the waitq for later retry (since un_retry_bp
13369 				 * must complete before the driver gets back to
13370 				 * commands on the waitq).
13371 				 *
13372 				 * To avoid deadlock we must schedule a callback
13373 				 * that will restart this command after a set
13374 				 * interval.  This should keep retrying for as
13375 				 * long as the underlying transport keeps
13376 				 * returning TRAN_BUSY (just like for other
13377 				 * commands).  Use the same timeout interval as
13378 				 * for the ordinary TRAN_BUSY retry.
13379 				 */
13380 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13381 				    "sd_start_cmds: scsi_transport() returned "
13382 				    "TRAN_BUSY for DIRECT_PRIORITY cmd!\n");
13383 
13384 				SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13385 				un->un_direct_priority_timeid =
13386 				    timeout(sd_start_direct_priority_command,
13387 				    bp, SD_BSY_TIMEOUT / 500);
13388 
13389 				goto exit;
13390 			}
13391 
13392 			/*
13393 			 * For TRAN_BUSY, we want to reduce the throttle value,
13394 			 * unless we are retrying a command.
13395 			 */
13396 			if (bp != un->un_retry_bp) {
13397 				sd_reduce_throttle(un, SD_THROTTLE_TRAN_BUSY);
13398 			}
13399 
13400 			/*
13401 			 * Set up the bp to be tried again 10 ms later.
13402 			 * Note:x86: Is there a timeout value in the sd_lun
13403 			 * for this condition?
13404 			 */
13405 			sd_set_retry_bp(un, bp, SD_BSY_TIMEOUT / 500,
13406 			    kstat_runq_back_to_waitq);
13407 			goto exit;
13408 
13409 		case TRAN_FATAL_ERROR:
13410 			un->un_tran_fatal_count++;
13411 			/* FALLTHRU */
13412 
13413 		case TRAN_BADPKT:
13414 		default:
13415 			un->un_ncmds_in_transport--;
13416 			ASSERT(un->un_ncmds_in_transport >= 0);
13417 
13418 			/*
13419 			 * If this is our REQUEST SENSE command with a
13420 			 * transport error, we must get back the pointers
13421 			 * to the original buf, and mark the REQUEST
13422 			 * SENSE command as "available".
13423 			 */
13424 			if (bp == un->un_rqs_bp) {
13425 				bp = sd_mark_rqs_idle(un, xp);
13426 				xp = SD_GET_XBUF(bp);
13427 			} else {
13428 				/*
13429 				 * Legacy behavior: do not update transport
13430 				 * error count for request sense commands.
13431 				 */
13432 				SD_UPDATE_ERRSTATS(un, sd_transerrs);
13433 			}
13434 
13435 			SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
13436 			sd_print_transport_rejected_message(un, xp, rval);
13437 
13438 			/*
13439 			 * We must use sd_return_failed_command_no_restart() to
13440 			 * avoid a recursive call back into sd_start_cmds().
13441 			 * However this also means that we must keep processing
13442 			 * the waitq here in order to avoid stalling.
13443 			 */
13444 			sd_return_failed_command_no_restart(un, bp, EIO);
13445 
13446 			/*
13447 			 * Notify any threads waiting in sd_ddi_suspend() that
13448 			 * a command completion has occurred.
13449 			 */
13450 			if (un->un_state == SD_STATE_SUSPENDED) {
13451 				cv_broadcast(&un->un_disk_busy_cv);
13452 			}
13453 
13454 			if (bp == immed_bp) {
13455 				/* immed_bp is gone by now, so clear this */
13456 				immed_bp = NULL;
13457 			}
13458 			break;
13459 		}
13460 
13461 	} while (immed_bp == NULL);
13462 
13463 exit:
13464 	ASSERT(mutex_owned(SD_MUTEX(un)));
13465 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_start_cmds: exit\n");
13466 }
13467 
13468 
13469 /*
13470  *    Function: sd_return_command
13471  *
13472  * Description: Returns a command to its originator (with or without an
13473  *		error).  Also starts commands waiting to be transported
13474  *		to the target.
13475  *
13476  *     Context: May be called from interrupt, kernel, or timeout context
13477  */
13478 
13479 static void
13480 sd_return_command(struct sd_lun *un, struct buf *bp)
13481 {
13482 	struct sd_xbuf *xp;
13483 	struct scsi_pkt *pktp;
13484 
13485 	ASSERT(bp != NULL);
13486 	ASSERT(un != NULL);
13487 	ASSERT(mutex_owned(SD_MUTEX(un)));
13488 	ASSERT(bp != un->un_rqs_bp);
13489 	xp = SD_GET_XBUF(bp);
13490 	ASSERT(xp != NULL);
13491 
13492 	pktp = SD_GET_PKTP(bp);
13493 
13494 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: entry\n");
13495 
13496 	/*
13497 	 * Note: check for the "sdrestart failed" case.
13498 	 */
13499 	if ((un->un_partial_dma_supported == 1) &&
13500 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) != SD_XB_USCSICMD) &&
13501 	    (geterror(bp) == 0) && (xp->xb_dma_resid != 0) &&
13502 	    (xp->xb_pktp->pkt_resid == 0)) {
13503 
13504 		if (sd_setup_next_xfer(un, bp, pktp, xp) != 0) {
13505 			/*
13506 			 * Successfully set up next portion of cmd
13507 			 * transfer, try sending it
13508 			 */
13509 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
13510 			    NULL, NULL, 0, (clock_t)0, NULL);
13511 			sd_start_cmds(un, NULL);
13512 			return;	/* Note:x86: need a return here? */
13513 		}
13514 	}
13515 
13516 	/*
13517 	 * If this is the failfast bp, clear it from un_failfast_bp. This
13518 	 * can happen if upon being re-tried the failfast bp either
13519 	 * succeeded or encountered another error (possibly even a different
13520 	 * error than the one that precipitated the failfast state, but in
13521 	 * that case it would have had to exhaust retries as well). Regardless,
13522 	 * this should not occur whenever the instance is in the active
13523 	 * failfast state.
13524 	 */
13525 	if (bp == un->un_failfast_bp) {
13526 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13527 		un->un_failfast_bp = NULL;
13528 	}
13529 
13530 	/*
13531 	 * Clear the failfast state upon successful completion of ANY cmd.
13532 	 */
13533 	if (bp->b_error == 0) {
13534 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13535 	}
13536 
13537 	/*
13538 	 * This is used if the command was retried one or more times. Show that
13539 	 * we are done with it, and allow processing of the waitq to resume.
13540 	 */
13541 	if (bp == un->un_retry_bp) {
13542 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13543 		    "sd_return_command: un:0x%p: "
13544 		    "RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13545 		un->un_retry_bp = NULL;
13546 		un->un_retry_statp = NULL;
13547 	}
13548 
13549 	SD_UPDATE_RDWR_STATS(un, bp);
13550 	SD_UPDATE_PARTITION_STATS(un, bp);
13551 
13552 	switch (un->un_state) {
13553 	case SD_STATE_SUSPENDED:
13554 		/*
13555 		 * Notify any threads waiting in sd_ddi_suspend() that
13556 		 * a command completion has occurred.
13557 		 */
13558 		cv_broadcast(&un->un_disk_busy_cv);
13559 		break;
13560 	default:
13561 		sd_start_cmds(un, NULL);
13562 		break;
13563 	}
13564 
13565 	/* Return this command up the iodone chain to its originator. */
13566 	mutex_exit(SD_MUTEX(un));
13567 
13568 	(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13569 	xp->xb_pktp = NULL;
13570 
13571 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13572 
13573 	ASSERT(!mutex_owned(SD_MUTEX(un)));
13574 	mutex_enter(SD_MUTEX(un));
13575 
13576 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_return_command: exit\n");
13577 }
13578 
13579 
13580 /*
13581  *    Function: sd_return_failed_command
13582  *
13583  * Description: Command completion when an error occurred.
13584  *
13585  *     Context: May be called from interrupt context
13586  */
13587 
13588 static void
13589 sd_return_failed_command(struct sd_lun *un, struct buf *bp, int errcode)
13590 {
13591 	ASSERT(bp != NULL);
13592 	ASSERT(un != NULL);
13593 	ASSERT(mutex_owned(SD_MUTEX(un)));
13594 
13595 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13596 	    "sd_return_failed_command: entry\n");
13597 
13598 	/*
13599 	 * b_resid could already be nonzero due to a partial data
13600 	 * transfer, so do not change it here.
13601 	 */
13602 	SD_BIOERROR(bp, errcode);
13603 
13604 	sd_return_command(un, bp);
13605 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13606 	    "sd_return_failed_command: exit\n");
13607 }
13608 
13609 
13610 /*
13611  *    Function: sd_return_failed_command_no_restart
13612  *
13613  * Description: Same as sd_return_failed_command, but ensures that no
13614  *		call back into sd_start_cmds will be issued.
13615  *
13616  *     Context: May be called from interrupt context
13617  */
13618 
13619 static void
13620 sd_return_failed_command_no_restart(struct sd_lun *un, struct buf *bp,
13621 	int errcode)
13622 {
13623 	struct sd_xbuf *xp;
13624 
13625 	ASSERT(bp != NULL);
13626 	ASSERT(un != NULL);
13627 	ASSERT(mutex_owned(SD_MUTEX(un)));
13628 	xp = SD_GET_XBUF(bp);
13629 	ASSERT(xp != NULL);
13630 	ASSERT(errcode != 0);
13631 
13632 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13633 	    "sd_return_failed_command_no_restart: entry\n");
13634 
13635 	/*
13636 	 * b_resid could already be nonzero due to a partial data
13637 	 * transfer, so do not change it here.
13638 	 */
13639 	SD_BIOERROR(bp, errcode);
13640 
13641 	/*
13642 	 * If this is the failfast bp, clear it. This can happen if the
13643 	 * failfast bp encounterd a fatal error when we attempted to
13644 	 * re-try it (such as a scsi_transport(9F) failure).  However
13645 	 * we should NOT be in an active failfast state if the failfast
13646 	 * bp is not NULL.
13647 	 */
13648 	if (bp == un->un_failfast_bp) {
13649 		ASSERT(un->un_failfast_state == SD_FAILFAST_INACTIVE);
13650 		un->un_failfast_bp = NULL;
13651 	}
13652 
13653 	if (bp == un->un_retry_bp) {
13654 		/*
13655 		 * This command was retried one or more times. Show that we are
13656 		 * done with it, and allow processing of the waitq to resume.
13657 		 */
13658 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13659 		    "sd_return_failed_command_no_restart: "
13660 		    " un:0x%p: RETURNING retry_bp:0x%p\n", un, un->un_retry_bp);
13661 		un->un_retry_bp = NULL;
13662 		un->un_retry_statp = NULL;
13663 	}
13664 
13665 	SD_UPDATE_RDWR_STATS(un, bp);
13666 	SD_UPDATE_PARTITION_STATS(un, bp);
13667 
13668 	mutex_exit(SD_MUTEX(un));
13669 
13670 	if (xp->xb_pktp != NULL) {
13671 		(*(sd_destroypkt_map[xp->xb_chain_iodone]))(bp);
13672 		xp->xb_pktp = NULL;
13673 	}
13674 
13675 	SD_BEGIN_IODONE(xp->xb_chain_iodone, un, bp);
13676 
13677 	mutex_enter(SD_MUTEX(un));
13678 
13679 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13680 	    "sd_return_failed_command_no_restart: exit\n");
13681 }
13682 
13683 
13684 /*
13685  *    Function: sd_retry_command
13686  *
13687  * Description: queue up a command for retry, or (optionally) fail it
13688  *		if retry counts are exhausted.
13689  *
13690  *   Arguments: un - Pointer to the sd_lun struct for the target.
13691  *
13692  *		bp - Pointer to the buf for the command to be retried.
13693  *
13694  *		retry_check_flag - Flag to see which (if any) of the retry
13695  *		   counts should be decremented/checked. If the indicated
13696  *		   retry count is exhausted, then the command will not be
13697  *		   retried; it will be failed instead. This should use a
13698  *		   value equal to one of the following:
13699  *
13700  *			SD_RETRIES_NOCHECK
13701  *			SD_RESD_RETRIES_STANDARD
13702  *			SD_RETRIES_VICTIM
13703  *
13704  *		   Optionally may be bitwise-OR'ed with SD_RETRIES_ISOLATE
13705  *		   if the check should be made to see of FLAG_ISOLATE is set
13706  *		   in the pkt. If FLAG_ISOLATE is set, then the command is
13707  *		   not retried, it is simply failed.
13708  *
13709  *		user_funcp - Ptr to function to call before dispatching the
13710  *		   command. May be NULL if no action needs to be performed.
13711  *		   (Primarily intended for printing messages.)
13712  *
13713  *		user_arg - Optional argument to be passed along to
13714  *		   the user_funcp call.
13715  *
13716  *		failure_code - errno return code to set in the bp if the
13717  *		   command is going to be failed.
13718  *
13719  *		retry_delay - Retry delay interval in (clock_t) units. May
13720  *		   be zero which indicates that the retry should be retried
13721  *		   immediately (ie, without an intervening delay).
13722  *
13723  *		statp - Ptr to kstat function to be updated if the command
13724  *		   is queued for a delayed retry. May be NULL if no kstat
13725  *		   update is desired.
13726  *
13727  *     Context: May be called from interrupt context.
13728  */
13729 
13730 static void
13731 sd_retry_command(struct sd_lun *un, struct buf *bp, int retry_check_flag,
13732 	void (*user_funcp)(struct sd_lun *un, struct buf *bp, void *argp, int
13733 	code), void *user_arg, int failure_code,  clock_t retry_delay,
13734 	void (*statp)(kstat_io_t *))
13735 {
13736 	struct sd_xbuf	*xp;
13737 	struct scsi_pkt	*pktp;
13738 
13739 	ASSERT(un != NULL);
13740 	ASSERT(mutex_owned(SD_MUTEX(un)));
13741 	ASSERT(bp != NULL);
13742 	xp = SD_GET_XBUF(bp);
13743 	ASSERT(xp != NULL);
13744 	pktp = SD_GET_PKTP(bp);
13745 	ASSERT(pktp != NULL);
13746 
13747 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
13748 	    "sd_retry_command: entry: bp:0x%p xp:0x%p\n", bp, xp);
13749 
13750 	/*
13751 	 * If we are syncing or dumping, fail the command to avoid
13752 	 * recursively calling back into scsi_transport().
13753 	 */
13754 	if (ddi_in_panic()) {
13755 		goto fail_command_no_log;
13756 	}
13757 
13758 	/*
13759 	 * We should never be be retrying a command with FLAG_DIAGNOSE set, so
13760 	 * log an error and fail the command.
13761 	 */
13762 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
13763 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
13764 		    "ERROR, retrying FLAG_DIAGNOSE command.\n");
13765 		sd_dump_memory(un, SD_LOG_IO, "CDB",
13766 		    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
13767 		sd_dump_memory(un, SD_LOG_IO, "Sense Data",
13768 		    (uchar_t *)xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
13769 		goto fail_command;
13770 	}
13771 
13772 	/*
13773 	 * If we are suspended, then put the command onto head of the
13774 	 * wait queue since we don't want to start more commands, and
13775 	 * clear the un_retry_bp. Next time when we are resumed, will
13776 	 * handle the command in the wait queue.
13777 	 */
13778 	switch (un->un_state) {
13779 	case SD_STATE_SUSPENDED:
13780 	case SD_STATE_DUMPING:
13781 		bp->av_forw = un->un_waitq_headp;
13782 		un->un_waitq_headp = bp;
13783 		if (un->un_waitq_tailp == NULL) {
13784 			un->un_waitq_tailp = bp;
13785 		}
13786 		if (bp == un->un_retry_bp) {
13787 			un->un_retry_bp = NULL;
13788 			un->un_retry_statp = NULL;
13789 		}
13790 		SD_UPDATE_KSTATS(un, kstat_waitq_enter, bp);
13791 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: "
13792 		    "exiting; cmd bp:0x%p requeued for SUSPEND/DUMP\n", bp);
13793 		return;
13794 	default:
13795 		break;
13796 	}
13797 
13798 	/*
13799 	 * If the caller wants us to check FLAG_ISOLATE, then see if that
13800 	 * is set; if it is then we do not want to retry the command.
13801 	 * Normally, FLAG_ISOLATE is only used with USCSI cmds.
13802 	 */
13803 	if ((retry_check_flag & SD_RETRIES_ISOLATE) != 0) {
13804 		if ((pktp->pkt_flags & FLAG_ISOLATE) != 0) {
13805 			goto fail_command;
13806 		}
13807 	}
13808 
13809 
13810 	/*
13811 	 * If SD_RETRIES_FAILFAST is set, it indicates that either a
13812 	 * command timeout or a selection timeout has occurred. This means
13813 	 * that we were unable to establish an kind of communication with
13814 	 * the target, and subsequent retries and/or commands are likely
13815 	 * to encounter similar results and take a long time to complete.
13816 	 *
13817 	 * If this is a failfast error condition, we need to update the
13818 	 * failfast state, even if this bp does not have B_FAILFAST set.
13819 	 */
13820 	if (retry_check_flag & SD_RETRIES_FAILFAST) {
13821 		if (un->un_failfast_state == SD_FAILFAST_ACTIVE) {
13822 			ASSERT(un->un_failfast_bp == NULL);
13823 			/*
13824 			 * If we are already in the active failfast state, and
13825 			 * another failfast error condition has been detected,
13826 			 * then fail this command if it has B_FAILFAST set.
13827 			 * If B_FAILFAST is clear, then maintain the legacy
13828 			 * behavior of retrying heroically, even tho this will
13829 			 * take a lot more time to fail the command.
13830 			 */
13831 			if (bp->b_flags & B_FAILFAST) {
13832 				goto fail_command;
13833 			}
13834 		} else {
13835 			/*
13836 			 * We're not in the active failfast state, but we
13837 			 * have a failfast error condition, so we must begin
13838 			 * transition to the next state. We do this regardless
13839 			 * of whether or not this bp has B_FAILFAST set.
13840 			 */
13841 			if (un->un_failfast_bp == NULL) {
13842 				/*
13843 				 * This is the first bp to meet a failfast
13844 				 * condition so save it on un_failfast_bp &
13845 				 * do normal retry processing. Do not enter
13846 				 * active failfast state yet. This marks
13847 				 * entry into the "failfast pending" state.
13848 				 */
13849 				un->un_failfast_bp = bp;
13850 
13851 			} else if (un->un_failfast_bp == bp) {
13852 				/*
13853 				 * This is the second time *this* bp has
13854 				 * encountered a failfast error condition,
13855 				 * so enter active failfast state & flush
13856 				 * queues as appropriate.
13857 				 */
13858 				un->un_failfast_state = SD_FAILFAST_ACTIVE;
13859 				un->un_failfast_bp = NULL;
13860 				sd_failfast_flushq(un);
13861 
13862 				/*
13863 				 * Fail this bp now if B_FAILFAST set;
13864 				 * otherwise continue with retries. (It would
13865 				 * be pretty ironic if this bp succeeded on a
13866 				 * subsequent retry after we just flushed all
13867 				 * the queues).
13868 				 */
13869 				if (bp->b_flags & B_FAILFAST) {
13870 					goto fail_command;
13871 				}
13872 
13873 #if !defined(lint) && !defined(__lint)
13874 			} else {
13875 				/*
13876 				 * If neither of the preceeding conditionals
13877 				 * was true, it means that there is some
13878 				 * *other* bp that has met an inital failfast
13879 				 * condition and is currently either being
13880 				 * retried or is waiting to be retried. In
13881 				 * that case we should perform normal retry
13882 				 * processing on *this* bp, since there is a
13883 				 * chance that the current failfast condition
13884 				 * is transient and recoverable. If that does
13885 				 * not turn out to be the case, then retries
13886 				 * will be cleared when the wait queue is
13887 				 * flushed anyway.
13888 				 */
13889 #endif
13890 			}
13891 		}
13892 	} else {
13893 		/*
13894 		 * SD_RETRIES_FAILFAST is clear, which indicates that we
13895 		 * likely were able to at least establish some level of
13896 		 * communication with the target and subsequent commands
13897 		 * and/or retries are likely to get through to the target,
13898 		 * In this case we want to be aggressive about clearing
13899 		 * the failfast state. Note that this does not affect
13900 		 * the "failfast pending" condition.
13901 		 */
13902 		un->un_failfast_state = SD_FAILFAST_INACTIVE;
13903 	}
13904 
13905 
13906 	/*
13907 	 * Check the specified retry count to see if we can still do
13908 	 * any retries with this pkt before we should fail it.
13909 	 */
13910 	switch (retry_check_flag & SD_RETRIES_MASK) {
13911 	case SD_RETRIES_VICTIM:
13912 		/*
13913 		 * Check the victim retry count. If exhausted, then fall
13914 		 * thru & check against the standard retry count.
13915 		 */
13916 		if (xp->xb_victim_retry_count < un->un_victim_retry_count) {
13917 			/* Increment count & proceed with the retry */
13918 			xp->xb_victim_retry_count++;
13919 			break;
13920 		}
13921 		/* Victim retries exhausted, fall back to std. retries... */
13922 		/* FALLTHRU */
13923 
13924 	case SD_RETRIES_STANDARD:
13925 		if (xp->xb_retry_count >= un->un_retry_count) {
13926 			/* Retries exhausted, fail the command */
13927 			SD_TRACE(SD_LOG_IO_CORE, un,
13928 			    "sd_retry_command: retries exhausted!\n");
13929 			/*
13930 			 * update b_resid for failed SCMD_READ & SCMD_WRITE
13931 			 * commands with nonzero pkt_resid.
13932 			 */
13933 			if ((pktp->pkt_reason == CMD_CMPLT) &&
13934 			    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD) &&
13935 			    (pktp->pkt_resid != 0)) {
13936 				uchar_t op = SD_GET_PKT_OPCODE(pktp) & 0x1F;
13937 				if ((op == SCMD_READ) || (op == SCMD_WRITE)) {
13938 					SD_UPDATE_B_RESID(bp, pktp);
13939 				}
13940 			}
13941 			goto fail_command;
13942 		}
13943 		xp->xb_retry_count++;
13944 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13945 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13946 		break;
13947 
13948 	case SD_RETRIES_UA:
13949 		if (xp->xb_ua_retry_count >= sd_ua_retry_count) {
13950 			/* Retries exhausted, fail the command */
13951 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
13952 			    "Unit Attention retries exhausted. "
13953 			    "Check the target.\n");
13954 			goto fail_command;
13955 		}
13956 		xp->xb_ua_retry_count++;
13957 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13958 		    "sd_retry_command: retry count:%d\n",
13959 		    xp->xb_ua_retry_count);
13960 		break;
13961 
13962 	case SD_RETRIES_BUSY:
13963 		if (xp->xb_retry_count >= un->un_busy_retry_count) {
13964 			/* Retries exhausted, fail the command */
13965 			SD_TRACE(SD_LOG_IO_CORE, un,
13966 			    "sd_retry_command: retries exhausted!\n");
13967 			goto fail_command;
13968 		}
13969 		xp->xb_retry_count++;
13970 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
13971 		    "sd_retry_command: retry count:%d\n", xp->xb_retry_count);
13972 		break;
13973 
13974 	case SD_RETRIES_NOCHECK:
13975 	default:
13976 		/* No retry count to check. Just proceed with the retry */
13977 		break;
13978 	}
13979 
13980 	xp->xb_pktp->pkt_flags |= FLAG_HEAD;
13981 
13982 	/*
13983 	 * If we were given a zero timeout, we must attempt to retry the
13984 	 * command immediately (ie, without a delay).
13985 	 */
13986 	if (retry_delay == 0) {
13987 		/*
13988 		 * Check some limiting conditions to see if we can actually
13989 		 * do the immediate retry.  If we cannot, then we must
13990 		 * fall back to queueing up a delayed retry.
13991 		 */
13992 		if (un->un_ncmds_in_transport >= un->un_throttle) {
13993 			/*
13994 			 * We are at the throttle limit for the target,
13995 			 * fall back to delayed retry.
13996 			 */
13997 			retry_delay = SD_BSY_TIMEOUT;
13998 			statp = kstat_waitq_enter;
13999 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14000 			    "sd_retry_command: immed. retry hit "
14001 			    "throttle!\n");
14002 		} else {
14003 			/*
14004 			 * We're clear to proceed with the immediate retry.
14005 			 * First call the user-provided function (if any)
14006 			 */
14007 			if (user_funcp != NULL) {
14008 				(*user_funcp)(un, bp, user_arg,
14009 				    SD_IMMEDIATE_RETRY_ISSUED);
14010 #ifdef __lock_lint
14011 				sd_print_incomplete_msg(un, bp, user_arg,
14012 				    SD_IMMEDIATE_RETRY_ISSUED);
14013 				sd_print_cmd_incomplete_msg(un, bp, user_arg,
14014 				    SD_IMMEDIATE_RETRY_ISSUED);
14015 				sd_print_sense_failed_msg(un, bp, user_arg,
14016 				    SD_IMMEDIATE_RETRY_ISSUED);
14017 #endif
14018 			}
14019 
14020 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14021 			    "sd_retry_command: issuing immediate retry\n");
14022 
14023 			/*
14024 			 * Call sd_start_cmds() to transport the command to
14025 			 * the target.
14026 			 */
14027 			sd_start_cmds(un, bp);
14028 
14029 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14030 			    "sd_retry_command exit\n");
14031 			return;
14032 		}
14033 	}
14034 
14035 	/*
14036 	 * Set up to retry the command after a delay.
14037 	 * First call the user-provided function (if any)
14038 	 */
14039 	if (user_funcp != NULL) {
14040 		(*user_funcp)(un, bp, user_arg, SD_DELAYED_RETRY_ISSUED);
14041 	}
14042 
14043 	sd_set_retry_bp(un, bp, retry_delay, statp);
14044 
14045 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
14046 	return;
14047 
14048 fail_command:
14049 
14050 	if (user_funcp != NULL) {
14051 		(*user_funcp)(un, bp, user_arg, SD_NO_RETRY_ISSUED);
14052 	}
14053 
14054 fail_command_no_log:
14055 
14056 	SD_INFO(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14057 	    "sd_retry_command: returning failed command\n");
14058 
14059 	sd_return_failed_command(un, bp, failure_code);
14060 
14061 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_retry_command: exit\n");
14062 }
14063 
14064 
14065 /*
14066  *    Function: sd_set_retry_bp
14067  *
14068  * Description: Set up the given bp for retry.
14069  *
14070  *   Arguments: un - ptr to associated softstate
14071  *		bp - ptr to buf(9S) for the command
14072  *		retry_delay - time interval before issuing retry (may be 0)
14073  *		statp - optional pointer to kstat function
14074  *
14075  *     Context: May be called under interrupt context
14076  */
14077 
14078 static void
14079 sd_set_retry_bp(struct sd_lun *un, struct buf *bp, clock_t retry_delay,
14080 	void (*statp)(kstat_io_t *))
14081 {
14082 	ASSERT(un != NULL);
14083 	ASSERT(mutex_owned(SD_MUTEX(un)));
14084 	ASSERT(bp != NULL);
14085 
14086 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14087 	    "sd_set_retry_bp: entry: un:0x%p bp:0x%p\n", un, bp);
14088 
14089 	/*
14090 	 * Indicate that the command is being retried. This will not allow any
14091 	 * other commands on the wait queue to be transported to the target
14092 	 * until this command has been completed (success or failure). The
14093 	 * "retry command" is not transported to the target until the given
14094 	 * time delay expires, unless the user specified a 0 retry_delay.
14095 	 *
14096 	 * Note: the timeout(9F) callback routine is what actually calls
14097 	 * sd_start_cmds() to transport the command, with the exception of a
14098 	 * zero retry_delay. The only current implementor of a zero retry delay
14099 	 * is the case where a START_STOP_UNIT is sent to spin-up a device.
14100 	 */
14101 	if (un->un_retry_bp == NULL) {
14102 		ASSERT(un->un_retry_statp == NULL);
14103 		un->un_retry_bp = bp;
14104 
14105 		/*
14106 		 * If the user has not specified a delay the command should
14107 		 * be queued and no timeout should be scheduled.
14108 		 */
14109 		if (retry_delay == 0) {
14110 			/*
14111 			 * Save the kstat pointer that will be used in the
14112 			 * call to SD_UPDATE_KSTATS() below, so that
14113 			 * sd_start_cmds() can correctly decrement the waitq
14114 			 * count when it is time to transport this command.
14115 			 */
14116 			un->un_retry_statp = statp;
14117 			goto done;
14118 		}
14119 	}
14120 
14121 	if (un->un_retry_bp == bp) {
14122 		/*
14123 		 * Save the kstat pointer that will be used in the call to
14124 		 * SD_UPDATE_KSTATS() below, so that sd_start_cmds() can
14125 		 * correctly decrement the waitq count when it is time to
14126 		 * transport this command.
14127 		 */
14128 		un->un_retry_statp = statp;
14129 
14130 		/*
14131 		 * Schedule a timeout if:
14132 		 *   1) The user has specified a delay.
14133 		 *   2) There is not a START_STOP_UNIT callback pending.
14134 		 *
14135 		 * If no delay has been specified, then it is up to the caller
14136 		 * to ensure that IO processing continues without stalling.
14137 		 * Effectively, this means that the caller will issue the
14138 		 * required call to sd_start_cmds(). The START_STOP_UNIT
14139 		 * callback does this after the START STOP UNIT command has
14140 		 * completed. In either of these cases we should not schedule
14141 		 * a timeout callback here.  Also don't schedule the timeout if
14142 		 * an SD_PATH_DIRECT_PRIORITY command is waiting to restart.
14143 		 */
14144 		if ((retry_delay != 0) && (un->un_startstop_timeid == NULL) &&
14145 		    (un->un_direct_priority_timeid == NULL)) {
14146 			un->un_retry_timeid =
14147 			    timeout(sd_start_retry_command, un, retry_delay);
14148 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14149 			    "sd_set_retry_bp: setting timeout: un: 0x%p"
14150 			    " bp:0x%p un_retry_timeid:0x%p\n",
14151 			    un, bp, un->un_retry_timeid);
14152 		}
14153 	} else {
14154 		/*
14155 		 * We only get in here if there is already another command
14156 		 * waiting to be retried.  In this case, we just put the
14157 		 * given command onto the wait queue, so it can be transported
14158 		 * after the current retry command has completed.
14159 		 *
14160 		 * Also we have to make sure that if the command at the head
14161 		 * of the wait queue is the un_failfast_bp, that we do not
14162 		 * put ahead of it any other commands that are to be retried.
14163 		 */
14164 		if ((un->un_failfast_bp != NULL) &&
14165 		    (un->un_failfast_bp == un->un_waitq_headp)) {
14166 			/*
14167 			 * Enqueue this command AFTER the first command on
14168 			 * the wait queue (which is also un_failfast_bp).
14169 			 */
14170 			bp->av_forw = un->un_waitq_headp->av_forw;
14171 			un->un_waitq_headp->av_forw = bp;
14172 			if (un->un_waitq_headp == un->un_waitq_tailp) {
14173 				un->un_waitq_tailp = bp;
14174 			}
14175 		} else {
14176 			/* Enqueue this command at the head of the waitq. */
14177 			bp->av_forw = un->un_waitq_headp;
14178 			un->un_waitq_headp = bp;
14179 			if (un->un_waitq_tailp == NULL) {
14180 				un->un_waitq_tailp = bp;
14181 			}
14182 		}
14183 
14184 		if (statp == NULL) {
14185 			statp = kstat_waitq_enter;
14186 		}
14187 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14188 		    "sd_set_retry_bp: un:0x%p already delayed retry\n", un);
14189 	}
14190 
14191 done:
14192 	if (statp != NULL) {
14193 		SD_UPDATE_KSTATS(un, statp, bp);
14194 	}
14195 
14196 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14197 	    "sd_set_retry_bp: exit un:0x%p\n", un);
14198 }
14199 
14200 
14201 /*
14202  *    Function: sd_start_retry_command
14203  *
14204  * Description: Start the command that has been waiting on the target's
14205  *		retry queue.  Called from timeout(9F) context after the
14206  *		retry delay interval has expired.
14207  *
14208  *   Arguments: arg - pointer to associated softstate for the device.
14209  *
14210  *     Context: timeout(9F) thread context.  May not sleep.
14211  */
14212 
14213 static void
14214 sd_start_retry_command(void *arg)
14215 {
14216 	struct sd_lun *un = arg;
14217 
14218 	ASSERT(un != NULL);
14219 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14220 
14221 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14222 	    "sd_start_retry_command: entry\n");
14223 
14224 	mutex_enter(SD_MUTEX(un));
14225 
14226 	un->un_retry_timeid = NULL;
14227 
14228 	if (un->un_retry_bp != NULL) {
14229 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14230 		    "sd_start_retry_command: un:0x%p STARTING bp:0x%p\n",
14231 		    un, un->un_retry_bp);
14232 		sd_start_cmds(un, un->un_retry_bp);
14233 	}
14234 
14235 	mutex_exit(SD_MUTEX(un));
14236 
14237 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14238 	    "sd_start_retry_command: exit\n");
14239 }
14240 
14241 
14242 /*
14243  *    Function: sd_start_direct_priority_command
14244  *
14245  * Description: Used to re-start an SD_PATH_DIRECT_PRIORITY command that had
14246  *		received TRAN_BUSY when we called scsi_transport() to send it
14247  *		to the underlying HBA. This function is called from timeout(9F)
14248  *		context after the delay interval has expired.
14249  *
14250  *   Arguments: arg - pointer to associated buf(9S) to be restarted.
14251  *
14252  *     Context: timeout(9F) thread context.  May not sleep.
14253  */
14254 
14255 static void
14256 sd_start_direct_priority_command(void *arg)
14257 {
14258 	struct buf	*priority_bp = arg;
14259 	struct sd_lun	*un;
14260 
14261 	ASSERT(priority_bp != NULL);
14262 	un = SD_GET_UN(priority_bp);
14263 	ASSERT(un != NULL);
14264 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14265 
14266 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14267 	    "sd_start_direct_priority_command: entry\n");
14268 
14269 	mutex_enter(SD_MUTEX(un));
14270 	un->un_direct_priority_timeid = NULL;
14271 	sd_start_cmds(un, priority_bp);
14272 	mutex_exit(SD_MUTEX(un));
14273 
14274 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14275 	    "sd_start_direct_priority_command: exit\n");
14276 }
14277 
14278 
14279 /*
14280  *    Function: sd_send_request_sense_command
14281  *
14282  * Description: Sends a REQUEST SENSE command to the target
14283  *
14284  *     Context: May be called from interrupt context.
14285  */
14286 
14287 static void
14288 sd_send_request_sense_command(struct sd_lun *un, struct buf *bp,
14289 	struct scsi_pkt *pktp)
14290 {
14291 	ASSERT(bp != NULL);
14292 	ASSERT(un != NULL);
14293 	ASSERT(mutex_owned(SD_MUTEX(un)));
14294 
14295 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_send_request_sense_command: "
14296 	    "entry: buf:0x%p\n", bp);
14297 
14298 	/*
14299 	 * If we are syncing or dumping, then fail the command to avoid a
14300 	 * recursive callback into scsi_transport(). Also fail the command
14301 	 * if we are suspended (legacy behavior).
14302 	 */
14303 	if (ddi_in_panic() || (un->un_state == SD_STATE_SUSPENDED) ||
14304 	    (un->un_state == SD_STATE_DUMPING)) {
14305 		sd_return_failed_command(un, bp, EIO);
14306 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14307 		    "sd_send_request_sense_command: syncing/dumping, exit\n");
14308 		return;
14309 	}
14310 
14311 	/*
14312 	 * Retry the failed command and don't issue the request sense if:
14313 	 *    1) the sense buf is busy
14314 	 *    2) we have 1 or more outstanding commands on the target
14315 	 *    (the sense data will be cleared or invalidated any way)
14316 	 *
14317 	 * Note: There could be an issue with not checking a retry limit here,
14318 	 * the problem is determining which retry limit to check.
14319 	 */
14320 	if ((un->un_sense_isbusy != 0) || (un->un_ncmds_in_transport > 0)) {
14321 		/* Don't retry if the command is flagged as non-retryable */
14322 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
14323 			sd_retry_command(un, bp, SD_RETRIES_NOCHECK,
14324 			    NULL, NULL, 0, SD_BSY_TIMEOUT, kstat_waitq_enter);
14325 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14326 			    "sd_send_request_sense_command: "
14327 			    "at full throttle, retrying exit\n");
14328 		} else {
14329 			sd_return_failed_command(un, bp, EIO);
14330 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14331 			    "sd_send_request_sense_command: "
14332 			    "at full throttle, non-retryable exit\n");
14333 		}
14334 		return;
14335 	}
14336 
14337 	sd_mark_rqs_busy(un, bp);
14338 	sd_start_cmds(un, un->un_rqs_bp);
14339 
14340 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14341 	    "sd_send_request_sense_command: exit\n");
14342 }
14343 
14344 
14345 /*
14346  *    Function: sd_mark_rqs_busy
14347  *
14348  * Description: Indicate that the request sense bp for this instance is
14349  *		in use.
14350  *
14351  *     Context: May be called under interrupt context
14352  */
14353 
14354 static void
14355 sd_mark_rqs_busy(struct sd_lun *un, struct buf *bp)
14356 {
14357 	struct sd_xbuf	*sense_xp;
14358 
14359 	ASSERT(un != NULL);
14360 	ASSERT(bp != NULL);
14361 	ASSERT(mutex_owned(SD_MUTEX(un)));
14362 	ASSERT(un->un_sense_isbusy == 0);
14363 
14364 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: entry: "
14365 	    "buf:0x%p xp:0x%p un:0x%p\n", bp, SD_GET_XBUF(bp), un);
14366 
14367 	sense_xp = SD_GET_XBUF(un->un_rqs_bp);
14368 	ASSERT(sense_xp != NULL);
14369 
14370 	SD_INFO(SD_LOG_IO, un,
14371 	    "sd_mark_rqs_busy: entry: sense_xp:0x%p\n", sense_xp);
14372 
14373 	ASSERT(sense_xp->xb_pktp != NULL);
14374 	ASSERT((sense_xp->xb_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD))
14375 	    == (FLAG_SENSING | FLAG_HEAD));
14376 
14377 	un->un_sense_isbusy = 1;
14378 	un->un_rqs_bp->b_resid = 0;
14379 	sense_xp->xb_pktp->pkt_resid  = 0;
14380 	sense_xp->xb_pktp->pkt_reason = 0;
14381 
14382 	/* So we can get back the bp at interrupt time! */
14383 	sense_xp->xb_sense_bp = bp;
14384 
14385 	bzero(un->un_rqs_bp->b_un.b_addr, SENSE_LENGTH);
14386 
14387 	/*
14388 	 * Mark this buf as awaiting sense data. (This is already set in
14389 	 * the pkt_flags for the RQS packet.)
14390 	 */
14391 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags |= FLAG_SENSING;
14392 
14393 	sense_xp->xb_retry_count	= 0;
14394 	sense_xp->xb_victim_retry_count = 0;
14395 	sense_xp->xb_ua_retry_count	= 0;
14396 	sense_xp->xb_nr_retry_count 	= 0;
14397 	sense_xp->xb_dma_resid  = 0;
14398 
14399 	/* Clean up the fields for auto-request sense */
14400 	sense_xp->xb_sense_status = 0;
14401 	sense_xp->xb_sense_state  = 0;
14402 	sense_xp->xb_sense_resid  = 0;
14403 	bzero(sense_xp->xb_sense_data, sizeof (sense_xp->xb_sense_data));
14404 
14405 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_mark_rqs_busy: exit\n");
14406 }
14407 
14408 
14409 /*
14410  *    Function: sd_mark_rqs_idle
14411  *
14412  * Description: SD_MUTEX must be held continuously through this routine
14413  *		to prevent reuse of the rqs struct before the caller can
14414  *		complete it's processing.
14415  *
14416  * Return Code: Pointer to the RQS buf
14417  *
14418  *     Context: May be called under interrupt context
14419  */
14420 
14421 static struct buf *
14422 sd_mark_rqs_idle(struct sd_lun *un, struct sd_xbuf *sense_xp)
14423 {
14424 	struct buf *bp;
14425 	ASSERT(un != NULL);
14426 	ASSERT(sense_xp != NULL);
14427 	ASSERT(mutex_owned(SD_MUTEX(un)));
14428 	ASSERT(un->un_sense_isbusy != 0);
14429 
14430 	un->un_sense_isbusy = 0;
14431 	bp = sense_xp->xb_sense_bp;
14432 	sense_xp->xb_sense_bp = NULL;
14433 
14434 	/* This pkt is no longer interested in getting sense data */
14435 	((SD_GET_XBUF(bp))->xb_pktp)->pkt_flags &= ~FLAG_SENSING;
14436 
14437 	return (bp);
14438 }
14439 
14440 
14441 
14442 /*
14443  *    Function: sd_alloc_rqs
14444  *
14445  * Description: Set up the unit to receive auto request sense data
14446  *
14447  * Return Code: DDI_SUCCESS or DDI_FAILURE
14448  *
14449  *     Context: Called under attach(9E) context
14450  */
14451 
14452 static int
14453 sd_alloc_rqs(struct scsi_device *devp, struct sd_lun *un)
14454 {
14455 	struct sd_xbuf *xp;
14456 
14457 	ASSERT(un != NULL);
14458 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14459 	ASSERT(un->un_rqs_bp == NULL);
14460 	ASSERT(un->un_rqs_pktp == NULL);
14461 
14462 	/*
14463 	 * First allocate the required buf and scsi_pkt structs, then set up
14464 	 * the CDB in the scsi_pkt for a REQUEST SENSE command.
14465 	 */
14466 	un->un_rqs_bp = scsi_alloc_consistent_buf(&devp->sd_address, NULL,
14467 	    MAX_SENSE_LENGTH, B_READ, SLEEP_FUNC, NULL);
14468 	if (un->un_rqs_bp == NULL) {
14469 		return (DDI_FAILURE);
14470 	}
14471 
14472 	un->un_rqs_pktp = scsi_init_pkt(&devp->sd_address, NULL, un->un_rqs_bp,
14473 	    CDB_GROUP0, 1, 0, PKT_CONSISTENT, SLEEP_FUNC, NULL);
14474 
14475 	if (un->un_rqs_pktp == NULL) {
14476 		sd_free_rqs(un);
14477 		return (DDI_FAILURE);
14478 	}
14479 
14480 	/* Set up the CDB in the scsi_pkt for a REQUEST SENSE command. */
14481 	(void) scsi_setup_cdb((union scsi_cdb *)un->un_rqs_pktp->pkt_cdbp,
14482 	    SCMD_REQUEST_SENSE, 0, MAX_SENSE_LENGTH, 0);
14483 
14484 	SD_FILL_SCSI1_LUN(un, un->un_rqs_pktp);
14485 
14486 	/* Set up the other needed members in the ARQ scsi_pkt. */
14487 	un->un_rqs_pktp->pkt_comp   = sdintr;
14488 	un->un_rqs_pktp->pkt_time   = sd_io_time;
14489 	un->un_rqs_pktp->pkt_flags |=
14490 	    (FLAG_SENSING | FLAG_HEAD);	/* (1222170) */
14491 
14492 	/*
14493 	 * Allocate  & init the sd_xbuf struct for the RQS command. Do not
14494 	 * provide any intpkt, destroypkt routines as we take care of
14495 	 * scsi_pkt allocation/freeing here and in sd_free_rqs().
14496 	 */
14497 	xp = kmem_alloc(sizeof (struct sd_xbuf), KM_SLEEP);
14498 	sd_xbuf_init(un, un->un_rqs_bp, xp, SD_CHAIN_NULL, NULL);
14499 	xp->xb_pktp = un->un_rqs_pktp;
14500 	SD_INFO(SD_LOG_ATTACH_DETACH, un,
14501 	    "sd_alloc_rqs: un 0x%p, rqs  xp 0x%p,  pkt 0x%p,  buf 0x%p\n",
14502 	    un, xp, un->un_rqs_pktp, un->un_rqs_bp);
14503 
14504 	/*
14505 	 * Save the pointer to the request sense private bp so it can
14506 	 * be retrieved in sdintr.
14507 	 */
14508 	un->un_rqs_pktp->pkt_private = un->un_rqs_bp;
14509 	ASSERT(un->un_rqs_bp->b_private == xp);
14510 
14511 	/*
14512 	 * See if the HBA supports auto-request sense for the specified
14513 	 * target/lun. If it does, then try to enable it (if not already
14514 	 * enabled).
14515 	 *
14516 	 * Note: For some HBAs (ifp & sf), scsi_ifsetcap will always return
14517 	 * failure, while for other HBAs (pln) scsi_ifsetcap will always
14518 	 * return success.  However, in both of these cases ARQ is always
14519 	 * enabled and scsi_ifgetcap will always return true. The best approach
14520 	 * is to issue the scsi_ifgetcap() first, then try the scsi_ifsetcap().
14521 	 *
14522 	 * The 3rd case is the HBA (adp) always return enabled on
14523 	 * scsi_ifgetgetcap even when it's not enable, the best approach
14524 	 * is issue a scsi_ifsetcap then a scsi_ifgetcap
14525 	 * Note: this case is to circumvent the Adaptec bug. (x86 only)
14526 	 */
14527 
14528 	if (un->un_f_is_fibre == TRUE) {
14529 		un->un_f_arq_enabled = TRUE;
14530 	} else {
14531 #if defined(__i386) || defined(__amd64)
14532 		/*
14533 		 * Circumvent the Adaptec bug, remove this code when
14534 		 * the bug is fixed
14535 		 */
14536 		(void) scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1);
14537 #endif
14538 		switch (scsi_ifgetcap(SD_ADDRESS(un), "auto-rqsense", 1)) {
14539 		case 0:
14540 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14541 			    "sd_alloc_rqs: HBA supports ARQ\n");
14542 			/*
14543 			 * ARQ is supported by this HBA but currently is not
14544 			 * enabled. Attempt to enable it and if successful then
14545 			 * mark this instance as ARQ enabled.
14546 			 */
14547 			if (scsi_ifsetcap(SD_ADDRESS(un), "auto-rqsense", 1, 1)
14548 			    == 1) {
14549 				/* Successfully enabled ARQ in the HBA */
14550 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14551 				    "sd_alloc_rqs: ARQ enabled\n");
14552 				un->un_f_arq_enabled = TRUE;
14553 			} else {
14554 				/* Could not enable ARQ in the HBA */
14555 				SD_INFO(SD_LOG_ATTACH_DETACH, un,
14556 				    "sd_alloc_rqs: failed ARQ enable\n");
14557 				un->un_f_arq_enabled = FALSE;
14558 			}
14559 			break;
14560 		case 1:
14561 			/*
14562 			 * ARQ is supported by this HBA and is already enabled.
14563 			 * Just mark ARQ as enabled for this instance.
14564 			 */
14565 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14566 			    "sd_alloc_rqs: ARQ already enabled\n");
14567 			un->un_f_arq_enabled = TRUE;
14568 			break;
14569 		default:
14570 			/*
14571 			 * ARQ is not supported by this HBA; disable it for this
14572 			 * instance.
14573 			 */
14574 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
14575 			    "sd_alloc_rqs: HBA does not support ARQ\n");
14576 			un->un_f_arq_enabled = FALSE;
14577 			break;
14578 		}
14579 	}
14580 
14581 	return (DDI_SUCCESS);
14582 }
14583 
14584 
14585 /*
14586  *    Function: sd_free_rqs
14587  *
14588  * Description: Cleanup for the pre-instance RQS command.
14589  *
14590  *     Context: Kernel thread context
14591  */
14592 
14593 static void
14594 sd_free_rqs(struct sd_lun *un)
14595 {
14596 	ASSERT(un != NULL);
14597 
14598 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: entry\n");
14599 
14600 	/*
14601 	 * If consistent memory is bound to a scsi_pkt, the pkt
14602 	 * has to be destroyed *before* freeing the consistent memory.
14603 	 * Don't change the sequence of this operations.
14604 	 * scsi_destroy_pkt() might access memory, which isn't allowed,
14605 	 * after it was freed in scsi_free_consistent_buf().
14606 	 */
14607 	if (un->un_rqs_pktp != NULL) {
14608 		scsi_destroy_pkt(un->un_rqs_pktp);
14609 		un->un_rqs_pktp = NULL;
14610 	}
14611 
14612 	if (un->un_rqs_bp != NULL) {
14613 		struct sd_xbuf *xp = SD_GET_XBUF(un->un_rqs_bp);
14614 		if (xp != NULL) {
14615 			kmem_free(xp, sizeof (struct sd_xbuf));
14616 		}
14617 		scsi_free_consistent_buf(un->un_rqs_bp);
14618 		un->un_rqs_bp = NULL;
14619 	}
14620 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_free_rqs: exit\n");
14621 }
14622 
14623 
14624 
14625 /*
14626  *    Function: sd_reduce_throttle
14627  *
14628  * Description: Reduces the maximum # of outstanding commands on a
14629  *		target to the current number of outstanding commands.
14630  *		Queues a tiemout(9F) callback to restore the limit
14631  *		after a specified interval has elapsed.
14632  *		Typically used when we get a TRAN_BUSY return code
14633  *		back from scsi_transport().
14634  *
14635  *   Arguments: un - ptr to the sd_lun softstate struct
14636  *		throttle_type: SD_THROTTLE_TRAN_BUSY or SD_THROTTLE_QFULL
14637  *
14638  *     Context: May be called from interrupt context
14639  */
14640 
14641 static void
14642 sd_reduce_throttle(struct sd_lun *un, int throttle_type)
14643 {
14644 	ASSERT(un != NULL);
14645 	ASSERT(mutex_owned(SD_MUTEX(un)));
14646 	ASSERT(un->un_ncmds_in_transport >= 0);
14647 
14648 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14649 	    "entry: un:0x%p un_throttle:%d un_ncmds_in_transport:%d\n",
14650 	    un, un->un_throttle, un->un_ncmds_in_transport);
14651 
14652 	if (un->un_throttle > 1) {
14653 		if (un->un_f_use_adaptive_throttle == TRUE) {
14654 			switch (throttle_type) {
14655 			case SD_THROTTLE_TRAN_BUSY:
14656 				if (un->un_busy_throttle == 0) {
14657 					un->un_busy_throttle = un->un_throttle;
14658 				}
14659 				break;
14660 			case SD_THROTTLE_QFULL:
14661 				un->un_busy_throttle = 0;
14662 				break;
14663 			default:
14664 				ASSERT(FALSE);
14665 			}
14666 
14667 			if (un->un_ncmds_in_transport > 0) {
14668 				un->un_throttle = un->un_ncmds_in_transport;
14669 			}
14670 
14671 		} else {
14672 			if (un->un_ncmds_in_transport == 0) {
14673 				un->un_throttle = 1;
14674 			} else {
14675 				un->un_throttle = un->un_ncmds_in_transport;
14676 			}
14677 		}
14678 	}
14679 
14680 	/* Reschedule the timeout if none is currently active */
14681 	if (un->un_reset_throttle_timeid == NULL) {
14682 		un->un_reset_throttle_timeid = timeout(sd_restore_throttle,
14683 		    un, SD_THROTTLE_RESET_INTERVAL);
14684 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14685 		    "sd_reduce_throttle: timeout scheduled!\n");
14686 	}
14687 
14688 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reduce_throttle: "
14689 	    "exit: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14690 }
14691 
14692 
14693 
14694 /*
14695  *    Function: sd_restore_throttle
14696  *
14697  * Description: Callback function for timeout(9F).  Resets the current
14698  *		value of un->un_throttle to its default.
14699  *
14700  *   Arguments: arg - pointer to associated softstate for the device.
14701  *
14702  *     Context: May be called from interrupt context
14703  */
14704 
14705 static void
14706 sd_restore_throttle(void *arg)
14707 {
14708 	struct sd_lun	*un = arg;
14709 
14710 	ASSERT(un != NULL);
14711 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14712 
14713 	mutex_enter(SD_MUTEX(un));
14714 
14715 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14716 	    "entry: un:0x%p un_throttle:%d\n", un, un->un_throttle);
14717 
14718 	un->un_reset_throttle_timeid = NULL;
14719 
14720 	if (un->un_f_use_adaptive_throttle == TRUE) {
14721 		/*
14722 		 * If un_busy_throttle is nonzero, then it contains the
14723 		 * value that un_throttle was when we got a TRAN_BUSY back
14724 		 * from scsi_transport(). We want to revert back to this
14725 		 * value.
14726 		 *
14727 		 * In the QFULL case, the throttle limit will incrementally
14728 		 * increase until it reaches max throttle.
14729 		 */
14730 		if (un->un_busy_throttle > 0) {
14731 			un->un_throttle = un->un_busy_throttle;
14732 			un->un_busy_throttle = 0;
14733 		} else {
14734 			/*
14735 			 * increase throttle by 10% open gate slowly, schedule
14736 			 * another restore if saved throttle has not been
14737 			 * reached
14738 			 */
14739 			short throttle;
14740 			if (sd_qfull_throttle_enable) {
14741 				throttle = un->un_throttle +
14742 				    max((un->un_throttle / 10), 1);
14743 				un->un_throttle =
14744 				    (throttle < un->un_saved_throttle) ?
14745 				    throttle : un->un_saved_throttle;
14746 				if (un->un_throttle < un->un_saved_throttle) {
14747 					un->un_reset_throttle_timeid =
14748 					    timeout(sd_restore_throttle,
14749 					    un,
14750 					    SD_QFULL_THROTTLE_RESET_INTERVAL);
14751 				}
14752 			}
14753 		}
14754 
14755 		/*
14756 		 * If un_throttle has fallen below the low-water mark, we
14757 		 * restore the maximum value here (and allow it to ratchet
14758 		 * down again if necessary).
14759 		 */
14760 		if (un->un_throttle < un->un_min_throttle) {
14761 			un->un_throttle = un->un_saved_throttle;
14762 		}
14763 	} else {
14764 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: "
14765 		    "restoring limit from 0x%x to 0x%x\n",
14766 		    un->un_throttle, un->un_saved_throttle);
14767 		un->un_throttle = un->un_saved_throttle;
14768 	}
14769 
14770 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14771 	    "sd_restore_throttle: calling sd_start_cmds!\n");
14772 
14773 	sd_start_cmds(un, NULL);
14774 
14775 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un,
14776 	    "sd_restore_throttle: exit: un:0x%p un_throttle:%d\n",
14777 	    un, un->un_throttle);
14778 
14779 	mutex_exit(SD_MUTEX(un));
14780 
14781 	SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sd_restore_throttle: exit\n");
14782 }
14783 
14784 /*
14785  *    Function: sdrunout
14786  *
14787  * Description: Callback routine for scsi_init_pkt when a resource allocation
14788  *		fails.
14789  *
14790  *   Arguments: arg - a pointer to the sd_lun unit struct for the particular
14791  *		soft state instance.
14792  *
14793  * Return Code: The scsi_init_pkt routine allows for the callback function to
14794  *		return a 0 indicating the callback should be rescheduled or a 1
14795  *		indicating not to reschedule. This routine always returns 1
14796  *		because the driver always provides a callback function to
14797  *		scsi_init_pkt. This results in a callback always being scheduled
14798  *		(via the scsi_init_pkt callback implementation) if a resource
14799  *		failure occurs.
14800  *
14801  *     Context: This callback function may not block or call routines that block
14802  *
14803  *        Note: Using the scsi_init_pkt callback facility can result in an I/O
14804  *		request persisting at the head of the list which cannot be
14805  *		satisfied even after multiple retries. In the future the driver
14806  *		may implement some time of maximum runout count before failing
14807  *		an I/O.
14808  */
14809 
14810 static int
14811 sdrunout(caddr_t arg)
14812 {
14813 	struct sd_lun	*un = (struct sd_lun *)arg;
14814 
14815 	ASSERT(un != NULL);
14816 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14817 
14818 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: entry\n");
14819 
14820 	mutex_enter(SD_MUTEX(un));
14821 	sd_start_cmds(un, NULL);
14822 	mutex_exit(SD_MUTEX(un));
14823 	/*
14824 	 * This callback routine always returns 1 (i.e. do not reschedule)
14825 	 * because we always specify sdrunout as the callback handler for
14826 	 * scsi_init_pkt inside the call to sd_start_cmds.
14827 	 */
14828 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdrunout: exit\n");
14829 	return (1);
14830 }
14831 
14832 
14833 /*
14834  *    Function: sdintr
14835  *
14836  * Description: Completion callback routine for scsi_pkt(9S) structs
14837  *		sent to the HBA driver via scsi_transport(9F).
14838  *
14839  *     Context: Interrupt context
14840  */
14841 
14842 static void
14843 sdintr(struct scsi_pkt *pktp)
14844 {
14845 	struct buf	*bp;
14846 	struct sd_xbuf	*xp;
14847 	struct sd_lun	*un;
14848 	size_t		actual_len;
14849 
14850 	ASSERT(pktp != NULL);
14851 	bp = (struct buf *)pktp->pkt_private;
14852 	ASSERT(bp != NULL);
14853 	xp = SD_GET_XBUF(bp);
14854 	ASSERT(xp != NULL);
14855 	ASSERT(xp->xb_pktp != NULL);
14856 	un = SD_GET_UN(bp);
14857 	ASSERT(un != NULL);
14858 	ASSERT(!mutex_owned(SD_MUTEX(un)));
14859 
14860 #ifdef SD_FAULT_INJECTION
14861 
14862 	SD_INFO(SD_LOG_IOERR, un, "sdintr: sdintr calling Fault injection\n");
14863 	/* SD FaultInjection */
14864 	sd_faultinjection(pktp);
14865 
14866 #endif /* SD_FAULT_INJECTION */
14867 
14868 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: entry: buf:0x%p,"
14869 	    " xp:0x%p, un:0x%p\n", bp, xp, un);
14870 
14871 	mutex_enter(SD_MUTEX(un));
14872 
14873 	/* Reduce the count of the #commands currently in transport */
14874 	un->un_ncmds_in_transport--;
14875 	ASSERT(un->un_ncmds_in_transport >= 0);
14876 
14877 	/* Increment counter to indicate that the callback routine is active */
14878 	un->un_in_callback++;
14879 
14880 	SD_UPDATE_KSTATS(un, kstat_runq_exit, bp);
14881 
14882 #ifdef	SDDEBUG
14883 	if (bp == un->un_retry_bp) {
14884 		SD_TRACE(SD_LOG_IO | SD_LOG_ERROR, un, "sdintr: "
14885 		    "un:0x%p: GOT retry_bp:0x%p un_ncmds_in_transport:%d\n",
14886 		    un, un->un_retry_bp, un->un_ncmds_in_transport);
14887 	}
14888 #endif
14889 
14890 	/*
14891 	 * If pkt_reason is CMD_DEV_GONE, fail the command, and update the media
14892 	 * state if needed.
14893 	 */
14894 	if (pktp->pkt_reason == CMD_DEV_GONE) {
14895 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
14896 		    "Command failed to complete...Device is gone\n");
14897 		if (un->un_mediastate != DKIO_DEV_GONE) {
14898 			un->un_mediastate = DKIO_DEV_GONE;
14899 			cv_broadcast(&un->un_state_cv);
14900 		}
14901 		sd_return_failed_command(un, bp, EIO);
14902 		goto exit;
14903 	}
14904 
14905 	if (pktp->pkt_state & STATE_XARQ_DONE) {
14906 		SD_TRACE(SD_LOG_COMMON, un,
14907 		    "sdintr: extra sense data received. pkt=%p\n", pktp);
14908 	}
14909 
14910 	/*
14911 	 * First see if the pkt has auto-request sense data with it....
14912 	 * Look at the packet state first so we don't take a performance
14913 	 * hit looking at the arq enabled flag unless absolutely necessary.
14914 	 */
14915 	if ((pktp->pkt_state & STATE_ARQ_DONE) &&
14916 	    (un->un_f_arq_enabled == TRUE)) {
14917 		/*
14918 		 * The HBA did an auto request sense for this command so check
14919 		 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
14920 		 * driver command that should not be retried.
14921 		 */
14922 		if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
14923 			/*
14924 			 * Save the relevant sense info into the xp for the
14925 			 * original cmd.
14926 			 */
14927 			struct scsi_arq_status *asp;
14928 			asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
14929 			xp->xb_sense_status =
14930 			    *((uchar_t *)(&(asp->sts_rqpkt_status)));
14931 			xp->xb_sense_state  = asp->sts_rqpkt_state;
14932 			xp->xb_sense_resid  = asp->sts_rqpkt_resid;
14933 			if (pktp->pkt_state & STATE_XARQ_DONE) {
14934 				actual_len = MAX_SENSE_LENGTH -
14935 				    xp->xb_sense_resid;
14936 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
14937 				    MAX_SENSE_LENGTH);
14938 			} else {
14939 				if (xp->xb_sense_resid > SENSE_LENGTH) {
14940 					actual_len = MAX_SENSE_LENGTH -
14941 					    xp->xb_sense_resid;
14942 				} else {
14943 					actual_len = SENSE_LENGTH -
14944 					    xp->xb_sense_resid;
14945 				}
14946 				if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
14947 					if ((((struct uscsi_cmd *)
14948 					    (xp->xb_pktinfo))->uscsi_rqlen) >
14949 					    actual_len) {
14950 						xp->xb_sense_resid =
14951 						    (((struct uscsi_cmd *)
14952 						    (xp->xb_pktinfo))->
14953 						    uscsi_rqlen) - actual_len;
14954 					} else {
14955 						xp->xb_sense_resid = 0;
14956 					}
14957 				}
14958 				bcopy(&asp->sts_sensedata, xp->xb_sense_data,
14959 				    SENSE_LENGTH);
14960 			}
14961 
14962 			/* fail the command */
14963 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14964 			    "sdintr: arq done and FLAG_DIAGNOSE set\n");
14965 			sd_return_failed_command(un, bp, EIO);
14966 			goto exit;
14967 		}
14968 
14969 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
14970 		/*
14971 		 * We want to either retry or fail this command, so free
14972 		 * the DMA resources here.  If we retry the command then
14973 		 * the DMA resources will be reallocated in sd_start_cmds().
14974 		 * Note that when PKT_DMA_PARTIAL is used, this reallocation
14975 		 * causes the *entire* transfer to start over again from the
14976 		 * beginning of the request, even for PARTIAL chunks that
14977 		 * have already transferred successfully.
14978 		 */
14979 		if ((un->un_f_is_fibre == TRUE) &&
14980 		    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
14981 		    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
14982 			scsi_dmafree(pktp);
14983 			xp->xb_pkt_flags |= SD_XB_DMA_FREED;
14984 		}
14985 #endif
14986 
14987 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14988 		    "sdintr: arq done, sd_handle_auto_request_sense\n");
14989 
14990 		sd_handle_auto_request_sense(un, bp, xp, pktp);
14991 		goto exit;
14992 	}
14993 
14994 	/* Next see if this is the REQUEST SENSE pkt for the instance */
14995 	if (pktp->pkt_flags & FLAG_SENSING)  {
14996 		/* This pktp is from the unit's REQUEST_SENSE command */
14997 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
14998 		    "sdintr: sd_handle_request_sense\n");
14999 		sd_handle_request_sense(un, bp, xp, pktp);
15000 		goto exit;
15001 	}
15002 
15003 	/*
15004 	 * Check to see if the command successfully completed as requested;
15005 	 * this is the most common case (and also the hot performance path).
15006 	 *
15007 	 * Requirements for successful completion are:
15008 	 * pkt_reason is CMD_CMPLT and packet status is status good.
15009 	 * In addition:
15010 	 * - A residual of zero indicates successful completion no matter what
15011 	 *   the command is.
15012 	 * - If the residual is not zero and the command is not a read or
15013 	 *   write, then it's still defined as successful completion. In other
15014 	 *   words, if the command is a read or write the residual must be
15015 	 *   zero for successful completion.
15016 	 * - If the residual is not zero and the command is a read or
15017 	 *   write, and it's a USCSICMD, then it's still defined as
15018 	 *   successful completion.
15019 	 */
15020 	if ((pktp->pkt_reason == CMD_CMPLT) &&
15021 	    (SD_GET_PKT_STATUS(pktp) == STATUS_GOOD)) {
15022 
15023 		/*
15024 		 * Since this command is returned with a good status, we
15025 		 * can reset the count for Sonoma failover.
15026 		 */
15027 		un->un_sonoma_failure_count = 0;
15028 
15029 		/*
15030 		 * Return all USCSI commands on good status
15031 		 */
15032 		if (pktp->pkt_resid == 0) {
15033 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15034 			    "sdintr: returning command for resid == 0\n");
15035 		} else if (((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_READ) &&
15036 		    ((SD_GET_PKT_OPCODE(pktp) & 0x1F) != SCMD_WRITE)) {
15037 			SD_UPDATE_B_RESID(bp, pktp);
15038 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15039 			    "sdintr: returning command for resid != 0\n");
15040 		} else if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
15041 			SD_UPDATE_B_RESID(bp, pktp);
15042 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15043 			    "sdintr: returning uscsi command\n");
15044 		} else {
15045 			goto not_successful;
15046 		}
15047 		sd_return_command(un, bp);
15048 
15049 		/*
15050 		 * Decrement counter to indicate that the callback routine
15051 		 * is done.
15052 		 */
15053 		un->un_in_callback--;
15054 		ASSERT(un->un_in_callback >= 0);
15055 		mutex_exit(SD_MUTEX(un));
15056 
15057 		return;
15058 	}
15059 
15060 not_successful:
15061 
15062 #if (defined(__i386) || defined(__amd64))	/* DMAFREE for x86 only */
15063 	/*
15064 	 * The following is based upon knowledge of the underlying transport
15065 	 * and its use of DMA resources.  This code should be removed when
15066 	 * PKT_DMA_PARTIAL support is taken out of the disk driver in favor
15067 	 * of the new PKT_CMD_BREAKUP protocol. See also sd_initpkt_for_buf()
15068 	 * and sd_start_cmds().
15069 	 *
15070 	 * Free any DMA resources associated with this command if there
15071 	 * is a chance it could be retried or enqueued for later retry.
15072 	 * If we keep the DMA binding then mpxio cannot reissue the
15073 	 * command on another path whenever a path failure occurs.
15074 	 *
15075 	 * Note that when PKT_DMA_PARTIAL is used, free/reallocation
15076 	 * causes the *entire* transfer to start over again from the
15077 	 * beginning of the request, even for PARTIAL chunks that
15078 	 * have already transferred successfully.
15079 	 *
15080 	 * This is only done for non-uscsi commands (and also skipped for the
15081 	 * driver's internal RQS command). Also just do this for Fibre Channel
15082 	 * devices as these are the only ones that support mpxio.
15083 	 */
15084 	if ((un->un_f_is_fibre == TRUE) &&
15085 	    ((xp->xb_pkt_flags & SD_XB_USCSICMD) == 0) &&
15086 	    ((pktp->pkt_flags & FLAG_SENSING) == 0))  {
15087 		scsi_dmafree(pktp);
15088 		xp->xb_pkt_flags |= SD_XB_DMA_FREED;
15089 	}
15090 #endif
15091 
15092 	/*
15093 	 * The command did not successfully complete as requested so check
15094 	 * for FLAG_DIAGNOSE. If set this indicates a uscsi or internal
15095 	 * driver command that should not be retried so just return. If
15096 	 * FLAG_DIAGNOSE is not set the error will be processed below.
15097 	 */
15098 	if ((pktp->pkt_flags & FLAG_DIAGNOSE) != 0) {
15099 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15100 		    "sdintr: FLAG_DIAGNOSE: sd_return_failed_command\n");
15101 		/*
15102 		 * Issue a request sense if a check condition caused the error
15103 		 * (we handle the auto request sense case above), otherwise
15104 		 * just fail the command.
15105 		 */
15106 		if ((pktp->pkt_reason == CMD_CMPLT) &&
15107 		    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK)) {
15108 			sd_send_request_sense_command(un, bp, pktp);
15109 		} else {
15110 			sd_return_failed_command(un, bp, EIO);
15111 		}
15112 		goto exit;
15113 	}
15114 
15115 	/*
15116 	 * The command did not successfully complete as requested so process
15117 	 * the error, retry, and/or attempt recovery.
15118 	 */
15119 	switch (pktp->pkt_reason) {
15120 	case CMD_CMPLT:
15121 		switch (SD_GET_PKT_STATUS(pktp)) {
15122 		case STATUS_GOOD:
15123 			/*
15124 			 * The command completed successfully with a non-zero
15125 			 * residual
15126 			 */
15127 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15128 			    "sdintr: STATUS_GOOD \n");
15129 			sd_pkt_status_good(un, bp, xp, pktp);
15130 			break;
15131 
15132 		case STATUS_CHECK:
15133 		case STATUS_TERMINATED:
15134 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15135 			    "sdintr: STATUS_TERMINATED | STATUS_CHECK\n");
15136 			sd_pkt_status_check_condition(un, bp, xp, pktp);
15137 			break;
15138 
15139 		case STATUS_BUSY:
15140 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15141 			    "sdintr: STATUS_BUSY\n");
15142 			sd_pkt_status_busy(un, bp, xp, pktp);
15143 			break;
15144 
15145 		case STATUS_RESERVATION_CONFLICT:
15146 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15147 			    "sdintr: STATUS_RESERVATION_CONFLICT\n");
15148 			sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
15149 			break;
15150 
15151 		case STATUS_QFULL:
15152 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15153 			    "sdintr: STATUS_QFULL\n");
15154 			sd_pkt_status_qfull(un, bp, xp, pktp);
15155 			break;
15156 
15157 		case STATUS_MET:
15158 		case STATUS_INTERMEDIATE:
15159 		case STATUS_SCSI2:
15160 		case STATUS_INTERMEDIATE_MET:
15161 		case STATUS_ACA_ACTIVE:
15162 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
15163 			    "Unexpected SCSI status received: 0x%x\n",
15164 			    SD_GET_PKT_STATUS(pktp));
15165 			sd_return_failed_command(un, bp, EIO);
15166 			break;
15167 
15168 		default:
15169 			scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
15170 			    "Invalid SCSI status received: 0x%x\n",
15171 			    SD_GET_PKT_STATUS(pktp));
15172 			sd_return_failed_command(un, bp, EIO);
15173 			break;
15174 
15175 		}
15176 		break;
15177 
15178 	case CMD_INCOMPLETE:
15179 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15180 		    "sdintr:  CMD_INCOMPLETE\n");
15181 		sd_pkt_reason_cmd_incomplete(un, bp, xp, pktp);
15182 		break;
15183 	case CMD_TRAN_ERR:
15184 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15185 		    "sdintr: CMD_TRAN_ERR\n");
15186 		sd_pkt_reason_cmd_tran_err(un, bp, xp, pktp);
15187 		break;
15188 	case CMD_RESET:
15189 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15190 		    "sdintr: CMD_RESET \n");
15191 		sd_pkt_reason_cmd_reset(un, bp, xp, pktp);
15192 		break;
15193 	case CMD_ABORTED:
15194 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15195 		    "sdintr: CMD_ABORTED \n");
15196 		sd_pkt_reason_cmd_aborted(un, bp, xp, pktp);
15197 		break;
15198 	case CMD_TIMEOUT:
15199 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15200 		    "sdintr: CMD_TIMEOUT\n");
15201 		sd_pkt_reason_cmd_timeout(un, bp, xp, pktp);
15202 		break;
15203 	case CMD_UNX_BUS_FREE:
15204 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15205 		    "sdintr: CMD_UNX_BUS_FREE \n");
15206 		sd_pkt_reason_cmd_unx_bus_free(un, bp, xp, pktp);
15207 		break;
15208 	case CMD_TAG_REJECT:
15209 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15210 		    "sdintr: CMD_TAG_REJECT\n");
15211 		sd_pkt_reason_cmd_tag_reject(un, bp, xp, pktp);
15212 		break;
15213 	default:
15214 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
15215 		    "sdintr: default\n");
15216 		sd_pkt_reason_default(un, bp, xp, pktp);
15217 		break;
15218 	}
15219 
15220 exit:
15221 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sdintr: exit\n");
15222 
15223 	/* Decrement counter to indicate that the callback routine is done. */
15224 	un->un_in_callback--;
15225 	ASSERT(un->un_in_callback >= 0);
15226 
15227 	/*
15228 	 * At this point, the pkt has been dispatched, ie, it is either
15229 	 * being re-tried or has been returned to its caller and should
15230 	 * not be referenced.
15231 	 */
15232 
15233 	mutex_exit(SD_MUTEX(un));
15234 }
15235 
15236 
15237 /*
15238  *    Function: sd_print_incomplete_msg
15239  *
15240  * Description: Prints the error message for a CMD_INCOMPLETE error.
15241  *
15242  *   Arguments: un - ptr to associated softstate for the device.
15243  *		bp - ptr to the buf(9S) for the command.
15244  *		arg - message string ptr
15245  *		code - SD_DELAYED_RETRY_ISSUED, SD_IMMEDIATE_RETRY_ISSUED,
15246  *			or SD_NO_RETRY_ISSUED.
15247  *
15248  *     Context: May be called under interrupt context
15249  */
15250 
15251 static void
15252 sd_print_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
15253 {
15254 	struct scsi_pkt	*pktp;
15255 	char	*msgp;
15256 	char	*cmdp = arg;
15257 
15258 	ASSERT(un != NULL);
15259 	ASSERT(mutex_owned(SD_MUTEX(un)));
15260 	ASSERT(bp != NULL);
15261 	ASSERT(arg != NULL);
15262 	pktp = SD_GET_PKTP(bp);
15263 	ASSERT(pktp != NULL);
15264 
15265 	switch (code) {
15266 	case SD_DELAYED_RETRY_ISSUED:
15267 	case SD_IMMEDIATE_RETRY_ISSUED:
15268 		msgp = "retrying";
15269 		break;
15270 	case SD_NO_RETRY_ISSUED:
15271 	default:
15272 		msgp = "giving up";
15273 		break;
15274 	}
15275 
15276 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
15277 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15278 		    "incomplete %s- %s\n", cmdp, msgp);
15279 	}
15280 }
15281 
15282 
15283 
15284 /*
15285  *    Function: sd_pkt_status_good
15286  *
15287  * Description: Processing for a STATUS_GOOD code in pkt_status.
15288  *
15289  *     Context: May be called under interrupt context
15290  */
15291 
15292 static void
15293 sd_pkt_status_good(struct sd_lun *un, struct buf *bp,
15294 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15295 {
15296 	char	*cmdp;
15297 
15298 	ASSERT(un != NULL);
15299 	ASSERT(mutex_owned(SD_MUTEX(un)));
15300 	ASSERT(bp != NULL);
15301 	ASSERT(xp != NULL);
15302 	ASSERT(pktp != NULL);
15303 	ASSERT(pktp->pkt_reason == CMD_CMPLT);
15304 	ASSERT(SD_GET_PKT_STATUS(pktp) == STATUS_GOOD);
15305 	ASSERT(pktp->pkt_resid != 0);
15306 
15307 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: entry\n");
15308 
15309 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
15310 	switch (SD_GET_PKT_OPCODE(pktp) & 0x1F) {
15311 	case SCMD_READ:
15312 		cmdp = "read";
15313 		break;
15314 	case SCMD_WRITE:
15315 		cmdp = "write";
15316 		break;
15317 	default:
15318 		SD_UPDATE_B_RESID(bp, pktp);
15319 		sd_return_command(un, bp);
15320 		SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15321 		return;
15322 	}
15323 
15324 	/*
15325 	 * See if we can retry the read/write, preferrably immediately.
15326 	 * If retries are exhaused, then sd_retry_command() will update
15327 	 * the b_resid count.
15328 	 */
15329 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_incomplete_msg,
15330 	    cmdp, EIO, (clock_t)0, NULL);
15331 
15332 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_good: exit\n");
15333 }
15334 
15335 
15336 
15337 
15338 
15339 /*
15340  *    Function: sd_handle_request_sense
15341  *
15342  * Description: Processing for non-auto Request Sense command.
15343  *
15344  *   Arguments: un - ptr to associated softstate
15345  *		sense_bp - ptr to buf(9S) for the RQS command
15346  *		sense_xp - ptr to the sd_xbuf for the RQS command
15347  *		sense_pktp - ptr to the scsi_pkt(9S) for the RQS command
15348  *
15349  *     Context: May be called under interrupt context
15350  */
15351 
15352 static void
15353 sd_handle_request_sense(struct sd_lun *un, struct buf *sense_bp,
15354 	struct sd_xbuf *sense_xp, struct scsi_pkt *sense_pktp)
15355 {
15356 	struct buf	*cmd_bp;	/* buf for the original command */
15357 	struct sd_xbuf	*cmd_xp;	/* sd_xbuf for the original command */
15358 	struct scsi_pkt *cmd_pktp;	/* pkt for the original command */
15359 	size_t		actual_len;	/* actual sense data length */
15360 
15361 	ASSERT(un != NULL);
15362 	ASSERT(mutex_owned(SD_MUTEX(un)));
15363 	ASSERT(sense_bp != NULL);
15364 	ASSERT(sense_xp != NULL);
15365 	ASSERT(sense_pktp != NULL);
15366 
15367 	/*
15368 	 * Note the sense_bp, sense_xp, and sense_pktp here are for the
15369 	 * RQS command and not the original command.
15370 	 */
15371 	ASSERT(sense_pktp == un->un_rqs_pktp);
15372 	ASSERT(sense_bp   == un->un_rqs_bp);
15373 	ASSERT((sense_pktp->pkt_flags & (FLAG_SENSING | FLAG_HEAD)) ==
15374 	    (FLAG_SENSING | FLAG_HEAD));
15375 	ASSERT((((SD_GET_XBUF(sense_xp->xb_sense_bp))->xb_pktp->pkt_flags) &
15376 	    FLAG_SENSING) == FLAG_SENSING);
15377 
15378 	/* These are the bp, xp, and pktp for the original command */
15379 	cmd_bp = sense_xp->xb_sense_bp;
15380 	cmd_xp = SD_GET_XBUF(cmd_bp);
15381 	cmd_pktp = SD_GET_PKTP(cmd_bp);
15382 
15383 	if (sense_pktp->pkt_reason != CMD_CMPLT) {
15384 		/*
15385 		 * The REQUEST SENSE command failed.  Release the REQUEST
15386 		 * SENSE command for re-use, get back the bp for the original
15387 		 * command, and attempt to re-try the original command if
15388 		 * FLAG_DIAGNOSE is not set in the original packet.
15389 		 */
15390 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
15391 		if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15392 			cmd_bp = sd_mark_rqs_idle(un, sense_xp);
15393 			sd_retry_command(un, cmd_bp, SD_RETRIES_STANDARD,
15394 			    NULL, NULL, EIO, (clock_t)0, NULL);
15395 			return;
15396 		}
15397 	}
15398 
15399 	/*
15400 	 * Save the relevant sense info into the xp for the original cmd.
15401 	 *
15402 	 * Note: if the request sense failed the state info will be zero
15403 	 * as set in sd_mark_rqs_busy()
15404 	 */
15405 	cmd_xp->xb_sense_status = *(sense_pktp->pkt_scbp);
15406 	cmd_xp->xb_sense_state  = sense_pktp->pkt_state;
15407 	actual_len = MAX_SENSE_LENGTH - sense_pktp->pkt_resid;
15408 	if ((cmd_xp->xb_pkt_flags & SD_XB_USCSICMD) &&
15409 	    (((struct uscsi_cmd *)cmd_xp->xb_pktinfo)->uscsi_rqlen >
15410 	    SENSE_LENGTH)) {
15411 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
15412 		    MAX_SENSE_LENGTH);
15413 		cmd_xp->xb_sense_resid = sense_pktp->pkt_resid;
15414 	} else {
15415 		bcopy(sense_bp->b_un.b_addr, cmd_xp->xb_sense_data,
15416 		    SENSE_LENGTH);
15417 		if (actual_len < SENSE_LENGTH) {
15418 			cmd_xp->xb_sense_resid = SENSE_LENGTH - actual_len;
15419 		} else {
15420 			cmd_xp->xb_sense_resid = 0;
15421 		}
15422 	}
15423 
15424 	/*
15425 	 *  Free up the RQS command....
15426 	 *  NOTE:
15427 	 *	Must do this BEFORE calling sd_validate_sense_data!
15428 	 *	sd_validate_sense_data may return the original command in
15429 	 *	which case the pkt will be freed and the flags can no
15430 	 *	longer be touched.
15431 	 *	SD_MUTEX is held through this process until the command
15432 	 *	is dispatched based upon the sense data, so there are
15433 	 *	no race conditions.
15434 	 */
15435 	(void) sd_mark_rqs_idle(un, sense_xp);
15436 
15437 	/*
15438 	 * For a retryable command see if we have valid sense data, if so then
15439 	 * turn it over to sd_decode_sense() to figure out the right course of
15440 	 * action. Just fail a non-retryable command.
15441 	 */
15442 	if ((cmd_pktp->pkt_flags & FLAG_DIAGNOSE) == 0) {
15443 		if (sd_validate_sense_data(un, cmd_bp, cmd_xp, actual_len) ==
15444 		    SD_SENSE_DATA_IS_VALID) {
15445 			sd_decode_sense(un, cmd_bp, cmd_xp, cmd_pktp);
15446 		}
15447 	} else {
15448 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Failed CDB",
15449 		    (uchar_t *)cmd_pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15450 		SD_DUMP_MEMORY(un, SD_LOG_IO_CORE, "Sense Data",
15451 		    (uchar_t *)cmd_xp->xb_sense_data, SENSE_LENGTH, SD_LOG_HEX);
15452 		sd_return_failed_command(un, cmd_bp, EIO);
15453 	}
15454 }
15455 
15456 
15457 
15458 
15459 /*
15460  *    Function: sd_handle_auto_request_sense
15461  *
15462  * Description: Processing for auto-request sense information.
15463  *
15464  *   Arguments: un - ptr to associated softstate
15465  *		bp - ptr to buf(9S) for the command
15466  *		xp - ptr to the sd_xbuf for the command
15467  *		pktp - ptr to the scsi_pkt(9S) for the command
15468  *
15469  *     Context: May be called under interrupt context
15470  */
15471 
15472 static void
15473 sd_handle_auto_request_sense(struct sd_lun *un, struct buf *bp,
15474 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
15475 {
15476 	struct scsi_arq_status *asp;
15477 	size_t actual_len;
15478 
15479 	ASSERT(un != NULL);
15480 	ASSERT(mutex_owned(SD_MUTEX(un)));
15481 	ASSERT(bp != NULL);
15482 	ASSERT(xp != NULL);
15483 	ASSERT(pktp != NULL);
15484 	ASSERT(pktp != un->un_rqs_pktp);
15485 	ASSERT(bp   != un->un_rqs_bp);
15486 
15487 	/*
15488 	 * For auto-request sense, we get a scsi_arq_status back from
15489 	 * the HBA, with the sense data in the sts_sensedata member.
15490 	 * The pkt_scbp of the packet points to this scsi_arq_status.
15491 	 */
15492 	asp = (struct scsi_arq_status *)(pktp->pkt_scbp);
15493 
15494 	if (asp->sts_rqpkt_reason != CMD_CMPLT) {
15495 		/*
15496 		 * The auto REQUEST SENSE failed; see if we can re-try
15497 		 * the original command.
15498 		 */
15499 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15500 		    "auto request sense failed (reason=%s)\n",
15501 		    scsi_rname(asp->sts_rqpkt_reason));
15502 
15503 		sd_reset_target(un, pktp);
15504 
15505 		sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15506 		    NULL, NULL, EIO, (clock_t)0, NULL);
15507 		return;
15508 	}
15509 
15510 	/* Save the relevant sense info into the xp for the original cmd. */
15511 	xp->xb_sense_status = *((uchar_t *)(&(asp->sts_rqpkt_status)));
15512 	xp->xb_sense_state  = asp->sts_rqpkt_state;
15513 	xp->xb_sense_resid  = asp->sts_rqpkt_resid;
15514 	if (xp->xb_sense_state & STATE_XARQ_DONE) {
15515 		actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
15516 		bcopy(&asp->sts_sensedata, xp->xb_sense_data,
15517 		    MAX_SENSE_LENGTH);
15518 	} else {
15519 		if (xp->xb_sense_resid > SENSE_LENGTH) {
15520 			actual_len = MAX_SENSE_LENGTH - xp->xb_sense_resid;
15521 		} else {
15522 			actual_len = SENSE_LENGTH - xp->xb_sense_resid;
15523 		}
15524 		if (xp->xb_pkt_flags & SD_XB_USCSICMD) {
15525 			if ((((struct uscsi_cmd *)
15526 			    (xp->xb_pktinfo))->uscsi_rqlen) > actual_len) {
15527 				xp->xb_sense_resid = (((struct uscsi_cmd *)
15528 				    (xp->xb_pktinfo))->uscsi_rqlen) -
15529 				    actual_len;
15530 			} else {
15531 				xp->xb_sense_resid = 0;
15532 			}
15533 		}
15534 		bcopy(&asp->sts_sensedata, xp->xb_sense_data, SENSE_LENGTH);
15535 	}
15536 
15537 	/*
15538 	 * See if we have valid sense data, if so then turn it over to
15539 	 * sd_decode_sense() to figure out the right course of action.
15540 	 */
15541 	if (sd_validate_sense_data(un, bp, xp, actual_len) ==
15542 	    SD_SENSE_DATA_IS_VALID) {
15543 		sd_decode_sense(un, bp, xp, pktp);
15544 	}
15545 }
15546 
15547 
15548 /*
15549  *    Function: sd_print_sense_failed_msg
15550  *
15551  * Description: Print log message when RQS has failed.
15552  *
15553  *   Arguments: un - ptr to associated softstate
15554  *		bp - ptr to buf(9S) for the command
15555  *		arg - generic message string ptr
15556  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15557  *			or SD_NO_RETRY_ISSUED
15558  *
15559  *     Context: May be called from interrupt context
15560  */
15561 
15562 static void
15563 sd_print_sense_failed_msg(struct sd_lun *un, struct buf *bp, void *arg,
15564 	int code)
15565 {
15566 	char	*msgp = arg;
15567 
15568 	ASSERT(un != NULL);
15569 	ASSERT(mutex_owned(SD_MUTEX(un)));
15570 	ASSERT(bp != NULL);
15571 
15572 	if ((code == SD_NO_RETRY_ISSUED) && (msgp != NULL)) {
15573 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, msgp);
15574 	}
15575 }
15576 
15577 
15578 /*
15579  *    Function: sd_validate_sense_data
15580  *
15581  * Description: Check the given sense data for validity.
15582  *		If the sense data is not valid, the command will
15583  *		be either failed or retried!
15584  *
15585  * Return Code: SD_SENSE_DATA_IS_INVALID
15586  *		SD_SENSE_DATA_IS_VALID
15587  *
15588  *     Context: May be called from interrupt context
15589  */
15590 
15591 static int
15592 sd_validate_sense_data(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
15593 	size_t actual_len)
15594 {
15595 	struct scsi_extended_sense *esp;
15596 	struct	scsi_pkt *pktp;
15597 	char	*msgp = NULL;
15598 
15599 	ASSERT(un != NULL);
15600 	ASSERT(mutex_owned(SD_MUTEX(un)));
15601 	ASSERT(bp != NULL);
15602 	ASSERT(bp != un->un_rqs_bp);
15603 	ASSERT(xp != NULL);
15604 
15605 	pktp = SD_GET_PKTP(bp);
15606 	ASSERT(pktp != NULL);
15607 
15608 	/*
15609 	 * Check the status of the RQS command (auto or manual).
15610 	 */
15611 	switch (xp->xb_sense_status & STATUS_MASK) {
15612 	case STATUS_GOOD:
15613 		break;
15614 
15615 	case STATUS_RESERVATION_CONFLICT:
15616 		sd_pkt_status_reservation_conflict(un, bp, xp, pktp);
15617 		return (SD_SENSE_DATA_IS_INVALID);
15618 
15619 	case STATUS_BUSY:
15620 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15621 		    "Busy Status on REQUEST SENSE\n");
15622 		sd_retry_command(un, bp, SD_RETRIES_BUSY, NULL,
15623 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15624 		return (SD_SENSE_DATA_IS_INVALID);
15625 
15626 	case STATUS_QFULL:
15627 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
15628 		    "QFULL Status on REQUEST SENSE\n");
15629 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL,
15630 		    NULL, EIO, SD_BSY_TIMEOUT / 500, kstat_waitq_enter);
15631 		return (SD_SENSE_DATA_IS_INVALID);
15632 
15633 	case STATUS_CHECK:
15634 	case STATUS_TERMINATED:
15635 		msgp = "Check Condition on REQUEST SENSE\n";
15636 		goto sense_failed;
15637 
15638 	default:
15639 		msgp = "Not STATUS_GOOD on REQUEST_SENSE\n";
15640 		goto sense_failed;
15641 	}
15642 
15643 	/*
15644 	 * See if we got the minimum required amount of sense data.
15645 	 * Note: We are assuming the returned sense data is SENSE_LENGTH bytes
15646 	 * or less.
15647 	 */
15648 	if (((xp->xb_sense_state & STATE_XFERRED_DATA) == 0) ||
15649 	    (actual_len == 0)) {
15650 		msgp = "Request Sense couldn't get sense data\n";
15651 		goto sense_failed;
15652 	}
15653 
15654 	if (actual_len < SUN_MIN_SENSE_LENGTH) {
15655 		msgp = "Not enough sense information\n";
15656 		goto sense_failed;
15657 	}
15658 
15659 	/*
15660 	 * We require the extended sense data
15661 	 */
15662 	esp = (struct scsi_extended_sense *)xp->xb_sense_data;
15663 	if (esp->es_class != CLASS_EXTENDED_SENSE) {
15664 		if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
15665 			static char tmp[8];
15666 			static char buf[148];
15667 			char *p = (char *)(xp->xb_sense_data);
15668 			int i;
15669 
15670 			mutex_enter(&sd_sense_mutex);
15671 			(void) strcpy(buf, "undecodable sense information:");
15672 			for (i = 0; i < actual_len; i++) {
15673 				(void) sprintf(tmp, " 0x%x", *(p++)&0xff);
15674 				(void) strcpy(&buf[strlen(buf)], tmp);
15675 			}
15676 			i = strlen(buf);
15677 			(void) strcpy(&buf[i], "-(assumed fatal)\n");
15678 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, buf);
15679 			mutex_exit(&sd_sense_mutex);
15680 		}
15681 		/* Note: Legacy behavior, fail the command with no retry */
15682 		sd_return_failed_command(un, bp, EIO);
15683 		return (SD_SENSE_DATA_IS_INVALID);
15684 	}
15685 
15686 	/*
15687 	 * Check that es_code is valid (es_class concatenated with es_code
15688 	 * make up the "response code" field.  es_class will always be 7, so
15689 	 * make sure es_code is 0, 1, 2, 3 or 0xf.  es_code will indicate the
15690 	 * format.
15691 	 */
15692 	if ((esp->es_code != CODE_FMT_FIXED_CURRENT) &&
15693 	    (esp->es_code != CODE_FMT_FIXED_DEFERRED) &&
15694 	    (esp->es_code != CODE_FMT_DESCR_CURRENT) &&
15695 	    (esp->es_code != CODE_FMT_DESCR_DEFERRED) &&
15696 	    (esp->es_code != CODE_FMT_VENDOR_SPECIFIC)) {
15697 		goto sense_failed;
15698 	}
15699 
15700 	return (SD_SENSE_DATA_IS_VALID);
15701 
15702 sense_failed:
15703 	/*
15704 	 * If the request sense failed (for whatever reason), attempt
15705 	 * to retry the original command.
15706 	 */
15707 #if defined(__i386) || defined(__amd64)
15708 	/*
15709 	 * SD_RETRY_DELAY is conditionally compile (#if fibre) in
15710 	 * sddef.h for Sparc platform, and x86 uses 1 binary
15711 	 * for both SCSI/FC.
15712 	 * The SD_RETRY_DELAY value need to be adjusted here
15713 	 * when SD_RETRY_DELAY change in sddef.h
15714 	 */
15715 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15716 	    sd_print_sense_failed_msg, msgp, EIO,
15717 	    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0, NULL);
15718 #else
15719 	sd_retry_command(un, bp, SD_RETRIES_STANDARD,
15720 	    sd_print_sense_failed_msg, msgp, EIO, SD_RETRY_DELAY, NULL);
15721 #endif
15722 
15723 	return (SD_SENSE_DATA_IS_INVALID);
15724 }
15725 
15726 
15727 
15728 /*
15729  *    Function: sd_decode_sense
15730  *
15731  * Description: Take recovery action(s) when SCSI Sense Data is received.
15732  *
15733  *     Context: Interrupt context.
15734  */
15735 
15736 static void
15737 sd_decode_sense(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
15738 	struct scsi_pkt *pktp)
15739 {
15740 	uint8_t sense_key;
15741 
15742 	ASSERT(un != NULL);
15743 	ASSERT(mutex_owned(SD_MUTEX(un)));
15744 	ASSERT(bp != NULL);
15745 	ASSERT(bp != un->un_rqs_bp);
15746 	ASSERT(xp != NULL);
15747 	ASSERT(pktp != NULL);
15748 
15749 	sense_key = scsi_sense_key(xp->xb_sense_data);
15750 
15751 	switch (sense_key) {
15752 	case KEY_NO_SENSE:
15753 		sd_sense_key_no_sense(un, bp, xp, pktp);
15754 		break;
15755 	case KEY_RECOVERABLE_ERROR:
15756 		sd_sense_key_recoverable_error(un, xp->xb_sense_data,
15757 		    bp, xp, pktp);
15758 		break;
15759 	case KEY_NOT_READY:
15760 		sd_sense_key_not_ready(un, xp->xb_sense_data,
15761 		    bp, xp, pktp);
15762 		break;
15763 	case KEY_MEDIUM_ERROR:
15764 	case KEY_HARDWARE_ERROR:
15765 		sd_sense_key_medium_or_hardware_error(un,
15766 		    xp->xb_sense_data, bp, xp, pktp);
15767 		break;
15768 	case KEY_ILLEGAL_REQUEST:
15769 		sd_sense_key_illegal_request(un, bp, xp, pktp);
15770 		break;
15771 	case KEY_UNIT_ATTENTION:
15772 		sd_sense_key_unit_attention(un, xp->xb_sense_data,
15773 		    bp, xp, pktp);
15774 		break;
15775 	case KEY_WRITE_PROTECT:
15776 	case KEY_VOLUME_OVERFLOW:
15777 	case KEY_MISCOMPARE:
15778 		sd_sense_key_fail_command(un, bp, xp, pktp);
15779 		break;
15780 	case KEY_BLANK_CHECK:
15781 		sd_sense_key_blank_check(un, bp, xp, pktp);
15782 		break;
15783 	case KEY_ABORTED_COMMAND:
15784 		sd_sense_key_aborted_command(un, bp, xp, pktp);
15785 		break;
15786 	case KEY_VENDOR_UNIQUE:
15787 	case KEY_COPY_ABORTED:
15788 	case KEY_EQUAL:
15789 	case KEY_RESERVED:
15790 	default:
15791 		sd_sense_key_default(un, xp->xb_sense_data,
15792 		    bp, xp, pktp);
15793 		break;
15794 	}
15795 }
15796 
15797 
15798 /*
15799  *    Function: sd_dump_memory
15800  *
15801  * Description: Debug logging routine to print the contents of a user provided
15802  *		buffer. The output of the buffer is broken up into 256 byte
15803  *		segments due to a size constraint of the scsi_log.
15804  *		implementation.
15805  *
15806  *   Arguments: un - ptr to softstate
15807  *		comp - component mask
15808  *		title - "title" string to preceed data when printed
15809  *		data - ptr to data block to be printed
15810  *		len - size of data block to be printed
15811  *		fmt - SD_LOG_HEX (use 0x%02x format) or SD_LOG_CHAR (use %c)
15812  *
15813  *     Context: May be called from interrupt context
15814  */
15815 
15816 #define	SD_DUMP_MEMORY_BUF_SIZE	256
15817 
15818 static char *sd_dump_format_string[] = {
15819 		" 0x%02x",
15820 		" %c"
15821 };
15822 
15823 static void
15824 sd_dump_memory(struct sd_lun *un, uint_t comp, char *title, uchar_t *data,
15825     int len, int fmt)
15826 {
15827 	int	i, j;
15828 	int	avail_count;
15829 	int	start_offset;
15830 	int	end_offset;
15831 	size_t	entry_len;
15832 	char	*bufp;
15833 	char	*local_buf;
15834 	char	*format_string;
15835 
15836 	ASSERT((fmt == SD_LOG_HEX) || (fmt == SD_LOG_CHAR));
15837 
15838 	/*
15839 	 * In the debug version of the driver, this function is called from a
15840 	 * number of places which are NOPs in the release driver.
15841 	 * The debug driver therefore has additional methods of filtering
15842 	 * debug output.
15843 	 */
15844 #ifdef SDDEBUG
15845 	/*
15846 	 * In the debug version of the driver we can reduce the amount of debug
15847 	 * messages by setting sd_error_level to something other than
15848 	 * SCSI_ERR_ALL and clearing bits in sd_level_mask and
15849 	 * sd_component_mask.
15850 	 */
15851 	if (((sd_level_mask & (SD_LOGMASK_DUMP_MEM | SD_LOGMASK_DIAG)) == 0) ||
15852 	    (sd_error_level != SCSI_ERR_ALL)) {
15853 		return;
15854 	}
15855 	if (((sd_component_mask & comp) == 0) ||
15856 	    (sd_error_level != SCSI_ERR_ALL)) {
15857 		return;
15858 	}
15859 #else
15860 	if (sd_error_level != SCSI_ERR_ALL) {
15861 		return;
15862 	}
15863 #endif
15864 
15865 	local_buf = kmem_zalloc(SD_DUMP_MEMORY_BUF_SIZE, KM_SLEEP);
15866 	bufp = local_buf;
15867 	/*
15868 	 * Available length is the length of local_buf[], minus the
15869 	 * length of the title string, minus one for the ":", minus
15870 	 * one for the newline, minus one for the NULL terminator.
15871 	 * This gives the #bytes available for holding the printed
15872 	 * values from the given data buffer.
15873 	 */
15874 	if (fmt == SD_LOG_HEX) {
15875 		format_string = sd_dump_format_string[0];
15876 	} else /* SD_LOG_CHAR */ {
15877 		format_string = sd_dump_format_string[1];
15878 	}
15879 	/*
15880 	 * Available count is the number of elements from the given
15881 	 * data buffer that we can fit into the available length.
15882 	 * This is based upon the size of the format string used.
15883 	 * Make one entry and find it's size.
15884 	 */
15885 	(void) sprintf(bufp, format_string, data[0]);
15886 	entry_len = strlen(bufp);
15887 	avail_count = (SD_DUMP_MEMORY_BUF_SIZE - strlen(title) - 3) / entry_len;
15888 
15889 	j = 0;
15890 	while (j < len) {
15891 		bufp = local_buf;
15892 		bzero(bufp, SD_DUMP_MEMORY_BUF_SIZE);
15893 		start_offset = j;
15894 
15895 		end_offset = start_offset + avail_count;
15896 
15897 		(void) sprintf(bufp, "%s:", title);
15898 		bufp += strlen(bufp);
15899 		for (i = start_offset; ((i < end_offset) && (j < len));
15900 		    i++, j++) {
15901 			(void) sprintf(bufp, format_string, data[i]);
15902 			bufp += entry_len;
15903 		}
15904 		(void) sprintf(bufp, "\n");
15905 
15906 		scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE, "%s", local_buf);
15907 	}
15908 	kmem_free(local_buf, SD_DUMP_MEMORY_BUF_SIZE);
15909 }
15910 
15911 /*
15912  *    Function: sd_print_sense_msg
15913  *
15914  * Description: Log a message based upon the given sense data.
15915  *
15916  *   Arguments: un - ptr to associated softstate
15917  *		bp - ptr to buf(9S) for the command
15918  *		arg - ptr to associate sd_sense_info struct
15919  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
15920  *			or SD_NO_RETRY_ISSUED
15921  *
15922  *     Context: May be called from interrupt context
15923  */
15924 
15925 static void
15926 sd_print_sense_msg(struct sd_lun *un, struct buf *bp, void *arg, int code)
15927 {
15928 	struct sd_xbuf	*xp;
15929 	struct scsi_pkt	*pktp;
15930 	uint8_t *sensep;
15931 	daddr_t request_blkno;
15932 	diskaddr_t err_blkno;
15933 	int severity;
15934 	int pfa_flag;
15935 	extern struct scsi_key_strings scsi_cmds[];
15936 
15937 	ASSERT(un != NULL);
15938 	ASSERT(mutex_owned(SD_MUTEX(un)));
15939 	ASSERT(bp != NULL);
15940 	xp = SD_GET_XBUF(bp);
15941 	ASSERT(xp != NULL);
15942 	pktp = SD_GET_PKTP(bp);
15943 	ASSERT(pktp != NULL);
15944 	ASSERT(arg != NULL);
15945 
15946 	severity = ((struct sd_sense_info *)(arg))->ssi_severity;
15947 	pfa_flag = ((struct sd_sense_info *)(arg))->ssi_pfa_flag;
15948 
15949 	if ((code == SD_DELAYED_RETRY_ISSUED) ||
15950 	    (code == SD_IMMEDIATE_RETRY_ISSUED)) {
15951 		severity = SCSI_ERR_RETRYABLE;
15952 	}
15953 
15954 	/* Use absolute block number for the request block number */
15955 	request_blkno = xp->xb_blkno;
15956 
15957 	/*
15958 	 * Now try to get the error block number from the sense data
15959 	 */
15960 	sensep = xp->xb_sense_data;
15961 
15962 	if (scsi_sense_info_uint64(sensep, SENSE_LENGTH,
15963 	    (uint64_t *)&err_blkno)) {
15964 		/*
15965 		 * We retrieved the error block number from the information
15966 		 * portion of the sense data.
15967 		 *
15968 		 * For USCSI commands we are better off using the error
15969 		 * block no. as the requested block no. (This is the best
15970 		 * we can estimate.)
15971 		 */
15972 		if ((SD_IS_BUFIO(xp) == FALSE) &&
15973 		    ((pktp->pkt_flags & FLAG_SILENT) == 0)) {
15974 			request_blkno = err_blkno;
15975 		}
15976 	} else {
15977 		/*
15978 		 * Without the es_valid bit set (for fixed format) or an
15979 		 * information descriptor (for descriptor format) we cannot
15980 		 * be certain of the error blkno, so just use the
15981 		 * request_blkno.
15982 		 */
15983 		err_blkno = (diskaddr_t)request_blkno;
15984 	}
15985 
15986 	/*
15987 	 * The following will log the buffer contents for the release driver
15988 	 * if the SD_LOGMASK_DIAG bit of sd_level_mask is set, or the error
15989 	 * level is set to verbose.
15990 	 */
15991 	sd_dump_memory(un, SD_LOG_IO, "Failed CDB",
15992 	    (uchar_t *)pktp->pkt_cdbp, CDB_SIZE, SD_LOG_HEX);
15993 	sd_dump_memory(un, SD_LOG_IO, "Sense Data",
15994 	    (uchar_t *)sensep, SENSE_LENGTH, SD_LOG_HEX);
15995 
15996 	if (pfa_flag == FALSE) {
15997 		/* This is normally only set for USCSI */
15998 		if ((pktp->pkt_flags & FLAG_SILENT) != 0) {
15999 			return;
16000 		}
16001 
16002 		if ((SD_IS_BUFIO(xp) == TRUE) &&
16003 		    (((sd_level_mask & SD_LOGMASK_DIAG) == 0) &&
16004 		    (severity < sd_error_level))) {
16005 			return;
16006 		}
16007 	}
16008 
16009 	/*
16010 	 * Check for Sonoma Failover and keep a count of how many failed I/O's
16011 	 */
16012 	if ((SD_IS_LSI(un)) &&
16013 	    (scsi_sense_key(sensep) == KEY_ILLEGAL_REQUEST) &&
16014 	    (scsi_sense_asc(sensep) == 0x94) &&
16015 	    (scsi_sense_ascq(sensep) == 0x01)) {
16016 		un->un_sonoma_failure_count++;
16017 		if (un->un_sonoma_failure_count > 1) {
16018 			return;
16019 		}
16020 	}
16021 
16022 	scsi_vu_errmsg(SD_SCSI_DEVP(un), pktp, sd_label, severity,
16023 	    request_blkno, err_blkno, scsi_cmds,
16024 	    (struct scsi_extended_sense *)sensep,
16025 	    un->un_additional_codes, NULL);
16026 }
16027 
16028 /*
16029  *    Function: sd_sense_key_no_sense
16030  *
16031  * Description: Recovery action when sense data was not received.
16032  *
16033  *     Context: May be called from interrupt context
16034  */
16035 
16036 static void
16037 sd_sense_key_no_sense(struct sd_lun *un, struct buf *bp,
16038 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16039 {
16040 	struct sd_sense_info	si;
16041 
16042 	ASSERT(un != NULL);
16043 	ASSERT(mutex_owned(SD_MUTEX(un)));
16044 	ASSERT(bp != NULL);
16045 	ASSERT(xp != NULL);
16046 	ASSERT(pktp != NULL);
16047 
16048 	si.ssi_severity = SCSI_ERR_FATAL;
16049 	si.ssi_pfa_flag = FALSE;
16050 
16051 	SD_UPDATE_ERRSTATS(un, sd_softerrs);
16052 
16053 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16054 	    &si, EIO, (clock_t)0, NULL);
16055 }
16056 
16057 
16058 /*
16059  *    Function: sd_sense_key_recoverable_error
16060  *
16061  * Description: Recovery actions for a SCSI "Recovered Error" sense key.
16062  *
16063  *     Context: May be called from interrupt context
16064  */
16065 
16066 static void
16067 sd_sense_key_recoverable_error(struct sd_lun *un,
16068 	uint8_t *sense_datap,
16069 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16070 {
16071 	struct sd_sense_info	si;
16072 	uint8_t asc = scsi_sense_asc(sense_datap);
16073 
16074 	ASSERT(un != NULL);
16075 	ASSERT(mutex_owned(SD_MUTEX(un)));
16076 	ASSERT(bp != NULL);
16077 	ASSERT(xp != NULL);
16078 	ASSERT(pktp != NULL);
16079 
16080 	/*
16081 	 * 0x5D: FAILURE PREDICTION THRESHOLD EXCEEDED
16082 	 */
16083 	if ((asc == 0x5D) && (sd_report_pfa != 0)) {
16084 		SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
16085 		si.ssi_severity = SCSI_ERR_INFO;
16086 		si.ssi_pfa_flag = TRUE;
16087 	} else {
16088 		SD_UPDATE_ERRSTATS(un, sd_softerrs);
16089 		SD_UPDATE_ERRSTATS(un, sd_rq_recov_err);
16090 		si.ssi_severity = SCSI_ERR_RECOVERED;
16091 		si.ssi_pfa_flag = FALSE;
16092 	}
16093 
16094 	if (pktp->pkt_resid == 0) {
16095 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16096 		sd_return_command(un, bp);
16097 		return;
16098 	}
16099 
16100 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16101 	    &si, EIO, (clock_t)0, NULL);
16102 }
16103 
16104 
16105 
16106 
16107 /*
16108  *    Function: sd_sense_key_not_ready
16109  *
16110  * Description: Recovery actions for a SCSI "Not Ready" sense key.
16111  *
16112  *     Context: May be called from interrupt context
16113  */
16114 
16115 static void
16116 sd_sense_key_not_ready(struct sd_lun *un,
16117 	uint8_t *sense_datap,
16118 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16119 {
16120 	struct sd_sense_info	si;
16121 	uint8_t asc = scsi_sense_asc(sense_datap);
16122 	uint8_t ascq = scsi_sense_ascq(sense_datap);
16123 
16124 	ASSERT(un != NULL);
16125 	ASSERT(mutex_owned(SD_MUTEX(un)));
16126 	ASSERT(bp != NULL);
16127 	ASSERT(xp != NULL);
16128 	ASSERT(pktp != NULL);
16129 
16130 	si.ssi_severity = SCSI_ERR_FATAL;
16131 	si.ssi_pfa_flag = FALSE;
16132 
16133 	/*
16134 	 * Update error stats after first NOT READY error. Disks may have
16135 	 * been powered down and may need to be restarted.  For CDROMs,
16136 	 * report NOT READY errors only if media is present.
16137 	 */
16138 	if ((ISCD(un) && (asc == 0x3A)) ||
16139 	    (xp->xb_nr_retry_count > 0)) {
16140 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16141 		SD_UPDATE_ERRSTATS(un, sd_rq_ntrdy_err);
16142 	}
16143 
16144 	/*
16145 	 * Just fail if the "not ready" retry limit has been reached.
16146 	 */
16147 	if (xp->xb_nr_retry_count >= un->un_notready_retry_count) {
16148 		/* Special check for error message printing for removables. */
16149 		if (un->un_f_has_removable_media && (asc == 0x04) &&
16150 		    (ascq >= 0x04)) {
16151 			si.ssi_severity = SCSI_ERR_ALL;
16152 		}
16153 		goto fail_command;
16154 	}
16155 
16156 	/*
16157 	 * Check the ASC and ASCQ in the sense data as needed, to determine
16158 	 * what to do.
16159 	 */
16160 	switch (asc) {
16161 	case 0x04:	/* LOGICAL UNIT NOT READY */
16162 		/*
16163 		 * disk drives that don't spin up result in a very long delay
16164 		 * in format without warning messages. We will log a message
16165 		 * if the error level is set to verbose.
16166 		 */
16167 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16168 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16169 			    "logical unit not ready, resetting disk\n");
16170 		}
16171 
16172 		/*
16173 		 * There are different requirements for CDROMs and disks for
16174 		 * the number of retries.  If a CD-ROM is giving this, it is
16175 		 * probably reading TOC and is in the process of getting
16176 		 * ready, so we should keep on trying for a long time to make
16177 		 * sure that all types of media are taken in account (for
16178 		 * some media the drive takes a long time to read TOC).  For
16179 		 * disks we do not want to retry this too many times as this
16180 		 * can cause a long hang in format when the drive refuses to
16181 		 * spin up (a very common failure).
16182 		 */
16183 		switch (ascq) {
16184 		case 0x00:  /* LUN NOT READY, CAUSE NOT REPORTABLE */
16185 			/*
16186 			 * Disk drives frequently refuse to spin up which
16187 			 * results in a very long hang in format without
16188 			 * warning messages.
16189 			 *
16190 			 * Note: This code preserves the legacy behavior of
16191 			 * comparing xb_nr_retry_count against zero for fibre
16192 			 * channel targets instead of comparing against the
16193 			 * un_reset_retry_count value.  The reason for this
16194 			 * discrepancy has been so utterly lost beneath the
16195 			 * Sands of Time that even Indiana Jones could not
16196 			 * find it.
16197 			 */
16198 			if (un->un_f_is_fibre == TRUE) {
16199 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
16200 				    (xp->xb_nr_retry_count > 0)) &&
16201 				    (un->un_startstop_timeid == NULL)) {
16202 					scsi_log(SD_DEVINFO(un), sd_label,
16203 					    CE_WARN, "logical unit not ready, "
16204 					    "resetting disk\n");
16205 					sd_reset_target(un, pktp);
16206 				}
16207 			} else {
16208 				if (((sd_level_mask & SD_LOGMASK_DIAG) ||
16209 				    (xp->xb_nr_retry_count >
16210 				    un->un_reset_retry_count)) &&
16211 				    (un->un_startstop_timeid == NULL)) {
16212 					scsi_log(SD_DEVINFO(un), sd_label,
16213 					    CE_WARN, "logical unit not ready, "
16214 					    "resetting disk\n");
16215 					sd_reset_target(un, pktp);
16216 				}
16217 			}
16218 			break;
16219 
16220 		case 0x01:  /* LUN IS IN PROCESS OF BECOMING READY */
16221 			/*
16222 			 * If the target is in the process of becoming
16223 			 * ready, just proceed with the retry. This can
16224 			 * happen with CD-ROMs that take a long time to
16225 			 * read TOC after a power cycle or reset.
16226 			 */
16227 			goto do_retry;
16228 
16229 		case 0x02:  /* LUN NOT READY, INITITIALIZING CMD REQUIRED */
16230 			break;
16231 
16232 		case 0x03:  /* LUN NOT READY, MANUAL INTERVENTION REQUIRED */
16233 			/*
16234 			 * Retries cannot help here so just fail right away.
16235 			 */
16236 			goto fail_command;
16237 
16238 		case 0x88:
16239 			/*
16240 			 * Vendor-unique code for T3/T4: it indicates a
16241 			 * path problem in a mutipathed config, but as far as
16242 			 * the target driver is concerned it equates to a fatal
16243 			 * error, so we should just fail the command right away
16244 			 * (without printing anything to the console). If this
16245 			 * is not a T3/T4, fall thru to the default recovery
16246 			 * action.
16247 			 * T3/T4 is FC only, don't need to check is_fibre
16248 			 */
16249 			if (SD_IS_T3(un) || SD_IS_T4(un)) {
16250 				sd_return_failed_command(un, bp, EIO);
16251 				return;
16252 			}
16253 			/* FALLTHRU */
16254 
16255 		case 0x04:  /* LUN NOT READY, FORMAT IN PROGRESS */
16256 		case 0x05:  /* LUN NOT READY, REBUILD IN PROGRESS */
16257 		case 0x06:  /* LUN NOT READY, RECALCULATION IN PROGRESS */
16258 		case 0x07:  /* LUN NOT READY, OPERATION IN PROGRESS */
16259 		case 0x08:  /* LUN NOT READY, LONG WRITE IN PROGRESS */
16260 		default:    /* Possible future codes in SCSI spec? */
16261 			/*
16262 			 * For removable-media devices, do not retry if
16263 			 * ASCQ > 2 as these result mostly from USCSI commands
16264 			 * on MMC devices issued to check status of an
16265 			 * operation initiated in immediate mode.  Also for
16266 			 * ASCQ >= 4 do not print console messages as these
16267 			 * mainly represent a user-initiated operation
16268 			 * instead of a system failure.
16269 			 */
16270 			if (un->un_f_has_removable_media) {
16271 				si.ssi_severity = SCSI_ERR_ALL;
16272 				goto fail_command;
16273 			}
16274 			break;
16275 		}
16276 
16277 		/*
16278 		 * As part of our recovery attempt for the NOT READY
16279 		 * condition, we issue a START STOP UNIT command. However
16280 		 * we want to wait for a short delay before attempting this
16281 		 * as there may still be more commands coming back from the
16282 		 * target with the check condition. To do this we use
16283 		 * timeout(9F) to call sd_start_stop_unit_callback() after
16284 		 * the delay interval expires. (sd_start_stop_unit_callback()
16285 		 * dispatches sd_start_stop_unit_task(), which will issue
16286 		 * the actual START STOP UNIT command. The delay interval
16287 		 * is one-half of the delay that we will use to retry the
16288 		 * command that generated the NOT READY condition.
16289 		 *
16290 		 * Note that we could just dispatch sd_start_stop_unit_task()
16291 		 * from here and allow it to sleep for the delay interval,
16292 		 * but then we would be tying up the taskq thread
16293 		 * uncesessarily for the duration of the delay.
16294 		 *
16295 		 * Do not issue the START STOP UNIT if the current command
16296 		 * is already a START STOP UNIT.
16297 		 */
16298 		if (pktp->pkt_cdbp[0] == SCMD_START_STOP) {
16299 			break;
16300 		}
16301 
16302 		/*
16303 		 * Do not schedule the timeout if one is already pending.
16304 		 */
16305 		if (un->un_startstop_timeid != NULL) {
16306 			SD_INFO(SD_LOG_ERROR, un,
16307 			    "sd_sense_key_not_ready: restart already issued to"
16308 			    " %s%d\n", ddi_driver_name(SD_DEVINFO(un)),
16309 			    ddi_get_instance(SD_DEVINFO(un)));
16310 			break;
16311 		}
16312 
16313 		/*
16314 		 * Schedule the START STOP UNIT command, then queue the command
16315 		 * for a retry.
16316 		 *
16317 		 * Note: A timeout is not scheduled for this retry because we
16318 		 * want the retry to be serial with the START_STOP_UNIT. The
16319 		 * retry will be started when the START_STOP_UNIT is completed
16320 		 * in sd_start_stop_unit_task.
16321 		 */
16322 		un->un_startstop_timeid = timeout(sd_start_stop_unit_callback,
16323 		    un, SD_BSY_TIMEOUT / 2);
16324 		xp->xb_nr_retry_count++;
16325 		sd_set_retry_bp(un, bp, 0, kstat_waitq_enter);
16326 		return;
16327 
16328 	case 0x05:	/* LOGICAL UNIT DOES NOT RESPOND TO SELECTION */
16329 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16330 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16331 			    "unit does not respond to selection\n");
16332 		}
16333 		break;
16334 
16335 	case 0x3A:	/* MEDIUM NOT PRESENT */
16336 		if (sd_error_level >= SCSI_ERR_FATAL) {
16337 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16338 			    "Caddy not inserted in drive\n");
16339 		}
16340 
16341 		sr_ejected(un);
16342 		un->un_mediastate = DKIO_EJECTED;
16343 		/* The state has changed, inform the media watch routines */
16344 		cv_broadcast(&un->un_state_cv);
16345 		/* Just fail if no media is present in the drive. */
16346 		goto fail_command;
16347 
16348 	default:
16349 		if (sd_error_level < SCSI_ERR_RETRYABLE) {
16350 			scsi_log(SD_DEVINFO(un), sd_label, CE_NOTE,
16351 			    "Unit not Ready. Additional sense code 0x%x\n",
16352 			    asc);
16353 		}
16354 		break;
16355 	}
16356 
16357 do_retry:
16358 
16359 	/*
16360 	 * Retry the command, as some targets may report NOT READY for
16361 	 * several seconds after being reset.
16362 	 */
16363 	xp->xb_nr_retry_count++;
16364 	si.ssi_severity = SCSI_ERR_RETRYABLE;
16365 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
16366 	    &si, EIO, SD_BSY_TIMEOUT, NULL);
16367 
16368 	return;
16369 
16370 fail_command:
16371 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16372 	sd_return_failed_command(un, bp, EIO);
16373 }
16374 
16375 
16376 
16377 /*
16378  *    Function: sd_sense_key_medium_or_hardware_error
16379  *
16380  * Description: Recovery actions for a SCSI "Medium Error" or "Hardware Error"
16381  *		sense key.
16382  *
16383  *     Context: May be called from interrupt context
16384  */
16385 
16386 static void
16387 sd_sense_key_medium_or_hardware_error(struct sd_lun *un,
16388 	uint8_t *sense_datap,
16389 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16390 {
16391 	struct sd_sense_info	si;
16392 	uint8_t sense_key = scsi_sense_key(sense_datap);
16393 	uint8_t asc = scsi_sense_asc(sense_datap);
16394 
16395 	ASSERT(un != NULL);
16396 	ASSERT(mutex_owned(SD_MUTEX(un)));
16397 	ASSERT(bp != NULL);
16398 	ASSERT(xp != NULL);
16399 	ASSERT(pktp != NULL);
16400 
16401 	si.ssi_severity = SCSI_ERR_FATAL;
16402 	si.ssi_pfa_flag = FALSE;
16403 
16404 	if (sense_key == KEY_MEDIUM_ERROR) {
16405 		SD_UPDATE_ERRSTATS(un, sd_rq_media_err);
16406 	}
16407 
16408 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16409 
16410 	if ((un->un_reset_retry_count != 0) &&
16411 	    (xp->xb_retry_count == un->un_reset_retry_count)) {
16412 		mutex_exit(SD_MUTEX(un));
16413 		/* Do NOT do a RESET_ALL here: too intrusive. (4112858) */
16414 		if (un->un_f_allow_bus_device_reset == TRUE) {
16415 
16416 			boolean_t try_resetting_target = B_TRUE;
16417 
16418 			/*
16419 			 * We need to be able to handle specific ASC when we are
16420 			 * handling a KEY_HARDWARE_ERROR. In particular
16421 			 * taking the default action of resetting the target may
16422 			 * not be the appropriate way to attempt recovery.
16423 			 * Resetting a target because of a single LUN failure
16424 			 * victimizes all LUNs on that target.
16425 			 *
16426 			 * This is true for the LSI arrays, if an LSI
16427 			 * array controller returns an ASC of 0x84 (LUN Dead) we
16428 			 * should trust it.
16429 			 */
16430 
16431 			if (sense_key == KEY_HARDWARE_ERROR) {
16432 				switch (asc) {
16433 				case 0x84:
16434 					if (SD_IS_LSI(un)) {
16435 						try_resetting_target = B_FALSE;
16436 					}
16437 					break;
16438 				default:
16439 					break;
16440 				}
16441 			}
16442 
16443 			if (try_resetting_target == B_TRUE) {
16444 				int reset_retval = 0;
16445 				if (un->un_f_lun_reset_enabled == TRUE) {
16446 					SD_TRACE(SD_LOG_IO_CORE, un,
16447 					    "sd_sense_key_medium_or_hardware_"
16448 					    "error: issuing RESET_LUN\n");
16449 					reset_retval =
16450 					    scsi_reset(SD_ADDRESS(un),
16451 					    RESET_LUN);
16452 				}
16453 				if (reset_retval == 0) {
16454 					SD_TRACE(SD_LOG_IO_CORE, un,
16455 					    "sd_sense_key_medium_or_hardware_"
16456 					    "error: issuing RESET_TARGET\n");
16457 					(void) scsi_reset(SD_ADDRESS(un),
16458 					    RESET_TARGET);
16459 				}
16460 			}
16461 		}
16462 		mutex_enter(SD_MUTEX(un));
16463 	}
16464 
16465 	/*
16466 	 * This really ought to be a fatal error, but we will retry anyway
16467 	 * as some drives report this as a spurious error.
16468 	 */
16469 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16470 	    &si, EIO, (clock_t)0, NULL);
16471 }
16472 
16473 
16474 
16475 /*
16476  *    Function: sd_sense_key_illegal_request
16477  *
16478  * Description: Recovery actions for a SCSI "Illegal Request" sense key.
16479  *
16480  *     Context: May be called from interrupt context
16481  */
16482 
16483 static void
16484 sd_sense_key_illegal_request(struct sd_lun *un, struct buf *bp,
16485 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16486 {
16487 	struct sd_sense_info	si;
16488 
16489 	ASSERT(un != NULL);
16490 	ASSERT(mutex_owned(SD_MUTEX(un)));
16491 	ASSERT(bp != NULL);
16492 	ASSERT(xp != NULL);
16493 	ASSERT(pktp != NULL);
16494 
16495 	SD_UPDATE_ERRSTATS(un, sd_rq_illrq_err);
16496 
16497 	si.ssi_severity = SCSI_ERR_INFO;
16498 	si.ssi_pfa_flag = FALSE;
16499 
16500 	/* Pointless to retry if the target thinks it's an illegal request */
16501 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16502 	sd_return_failed_command(un, bp, EIO);
16503 }
16504 
16505 
16506 
16507 
16508 /*
16509  *    Function: sd_sense_key_unit_attention
16510  *
16511  * Description: Recovery actions for a SCSI "Unit Attention" sense key.
16512  *
16513  *     Context: May be called from interrupt context
16514  */
16515 
16516 static void
16517 sd_sense_key_unit_attention(struct sd_lun *un,
16518 	uint8_t *sense_datap,
16519 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16520 {
16521 	/*
16522 	 * For UNIT ATTENTION we allow retries for one minute. Devices
16523 	 * like Sonoma can return UNIT ATTENTION close to a minute
16524 	 * under certain conditions.
16525 	 */
16526 	int	retry_check_flag = SD_RETRIES_UA;
16527 	boolean_t	kstat_updated = B_FALSE;
16528 	struct	sd_sense_info		si;
16529 	uint8_t asc = scsi_sense_asc(sense_datap);
16530 	uint8_t	ascq = scsi_sense_ascq(sense_datap);
16531 
16532 	ASSERT(un != NULL);
16533 	ASSERT(mutex_owned(SD_MUTEX(un)));
16534 	ASSERT(bp != NULL);
16535 	ASSERT(xp != NULL);
16536 	ASSERT(pktp != NULL);
16537 
16538 	si.ssi_severity = SCSI_ERR_INFO;
16539 	si.ssi_pfa_flag = FALSE;
16540 
16541 
16542 	switch (asc) {
16543 	case 0x5D:  /* FAILURE PREDICTION THRESHOLD EXCEEDED */
16544 		if (sd_report_pfa != 0) {
16545 			SD_UPDATE_ERRSTATS(un, sd_rq_pfa_err);
16546 			si.ssi_pfa_flag = TRUE;
16547 			retry_check_flag = SD_RETRIES_STANDARD;
16548 			goto do_retry;
16549 		}
16550 
16551 		break;
16552 
16553 	case 0x29:  /* POWER ON, RESET, OR BUS DEVICE RESET OCCURRED */
16554 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
16555 			un->un_resvd_status |=
16556 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
16557 		}
16558 #ifdef _LP64
16559 		if (un->un_blockcount + 1 > SD_GROUP1_MAX_ADDRESS) {
16560 			if (taskq_dispatch(sd_tq, sd_reenable_dsense_task,
16561 			    un, KM_NOSLEEP) == 0) {
16562 				/*
16563 				 * If we can't dispatch the task we'll just
16564 				 * live without descriptor sense.  We can
16565 				 * try again on the next "unit attention"
16566 				 */
16567 				SD_ERROR(SD_LOG_ERROR, un,
16568 				    "sd_sense_key_unit_attention: "
16569 				    "Could not dispatch "
16570 				    "sd_reenable_dsense_task\n");
16571 			}
16572 		}
16573 #endif /* _LP64 */
16574 		/* FALLTHRU */
16575 
16576 	case 0x28: /* NOT READY TO READY CHANGE, MEDIUM MAY HAVE CHANGED */
16577 		if (!un->un_f_has_removable_media) {
16578 			break;
16579 		}
16580 
16581 		/*
16582 		 * When we get a unit attention from a removable-media device,
16583 		 * it may be in a state that will take a long time to recover
16584 		 * (e.g., from a reset).  Since we are executing in interrupt
16585 		 * context here, we cannot wait around for the device to come
16586 		 * back. So hand this command off to sd_media_change_task()
16587 		 * for deferred processing under taskq thread context. (Note
16588 		 * that the command still may be failed if a problem is
16589 		 * encountered at a later time.)
16590 		 */
16591 		if (taskq_dispatch(sd_tq, sd_media_change_task, pktp,
16592 		    KM_NOSLEEP) == 0) {
16593 			/*
16594 			 * Cannot dispatch the request so fail the command.
16595 			 */
16596 			SD_UPDATE_ERRSTATS(un, sd_harderrs);
16597 			SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16598 			si.ssi_severity = SCSI_ERR_FATAL;
16599 			sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16600 			sd_return_failed_command(un, bp, EIO);
16601 		}
16602 
16603 		/*
16604 		 * If failed to dispatch sd_media_change_task(), we already
16605 		 * updated kstat. If succeed to dispatch sd_media_change_task(),
16606 		 * we should update kstat later if it encounters an error. So,
16607 		 * we update kstat_updated flag here.
16608 		 */
16609 		kstat_updated = B_TRUE;
16610 
16611 		/*
16612 		 * Either the command has been successfully dispatched to a
16613 		 * task Q for retrying, or the dispatch failed. In either case
16614 		 * do NOT retry again by calling sd_retry_command. This sets up
16615 		 * two retries of the same command and when one completes and
16616 		 * frees the resources the other will access freed memory,
16617 		 * a bad thing.
16618 		 */
16619 		return;
16620 
16621 	default:
16622 		break;
16623 	}
16624 
16625 	/*
16626 	 * ASC  ASCQ
16627 	 *  2A   09	Capacity data has changed
16628 	 *  2A   01	Mode parameters changed
16629 	 *  3F   0E	Reported luns data has changed
16630 	 * Arrays that support logical unit expansion should report
16631 	 * capacity changes(2Ah/09). Mode parameters changed and
16632 	 * reported luns data has changed are the approximation.
16633 	 */
16634 	if (((asc == 0x2a) && (ascq == 0x09)) ||
16635 	    ((asc == 0x2a) && (ascq == 0x01)) ||
16636 	    ((asc == 0x3f) && (ascq == 0x0e))) {
16637 		if (taskq_dispatch(sd_tq, sd_target_change_task, un,
16638 		    KM_NOSLEEP) == 0) {
16639 			SD_ERROR(SD_LOG_ERROR, un,
16640 			    "sd_sense_key_unit_attention: "
16641 			    "Could not dispatch sd_target_change_task\n");
16642 		}
16643 	}
16644 
16645 	/*
16646 	 * Update kstat if we haven't done that.
16647 	 */
16648 	if (!kstat_updated) {
16649 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
16650 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
16651 	}
16652 
16653 do_retry:
16654 	sd_retry_command(un, bp, retry_check_flag, sd_print_sense_msg, &si,
16655 	    EIO, SD_UA_RETRY_DELAY, NULL);
16656 }
16657 
16658 
16659 
16660 /*
16661  *    Function: sd_sense_key_fail_command
16662  *
16663  * Description: Use to fail a command when we don't like the sense key that
16664  *		was returned.
16665  *
16666  *     Context: May be called from interrupt context
16667  */
16668 
16669 static void
16670 sd_sense_key_fail_command(struct sd_lun *un, struct buf *bp,
16671 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16672 {
16673 	struct sd_sense_info	si;
16674 
16675 	ASSERT(un != NULL);
16676 	ASSERT(mutex_owned(SD_MUTEX(un)));
16677 	ASSERT(bp != NULL);
16678 	ASSERT(xp != NULL);
16679 	ASSERT(pktp != NULL);
16680 
16681 	si.ssi_severity = SCSI_ERR_FATAL;
16682 	si.ssi_pfa_flag = FALSE;
16683 
16684 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16685 	sd_return_failed_command(un, bp, EIO);
16686 }
16687 
16688 
16689 
16690 /*
16691  *    Function: sd_sense_key_blank_check
16692  *
16693  * Description: Recovery actions for a SCSI "Blank Check" sense key.
16694  *		Has no monetary connotation.
16695  *
16696  *     Context: May be called from interrupt context
16697  */
16698 
16699 static void
16700 sd_sense_key_blank_check(struct sd_lun *un, struct buf *bp,
16701 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16702 {
16703 	struct sd_sense_info	si;
16704 
16705 	ASSERT(un != NULL);
16706 	ASSERT(mutex_owned(SD_MUTEX(un)));
16707 	ASSERT(bp != NULL);
16708 	ASSERT(xp != NULL);
16709 	ASSERT(pktp != NULL);
16710 
16711 	/*
16712 	 * Blank check is not fatal for removable devices, therefore
16713 	 * it does not require a console message.
16714 	 */
16715 	si.ssi_severity = (un->un_f_has_removable_media) ? SCSI_ERR_ALL :
16716 	    SCSI_ERR_FATAL;
16717 	si.ssi_pfa_flag = FALSE;
16718 
16719 	sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
16720 	sd_return_failed_command(un, bp, EIO);
16721 }
16722 
16723 
16724 
16725 
16726 /*
16727  *    Function: sd_sense_key_aborted_command
16728  *
16729  * Description: Recovery actions for a SCSI "Aborted Command" sense key.
16730  *
16731  *     Context: May be called from interrupt context
16732  */
16733 
16734 static void
16735 sd_sense_key_aborted_command(struct sd_lun *un, struct buf *bp,
16736 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16737 {
16738 	struct sd_sense_info	si;
16739 
16740 	ASSERT(un != NULL);
16741 	ASSERT(mutex_owned(SD_MUTEX(un)));
16742 	ASSERT(bp != NULL);
16743 	ASSERT(xp != NULL);
16744 	ASSERT(pktp != NULL);
16745 
16746 	si.ssi_severity = SCSI_ERR_FATAL;
16747 	si.ssi_pfa_flag = FALSE;
16748 
16749 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16750 
16751 	/*
16752 	 * This really ought to be a fatal error, but we will retry anyway
16753 	 * as some drives report this as a spurious error.
16754 	 */
16755 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16756 	    &si, EIO, drv_usectohz(100000), NULL);
16757 }
16758 
16759 
16760 
16761 /*
16762  *    Function: sd_sense_key_default
16763  *
16764  * Description: Default recovery action for several SCSI sense keys (basically
16765  *		attempts a retry).
16766  *
16767  *     Context: May be called from interrupt context
16768  */
16769 
16770 static void
16771 sd_sense_key_default(struct sd_lun *un,
16772 	uint8_t *sense_datap,
16773 	struct buf *bp, struct sd_xbuf *xp, struct scsi_pkt *pktp)
16774 {
16775 	struct sd_sense_info	si;
16776 	uint8_t sense_key = scsi_sense_key(sense_datap);
16777 
16778 	ASSERT(un != NULL);
16779 	ASSERT(mutex_owned(SD_MUTEX(un)));
16780 	ASSERT(bp != NULL);
16781 	ASSERT(xp != NULL);
16782 	ASSERT(pktp != NULL);
16783 
16784 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
16785 
16786 	/*
16787 	 * Undecoded sense key.	Attempt retries and hope that will fix
16788 	 * the problem.  Otherwise, we're dead.
16789 	 */
16790 	if ((pktp->pkt_flags & FLAG_SILENT) == 0) {
16791 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16792 		    "Unhandled Sense Key '%s'\n", sense_keys[sense_key]);
16793 	}
16794 
16795 	si.ssi_severity = SCSI_ERR_FATAL;
16796 	si.ssi_pfa_flag = FALSE;
16797 
16798 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, sd_print_sense_msg,
16799 	    &si, EIO, (clock_t)0, NULL);
16800 }
16801 
16802 
16803 
16804 /*
16805  *    Function: sd_print_retry_msg
16806  *
16807  * Description: Print a message indicating the retry action being taken.
16808  *
16809  *   Arguments: un - ptr to associated softstate
16810  *		bp - ptr to buf(9S) for the command
16811  *		arg - not used.
16812  *		flag - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16813  *			or SD_NO_RETRY_ISSUED
16814  *
16815  *     Context: May be called from interrupt context
16816  */
16817 /* ARGSUSED */
16818 static void
16819 sd_print_retry_msg(struct sd_lun *un, struct buf *bp, void *arg, int flag)
16820 {
16821 	struct sd_xbuf	*xp;
16822 	struct scsi_pkt *pktp;
16823 	char *reasonp;
16824 	char *msgp;
16825 
16826 	ASSERT(un != NULL);
16827 	ASSERT(mutex_owned(SD_MUTEX(un)));
16828 	ASSERT(bp != NULL);
16829 	pktp = SD_GET_PKTP(bp);
16830 	ASSERT(pktp != NULL);
16831 	xp = SD_GET_XBUF(bp);
16832 	ASSERT(xp != NULL);
16833 
16834 	ASSERT(!mutex_owned(&un->un_pm_mutex));
16835 	mutex_enter(&un->un_pm_mutex);
16836 	if ((un->un_state == SD_STATE_SUSPENDED) ||
16837 	    (SD_DEVICE_IS_IN_LOW_POWER(un)) ||
16838 	    (pktp->pkt_flags & FLAG_SILENT)) {
16839 		mutex_exit(&un->un_pm_mutex);
16840 		goto update_pkt_reason;
16841 	}
16842 	mutex_exit(&un->un_pm_mutex);
16843 
16844 	/*
16845 	 * Suppress messages if they are all the same pkt_reason; with
16846 	 * TQ, many (up to 256) are returned with the same pkt_reason.
16847 	 * If we are in panic, then suppress the retry messages.
16848 	 */
16849 	switch (flag) {
16850 	case SD_NO_RETRY_ISSUED:
16851 		msgp = "giving up";
16852 		break;
16853 	case SD_IMMEDIATE_RETRY_ISSUED:
16854 	case SD_DELAYED_RETRY_ISSUED:
16855 		if (ddi_in_panic() || (un->un_state == SD_STATE_OFFLINE) ||
16856 		    ((pktp->pkt_reason == un->un_last_pkt_reason) &&
16857 		    (sd_error_level != SCSI_ERR_ALL))) {
16858 			return;
16859 		}
16860 		msgp = "retrying command";
16861 		break;
16862 	default:
16863 		goto update_pkt_reason;
16864 	}
16865 
16866 	reasonp = (((pktp->pkt_statistics & STAT_PERR) != 0) ? "parity error" :
16867 	    scsi_rname(pktp->pkt_reason));
16868 
16869 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16870 	    "SCSI transport failed: reason '%s': %s\n", reasonp, msgp);
16871 
16872 update_pkt_reason:
16873 	/*
16874 	 * Update un->un_last_pkt_reason with the value in pktp->pkt_reason.
16875 	 * This is to prevent multiple console messages for the same failure
16876 	 * condition.  Note that un->un_last_pkt_reason is NOT restored if &
16877 	 * when the command is retried successfully because there still may be
16878 	 * more commands coming back with the same value of pktp->pkt_reason.
16879 	 */
16880 	if ((pktp->pkt_reason != CMD_CMPLT) || (xp->xb_retry_count == 0)) {
16881 		un->un_last_pkt_reason = pktp->pkt_reason;
16882 	}
16883 }
16884 
16885 
16886 /*
16887  *    Function: sd_print_cmd_incomplete_msg
16888  *
16889  * Description: Message logging fn. for a SCSA "CMD_INCOMPLETE" pkt_reason.
16890  *
16891  *   Arguments: un - ptr to associated softstate
16892  *		bp - ptr to buf(9S) for the command
16893  *		arg - passed to sd_print_retry_msg()
16894  *		code - SD_IMMEDIATE_RETRY_ISSUED, SD_DELAYED_RETRY_ISSUED,
16895  *			or SD_NO_RETRY_ISSUED
16896  *
16897  *     Context: May be called from interrupt context
16898  */
16899 
16900 static void
16901 sd_print_cmd_incomplete_msg(struct sd_lun *un, struct buf *bp, void *arg,
16902 	int code)
16903 {
16904 	dev_info_t	*dip;
16905 
16906 	ASSERT(un != NULL);
16907 	ASSERT(mutex_owned(SD_MUTEX(un)));
16908 	ASSERT(bp != NULL);
16909 
16910 	switch (code) {
16911 	case SD_NO_RETRY_ISSUED:
16912 		/* Command was failed. Someone turned off this target? */
16913 		if (un->un_state != SD_STATE_OFFLINE) {
16914 			/*
16915 			 * Suppress message if we are detaching and
16916 			 * device has been disconnected
16917 			 * Note that DEVI_IS_DEVICE_REMOVED is a consolidation
16918 			 * private interface and not part of the DDI
16919 			 */
16920 			dip = un->un_sd->sd_dev;
16921 			if (!(DEVI_IS_DETACHING(dip) &&
16922 			    DEVI_IS_DEVICE_REMOVED(dip))) {
16923 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
16924 				"disk not responding to selection\n");
16925 			}
16926 			New_state(un, SD_STATE_OFFLINE);
16927 		}
16928 		break;
16929 
16930 	case SD_DELAYED_RETRY_ISSUED:
16931 	case SD_IMMEDIATE_RETRY_ISSUED:
16932 	default:
16933 		/* Command was successfully queued for retry */
16934 		sd_print_retry_msg(un, bp, arg, code);
16935 		break;
16936 	}
16937 }
16938 
16939 
16940 /*
16941  *    Function: sd_pkt_reason_cmd_incomplete
16942  *
16943  * Description: Recovery actions for a SCSA "CMD_INCOMPLETE" pkt_reason.
16944  *
16945  *     Context: May be called from interrupt context
16946  */
16947 
16948 static void
16949 sd_pkt_reason_cmd_incomplete(struct sd_lun *un, struct buf *bp,
16950 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16951 {
16952 	int flag = SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE;
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 	/* Do not do a reset if selection did not complete */
16961 	/* Note: Should this not just check the bit? */
16962 	if (pktp->pkt_state != STATE_GOT_BUS) {
16963 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
16964 		sd_reset_target(un, pktp);
16965 	}
16966 
16967 	/*
16968 	 * If the target was not successfully selected, then set
16969 	 * SD_RETRIES_FAILFAST to indicate that we lost communication
16970 	 * with the target, and further retries and/or commands are
16971 	 * likely to take a long time.
16972 	 */
16973 	if ((pktp->pkt_state & STATE_GOT_TARGET) == 0) {
16974 		flag |= SD_RETRIES_FAILFAST;
16975 	}
16976 
16977 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
16978 
16979 	sd_retry_command(un, bp, flag,
16980 	    sd_print_cmd_incomplete_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
16981 }
16982 
16983 
16984 
16985 /*
16986  *    Function: sd_pkt_reason_cmd_tran_err
16987  *
16988  * Description: Recovery actions for a SCSA "CMD_TRAN_ERR" pkt_reason.
16989  *
16990  *     Context: May be called from interrupt context
16991  */
16992 
16993 static void
16994 sd_pkt_reason_cmd_tran_err(struct sd_lun *un, struct buf *bp,
16995 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
16996 {
16997 	ASSERT(un != NULL);
16998 	ASSERT(mutex_owned(SD_MUTEX(un)));
16999 	ASSERT(bp != NULL);
17000 	ASSERT(xp != NULL);
17001 	ASSERT(pktp != NULL);
17002 
17003 	/*
17004 	 * Do not reset if we got a parity error, or if
17005 	 * selection did not complete.
17006 	 */
17007 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17008 	/* Note: Should this not just check the bit for pkt_state? */
17009 	if (((pktp->pkt_statistics & STAT_PERR) == 0) &&
17010 	    (pktp->pkt_state != STATE_GOT_BUS)) {
17011 		SD_UPDATE_ERRSTATS(un, sd_transerrs);
17012 		sd_reset_target(un, pktp);
17013 	}
17014 
17015 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17016 
17017 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
17018 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17019 }
17020 
17021 
17022 
17023 /*
17024  *    Function: sd_pkt_reason_cmd_reset
17025  *
17026  * Description: Recovery actions for a SCSA "CMD_RESET" pkt_reason.
17027  *
17028  *     Context: May be called from interrupt context
17029  */
17030 
17031 static void
17032 sd_pkt_reason_cmd_reset(struct sd_lun *un, struct buf *bp,
17033 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17034 {
17035 	ASSERT(un != NULL);
17036 	ASSERT(mutex_owned(SD_MUTEX(un)));
17037 	ASSERT(bp != NULL);
17038 	ASSERT(xp != NULL);
17039 	ASSERT(pktp != NULL);
17040 
17041 	/* The target may still be running the command, so try to reset. */
17042 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
17043 	sd_reset_target(un, pktp);
17044 
17045 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17046 
17047 	/*
17048 	 * If pkt_reason is CMD_RESET chances are that this pkt got
17049 	 * reset because another target on this bus caused it. The target
17050 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
17051 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
17052 	 */
17053 
17054 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
17055 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17056 }
17057 
17058 
17059 
17060 
17061 /*
17062  *    Function: sd_pkt_reason_cmd_aborted
17063  *
17064  * Description: Recovery actions for a SCSA "CMD_ABORTED" pkt_reason.
17065  *
17066  *     Context: May be called from interrupt context
17067  */
17068 
17069 static void
17070 sd_pkt_reason_cmd_aborted(struct sd_lun *un, struct buf *bp,
17071 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17072 {
17073 	ASSERT(un != NULL);
17074 	ASSERT(mutex_owned(SD_MUTEX(un)));
17075 	ASSERT(bp != NULL);
17076 	ASSERT(xp != NULL);
17077 	ASSERT(pktp != NULL);
17078 
17079 	/* The target may still be running the command, so try to reset. */
17080 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
17081 	sd_reset_target(un, pktp);
17082 
17083 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17084 
17085 	/*
17086 	 * If pkt_reason is CMD_ABORTED chances are that this pkt got
17087 	 * aborted because another target on this bus caused it. The target
17088 	 * that caused it should get CMD_TIMEOUT with pkt_statistics
17089 	 * of STAT_TIMEOUT/STAT_DEV_RESET.
17090 	 */
17091 
17092 	sd_retry_command(un, bp, (SD_RETRIES_VICTIM | SD_RETRIES_ISOLATE),
17093 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17094 }
17095 
17096 
17097 
17098 /*
17099  *    Function: sd_pkt_reason_cmd_timeout
17100  *
17101  * Description: Recovery actions for a SCSA "CMD_TIMEOUT" pkt_reason.
17102  *
17103  *     Context: May be called from interrupt context
17104  */
17105 
17106 static void
17107 sd_pkt_reason_cmd_timeout(struct sd_lun *un, struct buf *bp,
17108 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17109 {
17110 	ASSERT(un != NULL);
17111 	ASSERT(mutex_owned(SD_MUTEX(un)));
17112 	ASSERT(bp != NULL);
17113 	ASSERT(xp != NULL);
17114 	ASSERT(pktp != NULL);
17115 
17116 
17117 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
17118 	sd_reset_target(un, pktp);
17119 
17120 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17121 
17122 	/*
17123 	 * A command timeout indicates that we could not establish
17124 	 * communication with the target, so set SD_RETRIES_FAILFAST
17125 	 * as further retries/commands are likely to take a long time.
17126 	 */
17127 	sd_retry_command(un, bp,
17128 	    (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE | SD_RETRIES_FAILFAST),
17129 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17130 }
17131 
17132 
17133 
17134 /*
17135  *    Function: sd_pkt_reason_cmd_unx_bus_free
17136  *
17137  * Description: Recovery actions for a SCSA "CMD_UNX_BUS_FREE" pkt_reason.
17138  *
17139  *     Context: May be called from interrupt context
17140  */
17141 
17142 static void
17143 sd_pkt_reason_cmd_unx_bus_free(struct sd_lun *un, struct buf *bp,
17144 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17145 {
17146 	void (*funcp)(struct sd_lun *un, struct buf *bp, void *arg, int code);
17147 
17148 	ASSERT(un != NULL);
17149 	ASSERT(mutex_owned(SD_MUTEX(un)));
17150 	ASSERT(bp != NULL);
17151 	ASSERT(xp != NULL);
17152 	ASSERT(pktp != NULL);
17153 
17154 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17155 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17156 
17157 	funcp = ((pktp->pkt_statistics & STAT_PERR) == 0) ?
17158 	    sd_print_retry_msg : NULL;
17159 
17160 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
17161 	    funcp, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17162 }
17163 
17164 
17165 /*
17166  *    Function: sd_pkt_reason_cmd_tag_reject
17167  *
17168  * Description: Recovery actions for a SCSA "CMD_TAG_REJECT" pkt_reason.
17169  *
17170  *     Context: May be called from interrupt context
17171  */
17172 
17173 static void
17174 sd_pkt_reason_cmd_tag_reject(struct sd_lun *un, struct buf *bp,
17175 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17176 {
17177 	ASSERT(un != NULL);
17178 	ASSERT(mutex_owned(SD_MUTEX(un)));
17179 	ASSERT(bp != NULL);
17180 	ASSERT(xp != NULL);
17181 	ASSERT(pktp != NULL);
17182 
17183 	SD_UPDATE_ERRSTATS(un, sd_harderrs);
17184 	pktp->pkt_flags = 0;
17185 	un->un_tagflags = 0;
17186 	if (un->un_f_opt_queueing == TRUE) {
17187 		un->un_throttle = min(un->un_throttle, 3);
17188 	} else {
17189 		un->un_throttle = 1;
17190 	}
17191 	mutex_exit(SD_MUTEX(un));
17192 	(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
17193 	mutex_enter(SD_MUTEX(un));
17194 
17195 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17196 
17197 	/* Legacy behavior not to check retry counts here. */
17198 	sd_retry_command(un, bp, (SD_RETRIES_NOCHECK | SD_RETRIES_ISOLATE),
17199 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17200 }
17201 
17202 
17203 /*
17204  *    Function: sd_pkt_reason_default
17205  *
17206  * Description: Default recovery actions for SCSA pkt_reason values that
17207  *		do not have more explicit recovery actions.
17208  *
17209  *     Context: May be called from interrupt context
17210  */
17211 
17212 static void
17213 sd_pkt_reason_default(struct sd_lun *un, struct buf *bp,
17214 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17215 {
17216 	ASSERT(un != NULL);
17217 	ASSERT(mutex_owned(SD_MUTEX(un)));
17218 	ASSERT(bp != NULL);
17219 	ASSERT(xp != NULL);
17220 	ASSERT(pktp != NULL);
17221 
17222 	SD_UPDATE_ERRSTATS(un, sd_transerrs);
17223 	sd_reset_target(un, pktp);
17224 
17225 	SD_UPDATE_RESERVATION_STATUS(un, pktp);
17226 
17227 	sd_retry_command(un, bp, (SD_RETRIES_STANDARD | SD_RETRIES_ISOLATE),
17228 	    sd_print_retry_msg, NULL, EIO, SD_RESTART_TIMEOUT, NULL);
17229 }
17230 
17231 
17232 
17233 /*
17234  *    Function: sd_pkt_status_check_condition
17235  *
17236  * Description: Recovery actions for a "STATUS_CHECK" SCSI command status.
17237  *
17238  *     Context: May be called from interrupt context
17239  */
17240 
17241 static void
17242 sd_pkt_status_check_condition(struct sd_lun *un, struct buf *bp,
17243 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17244 {
17245 	ASSERT(un != NULL);
17246 	ASSERT(mutex_owned(SD_MUTEX(un)));
17247 	ASSERT(bp != NULL);
17248 	ASSERT(xp != NULL);
17249 	ASSERT(pktp != NULL);
17250 
17251 	SD_TRACE(SD_LOG_IO, un, "sd_pkt_status_check_condition: "
17252 	    "entry: buf:0x%p xp:0x%p\n", bp, xp);
17253 
17254 	/*
17255 	 * If ARQ is NOT enabled, then issue a REQUEST SENSE command (the
17256 	 * command will be retried after the request sense). Otherwise, retry
17257 	 * the command. Note: we are issuing the request sense even though the
17258 	 * retry limit may have been reached for the failed command.
17259 	 */
17260 	if (un->un_f_arq_enabled == FALSE) {
17261 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
17262 		    "no ARQ, sending request sense command\n");
17263 		sd_send_request_sense_command(un, bp, pktp);
17264 	} else {
17265 		SD_INFO(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: "
17266 		    "ARQ,retrying request sense command\n");
17267 #if defined(__i386) || defined(__amd64)
17268 		/*
17269 		 * The SD_RETRY_DELAY value need to be adjusted here
17270 		 * when SD_RETRY_DELAY change in sddef.h
17271 		 */
17272 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
17273 		    un->un_f_is_fibre?drv_usectohz(100000):(clock_t)0,
17274 		    NULL);
17275 #else
17276 		sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL,
17277 		    EIO, SD_RETRY_DELAY, NULL);
17278 #endif
17279 	}
17280 
17281 	SD_TRACE(SD_LOG_IO_CORE, un, "sd_pkt_status_check_condition: exit\n");
17282 }
17283 
17284 
17285 /*
17286  *    Function: sd_pkt_status_busy
17287  *
17288  * Description: Recovery actions for a "STATUS_BUSY" SCSI command status.
17289  *
17290  *     Context: May be called from interrupt context
17291  */
17292 
17293 static void
17294 sd_pkt_status_busy(struct sd_lun *un, struct buf *bp, struct sd_xbuf *xp,
17295 	struct scsi_pkt *pktp)
17296 {
17297 	ASSERT(un != NULL);
17298 	ASSERT(mutex_owned(SD_MUTEX(un)));
17299 	ASSERT(bp != NULL);
17300 	ASSERT(xp != NULL);
17301 	ASSERT(pktp != NULL);
17302 
17303 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17304 	    "sd_pkt_status_busy: entry\n");
17305 
17306 	/* If retries are exhausted, just fail the command. */
17307 	if (xp->xb_retry_count >= un->un_busy_retry_count) {
17308 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
17309 		    "device busy too long\n");
17310 		sd_return_failed_command(un, bp, EIO);
17311 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17312 		    "sd_pkt_status_busy: exit\n");
17313 		return;
17314 	}
17315 	xp->xb_retry_count++;
17316 
17317 	/*
17318 	 * Try to reset the target. However, we do not want to perform
17319 	 * more than one reset if the device continues to fail. The reset
17320 	 * will be performed when the retry count reaches the reset
17321 	 * threshold.  This threshold should be set such that at least
17322 	 * one retry is issued before the reset is performed.
17323 	 */
17324 	if (xp->xb_retry_count ==
17325 	    ((un->un_reset_retry_count < 2) ? 2 : un->un_reset_retry_count)) {
17326 		int rval = 0;
17327 		mutex_exit(SD_MUTEX(un));
17328 		if (un->un_f_allow_bus_device_reset == TRUE) {
17329 			/*
17330 			 * First try to reset the LUN; if we cannot then
17331 			 * try to reset the target.
17332 			 */
17333 			if (un->un_f_lun_reset_enabled == TRUE) {
17334 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17335 				    "sd_pkt_status_busy: RESET_LUN\n");
17336 				rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
17337 			}
17338 			if (rval == 0) {
17339 				SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17340 				    "sd_pkt_status_busy: RESET_TARGET\n");
17341 				rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
17342 			}
17343 		}
17344 		if (rval == 0) {
17345 			/*
17346 			 * If the RESET_LUN and/or RESET_TARGET failed,
17347 			 * try RESET_ALL
17348 			 */
17349 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17350 			    "sd_pkt_status_busy: RESET_ALL\n");
17351 			rval = scsi_reset(SD_ADDRESS(un), RESET_ALL);
17352 		}
17353 		mutex_enter(SD_MUTEX(un));
17354 		if (rval == 0) {
17355 			/*
17356 			 * The RESET_LUN, RESET_TARGET, and/or RESET_ALL failed.
17357 			 * At this point we give up & fail the command.
17358 			 */
17359 			sd_return_failed_command(un, bp, EIO);
17360 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17361 			    "sd_pkt_status_busy: exit (failed cmd)\n");
17362 			return;
17363 		}
17364 	}
17365 
17366 	/*
17367 	 * Retry the command. Be sure to specify SD_RETRIES_NOCHECK as
17368 	 * we have already checked the retry counts above.
17369 	 */
17370 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL,
17371 	    EIO, SD_BSY_TIMEOUT, NULL);
17372 
17373 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17374 	    "sd_pkt_status_busy: exit\n");
17375 }
17376 
17377 
17378 /*
17379  *    Function: sd_pkt_status_reservation_conflict
17380  *
17381  * Description: Recovery actions for a "STATUS_RESERVATION_CONFLICT" SCSI
17382  *		command status.
17383  *
17384  *     Context: May be called from interrupt context
17385  */
17386 
17387 static void
17388 sd_pkt_status_reservation_conflict(struct sd_lun *un, struct buf *bp,
17389 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17390 {
17391 	ASSERT(un != NULL);
17392 	ASSERT(mutex_owned(SD_MUTEX(un)));
17393 	ASSERT(bp != NULL);
17394 	ASSERT(xp != NULL);
17395 	ASSERT(pktp != NULL);
17396 
17397 	/*
17398 	 * If the command was PERSISTENT_RESERVATION_[IN|OUT] then reservation
17399 	 * conflict could be due to various reasons like incorrect keys, not
17400 	 * registered or not reserved etc. So, we return EACCES to the caller.
17401 	 */
17402 	if (un->un_reservation_type == SD_SCSI3_RESERVATION) {
17403 		int cmd = SD_GET_PKT_OPCODE(pktp);
17404 		if ((cmd == SCMD_PERSISTENT_RESERVE_IN) ||
17405 		    (cmd == SCMD_PERSISTENT_RESERVE_OUT)) {
17406 			sd_return_failed_command(un, bp, EACCES);
17407 			return;
17408 		}
17409 	}
17410 
17411 	un->un_resvd_status |= SD_RESERVATION_CONFLICT;
17412 
17413 	if ((un->un_resvd_status & SD_FAILFAST) != 0) {
17414 		if (sd_failfast_enable != 0) {
17415 			/* By definition, we must panic here.... */
17416 			sd_panic_for_res_conflict(un);
17417 			/*NOTREACHED*/
17418 		}
17419 		SD_ERROR(SD_LOG_IO, un,
17420 		    "sd_handle_resv_conflict: Disk Reserved\n");
17421 		sd_return_failed_command(un, bp, EACCES);
17422 		return;
17423 	}
17424 
17425 	/*
17426 	 * 1147670: retry only if sd_retry_on_reservation_conflict
17427 	 * property is set (default is 1). Retries will not succeed
17428 	 * on a disk reserved by another initiator. HA systems
17429 	 * may reset this via sd.conf to avoid these retries.
17430 	 *
17431 	 * Note: The legacy return code for this failure is EIO, however EACCES
17432 	 * seems more appropriate for a reservation conflict.
17433 	 */
17434 	if (sd_retry_on_reservation_conflict == 0) {
17435 		SD_ERROR(SD_LOG_IO, un,
17436 		    "sd_handle_resv_conflict: Device Reserved\n");
17437 		sd_return_failed_command(un, bp, EIO);
17438 		return;
17439 	}
17440 
17441 	/*
17442 	 * Retry the command if we can.
17443 	 *
17444 	 * Note: The legacy return code for this failure is EIO, however EACCES
17445 	 * seems more appropriate for a reservation conflict.
17446 	 */
17447 	sd_retry_command(un, bp, SD_RETRIES_STANDARD, NULL, NULL, EIO,
17448 	    (clock_t)2, NULL);
17449 }
17450 
17451 
17452 
17453 /*
17454  *    Function: sd_pkt_status_qfull
17455  *
17456  * Description: Handle a QUEUE FULL condition from the target.  This can
17457  *		occur if the HBA does not handle the queue full condition.
17458  *		(Basically this means third-party HBAs as Sun HBAs will
17459  *		handle the queue full condition.)  Note that if there are
17460  *		some commands already in the transport, then the queue full
17461  *		has occurred because the queue for this nexus is actually
17462  *		full. If there are no commands in the transport, then the
17463  *		queue full is resulting from some other initiator or lun
17464  *		consuming all the resources at the target.
17465  *
17466  *     Context: May be called from interrupt context
17467  */
17468 
17469 static void
17470 sd_pkt_status_qfull(struct sd_lun *un, struct buf *bp,
17471 	struct sd_xbuf *xp, struct scsi_pkt *pktp)
17472 {
17473 	ASSERT(un != NULL);
17474 	ASSERT(mutex_owned(SD_MUTEX(un)));
17475 	ASSERT(bp != NULL);
17476 	ASSERT(xp != NULL);
17477 	ASSERT(pktp != NULL);
17478 
17479 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17480 	    "sd_pkt_status_qfull: entry\n");
17481 
17482 	/*
17483 	 * Just lower the QFULL throttle and retry the command.  Note that
17484 	 * we do not limit the number of retries here.
17485 	 */
17486 	sd_reduce_throttle(un, SD_THROTTLE_QFULL);
17487 	sd_retry_command(un, bp, SD_RETRIES_NOCHECK, NULL, NULL, 0,
17488 	    SD_RESTART_TIMEOUT, NULL);
17489 
17490 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17491 	    "sd_pkt_status_qfull: exit\n");
17492 }
17493 
17494 
17495 /*
17496  *    Function: sd_reset_target
17497  *
17498  * Description: Issue a scsi_reset(9F), with either RESET_LUN,
17499  *		RESET_TARGET, or RESET_ALL.
17500  *
17501  *     Context: May be called under interrupt context.
17502  */
17503 
17504 static void
17505 sd_reset_target(struct sd_lun *un, struct scsi_pkt *pktp)
17506 {
17507 	int rval = 0;
17508 
17509 	ASSERT(un != NULL);
17510 	ASSERT(mutex_owned(SD_MUTEX(un)));
17511 	ASSERT(pktp != NULL);
17512 
17513 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: entry\n");
17514 
17515 	/*
17516 	 * No need to reset if the transport layer has already done so.
17517 	 */
17518 	if ((pktp->pkt_statistics &
17519 	    (STAT_BUS_RESET | STAT_DEV_RESET | STAT_ABORTED)) != 0) {
17520 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17521 		    "sd_reset_target: no reset\n");
17522 		return;
17523 	}
17524 
17525 	mutex_exit(SD_MUTEX(un));
17526 
17527 	if (un->un_f_allow_bus_device_reset == TRUE) {
17528 		if (un->un_f_lun_reset_enabled == TRUE) {
17529 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17530 			    "sd_reset_target: RESET_LUN\n");
17531 			rval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
17532 		}
17533 		if (rval == 0) {
17534 			SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17535 			    "sd_reset_target: RESET_TARGET\n");
17536 			rval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
17537 		}
17538 	}
17539 
17540 	if (rval == 0) {
17541 		SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
17542 		    "sd_reset_target: RESET_ALL\n");
17543 		(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
17544 	}
17545 
17546 	mutex_enter(SD_MUTEX(un));
17547 
17548 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un, "sd_reset_target: exit\n");
17549 }
17550 
17551 /*
17552  *    Function: sd_target_change_task
17553  *
17554  * Description: Handle dynamic target change
17555  *
17556  *     Context: Executes in a taskq() thread context
17557  */
17558 static void
17559 sd_target_change_task(void *arg)
17560 {
17561 	struct sd_lun		*un = arg;
17562 	uint64_t		capacity;
17563 	diskaddr_t		label_cap;
17564 	uint_t			lbasize;
17565 
17566 	ASSERT(un != NULL);
17567 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17568 
17569 	if ((un->un_f_blockcount_is_valid == FALSE) ||
17570 	    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
17571 		return;
17572 	}
17573 
17574 	if (sd_send_scsi_READ_CAPACITY(un, &capacity,
17575 	    &lbasize, SD_PATH_DIRECT) != 0) {
17576 		SD_ERROR(SD_LOG_ERROR, un,
17577 		    "sd_target_change_task: fail to read capacity\n");
17578 		return;
17579 	}
17580 
17581 	mutex_enter(SD_MUTEX(un));
17582 	if (capacity <= un->un_blockcount) {
17583 		mutex_exit(SD_MUTEX(un));
17584 		return;
17585 	}
17586 
17587 	sd_update_block_info(un, lbasize, capacity);
17588 	mutex_exit(SD_MUTEX(un));
17589 
17590 	/*
17591 	 * If lun is EFI labeled and lun capacity is greater than the
17592 	 * capacity contained in the label, log a sys event.
17593 	 */
17594 	if (cmlb_efi_label_capacity(un->un_cmlbhandle, &label_cap,
17595 	    (void*)SD_PATH_DIRECT) == 0) {
17596 		mutex_enter(SD_MUTEX(un));
17597 		if (un->un_f_blockcount_is_valid &&
17598 		    un->un_blockcount > label_cap) {
17599 			mutex_exit(SD_MUTEX(un));
17600 			sd_log_lun_expansion_event(un, KM_SLEEP);
17601 		} else {
17602 			mutex_exit(SD_MUTEX(un));
17603 		}
17604 	}
17605 }
17606 
17607 /*
17608  *    Function: sd_log_lun_expansion_event
17609  *
17610  * Description: Log lun expansion sys event
17611  *
17612  *     Context: Never called from interrupt context
17613  */
17614 static void
17615 sd_log_lun_expansion_event(struct sd_lun *un, int km_flag)
17616 {
17617 	int err;
17618 	char			*path;
17619 	nvlist_t		*dle_attr_list;
17620 
17621 	/* Allocate and build sysevent attribute list */
17622 	err = nvlist_alloc(&dle_attr_list, NV_UNIQUE_NAME_TYPE, km_flag);
17623 	if (err != 0) {
17624 		SD_ERROR(SD_LOG_ERROR, un,
17625 		    "sd_log_lun_expansion_event: fail to allocate space\n");
17626 		return;
17627 	}
17628 
17629 	path = kmem_alloc(MAXPATHLEN, km_flag);
17630 	if (path == NULL) {
17631 		nvlist_free(dle_attr_list);
17632 		SD_ERROR(SD_LOG_ERROR, un,
17633 		    "sd_log_lun_expansion_event: fail to allocate space\n");
17634 		return;
17635 	}
17636 	/*
17637 	 * Add path attribute to identify the lun.
17638 	 * We are using minor node 'a' as the sysevent attribute.
17639 	 */
17640 	(void) snprintf(path, MAXPATHLEN, "/devices");
17641 	(void) ddi_pathname(SD_DEVINFO(un), path + strlen(path));
17642 	(void) snprintf(path + strlen(path), MAXPATHLEN - strlen(path),
17643 	    ":a");
17644 
17645 	err = nvlist_add_string(dle_attr_list, DEV_PHYS_PATH, path);
17646 	if (err != 0) {
17647 		nvlist_free(dle_attr_list);
17648 		kmem_free(path, MAXPATHLEN);
17649 		SD_ERROR(SD_LOG_ERROR, un,
17650 		    "sd_log_lun_expansion_event: fail to add attribute\n");
17651 		return;
17652 	}
17653 
17654 	/* Log dynamic lun expansion sysevent */
17655 	err = ddi_log_sysevent(SD_DEVINFO(un), SUNW_VENDOR, EC_DEV_STATUS,
17656 	    ESC_DEV_DLE, dle_attr_list, NULL, km_flag);
17657 	if (err != DDI_SUCCESS) {
17658 		SD_ERROR(SD_LOG_ERROR, un,
17659 		    "sd_log_lun_expansion_event: fail to log sysevent\n");
17660 	}
17661 
17662 	nvlist_free(dle_attr_list);
17663 	kmem_free(path, MAXPATHLEN);
17664 }
17665 
17666 /*
17667  *    Function: sd_media_change_task
17668  *
17669  * Description: Recovery action for CDROM to become available.
17670  *
17671  *     Context: Executes in a taskq() thread context
17672  */
17673 
17674 static void
17675 sd_media_change_task(void *arg)
17676 {
17677 	struct	scsi_pkt	*pktp = arg;
17678 	struct	sd_lun		*un;
17679 	struct	buf		*bp;
17680 	struct	sd_xbuf		*xp;
17681 	int	err		= 0;
17682 	int	retry_count	= 0;
17683 	int	retry_limit	= SD_UNIT_ATTENTION_RETRY/10;
17684 	struct	sd_sense_info	si;
17685 
17686 	ASSERT(pktp != NULL);
17687 	bp = (struct buf *)pktp->pkt_private;
17688 	ASSERT(bp != NULL);
17689 	xp = SD_GET_XBUF(bp);
17690 	ASSERT(xp != NULL);
17691 	un = SD_GET_UN(bp);
17692 	ASSERT(un != NULL);
17693 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17694 	ASSERT(un->un_f_monitor_media_state);
17695 
17696 	si.ssi_severity = SCSI_ERR_INFO;
17697 	si.ssi_pfa_flag = FALSE;
17698 
17699 	/*
17700 	 * When a reset is issued on a CDROM, it takes a long time to
17701 	 * recover. First few attempts to read capacity and other things
17702 	 * related to handling unit attention fail (with a ASC 0x4 and
17703 	 * ASCQ 0x1). In that case we want to do enough retries and we want
17704 	 * to limit the retries in other cases of genuine failures like
17705 	 * no media in drive.
17706 	 */
17707 	while (retry_count++ < retry_limit) {
17708 		if ((err = sd_handle_mchange(un)) == 0) {
17709 			break;
17710 		}
17711 		if (err == EAGAIN) {
17712 			retry_limit = SD_UNIT_ATTENTION_RETRY;
17713 		}
17714 		/* Sleep for 0.5 sec. & try again */
17715 		delay(drv_usectohz(500000));
17716 	}
17717 
17718 	/*
17719 	 * Dispatch (retry or fail) the original command here,
17720 	 * along with appropriate console messages....
17721 	 *
17722 	 * Must grab the mutex before calling sd_retry_command,
17723 	 * sd_print_sense_msg and sd_return_failed_command.
17724 	 */
17725 	mutex_enter(SD_MUTEX(un));
17726 	if (err != SD_CMD_SUCCESS) {
17727 		SD_UPDATE_ERRSTATS(un, sd_harderrs);
17728 		SD_UPDATE_ERRSTATS(un, sd_rq_nodev_err);
17729 		si.ssi_severity = SCSI_ERR_FATAL;
17730 		sd_print_sense_msg(un, bp, &si, SD_NO_RETRY_ISSUED);
17731 		sd_return_failed_command(un, bp, EIO);
17732 	} else {
17733 		sd_retry_command(un, bp, SD_RETRIES_NOCHECK, sd_print_sense_msg,
17734 		    &si, EIO, (clock_t)0, NULL);
17735 	}
17736 	mutex_exit(SD_MUTEX(un));
17737 }
17738 
17739 
17740 
17741 /*
17742  *    Function: sd_handle_mchange
17743  *
17744  * Description: Perform geometry validation & other recovery when CDROM
17745  *		has been removed from drive.
17746  *
17747  * Return Code: 0 for success
17748  *		errno-type return code of either sd_send_scsi_DOORLOCK() or
17749  *		sd_send_scsi_READ_CAPACITY()
17750  *
17751  *     Context: Executes in a taskq() thread context
17752  */
17753 
17754 static int
17755 sd_handle_mchange(struct sd_lun *un)
17756 {
17757 	uint64_t	capacity;
17758 	uint32_t	lbasize;
17759 	int		rval;
17760 
17761 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17762 	ASSERT(un->un_f_monitor_media_state);
17763 
17764 	if ((rval = sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
17765 	    SD_PATH_DIRECT_PRIORITY)) != 0) {
17766 		return (rval);
17767 	}
17768 
17769 	mutex_enter(SD_MUTEX(un));
17770 	sd_update_block_info(un, lbasize, capacity);
17771 
17772 	if (un->un_errstats != NULL) {
17773 		struct	sd_errstats *stp =
17774 		    (struct sd_errstats *)un->un_errstats->ks_data;
17775 		stp->sd_capacity.value.ui64 = (uint64_t)
17776 		    ((uint64_t)un->un_blockcount *
17777 		    (uint64_t)un->un_tgt_blocksize);
17778 	}
17779 
17780 
17781 	/*
17782 	 * Check if the media in the device is writable or not
17783 	 */
17784 	if (ISCD(un))
17785 		sd_check_for_writable_cd(un, SD_PATH_DIRECT_PRIORITY);
17786 
17787 	/*
17788 	 * Note: Maybe let the strategy/partitioning chain worry about getting
17789 	 * valid geometry.
17790 	 */
17791 	mutex_exit(SD_MUTEX(un));
17792 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
17793 
17794 
17795 	if (cmlb_validate(un->un_cmlbhandle, 0,
17796 	    (void *)SD_PATH_DIRECT_PRIORITY) != 0) {
17797 		return (EIO);
17798 	} else {
17799 		if (un->un_f_pkstats_enabled) {
17800 			sd_set_pstats(un);
17801 			SD_TRACE(SD_LOG_IO_PARTITION, un,
17802 			    "sd_handle_mchange: un:0x%p pstats created and "
17803 			    "set\n", un);
17804 		}
17805 	}
17806 
17807 
17808 	/*
17809 	 * Try to lock the door
17810 	 */
17811 	return (sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
17812 	    SD_PATH_DIRECT_PRIORITY));
17813 }
17814 
17815 
17816 /*
17817  *    Function: sd_send_scsi_DOORLOCK
17818  *
17819  * Description: Issue the scsi DOOR LOCK command
17820  *
17821  *   Arguments: un    - pointer to driver soft state (unit) structure for
17822  *			this target.
17823  *		flag  - SD_REMOVAL_ALLOW
17824  *			SD_REMOVAL_PREVENT
17825  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17826  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17827  *			to use the USCSI "direct" chain and bypass the normal
17828  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17829  *			command is issued as part of an error recovery action.
17830  *
17831  * Return Code: 0   - Success
17832  *		errno return code from sd_send_scsi_cmd()
17833  *
17834  *     Context: Can sleep.
17835  */
17836 
17837 static int
17838 sd_send_scsi_DOORLOCK(struct sd_lun *un, int flag, int path_flag)
17839 {
17840 	union scsi_cdb		cdb;
17841 	struct uscsi_cmd	ucmd_buf;
17842 	struct scsi_extended_sense	sense_buf;
17843 	int			status;
17844 
17845 	ASSERT(un != NULL);
17846 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17847 
17848 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_DOORLOCK: entry: un:0x%p\n", un);
17849 
17850 	/* already determined doorlock is not supported, fake success */
17851 	if (un->un_f_doorlock_supported == FALSE) {
17852 		return (0);
17853 	}
17854 
17855 	/*
17856 	 * If we are ejecting and see an SD_REMOVAL_PREVENT
17857 	 * ignore the command so we can complete the eject
17858 	 * operation.
17859 	 */
17860 	if (flag == SD_REMOVAL_PREVENT) {
17861 		mutex_enter(SD_MUTEX(un));
17862 		if (un->un_f_ejecting == TRUE) {
17863 			mutex_exit(SD_MUTEX(un));
17864 			return (EAGAIN);
17865 		}
17866 		mutex_exit(SD_MUTEX(un));
17867 	}
17868 
17869 	bzero(&cdb, sizeof (cdb));
17870 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17871 
17872 	cdb.scc_cmd = SCMD_DOORLOCK;
17873 	cdb.cdb_opaque[4] = (uchar_t)flag;
17874 
17875 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17876 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
17877 	ucmd_buf.uscsi_bufaddr	= NULL;
17878 	ucmd_buf.uscsi_buflen	= 0;
17879 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17880 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17881 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
17882 	ucmd_buf.uscsi_timeout	= 15;
17883 
17884 	SD_TRACE(SD_LOG_IO, un,
17885 	    "sd_send_scsi_DOORLOCK: returning sd_send_scsi_cmd()\n");
17886 
17887 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17888 	    UIO_SYSSPACE, path_flag);
17889 
17890 	if ((status == EIO) && (ucmd_buf.uscsi_status == STATUS_CHECK) &&
17891 	    (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
17892 	    (scsi_sense_key((uint8_t *)&sense_buf) == KEY_ILLEGAL_REQUEST)) {
17893 		/* fake success and skip subsequent doorlock commands */
17894 		un->un_f_doorlock_supported = FALSE;
17895 		return (0);
17896 	}
17897 
17898 	return (status);
17899 }
17900 
17901 /*
17902  *    Function: sd_send_scsi_READ_CAPACITY
17903  *
17904  * Description: This routine uses the scsi READ CAPACITY command to determine
17905  *		the device capacity in number of blocks and the device native
17906  *		block size. If this function returns a failure, then the
17907  *		values in *capp and *lbap are undefined.  If the capacity
17908  *		returned is 0xffffffff then the lun is too large for a
17909  *		normal READ CAPACITY command and the results of a
17910  *		READ CAPACITY 16 will be used instead.
17911  *
17912  *   Arguments: un   - ptr to soft state struct for the target
17913  *		capp - ptr to unsigned 64-bit variable to receive the
17914  *			capacity value from the command.
17915  *		lbap - ptr to unsigned 32-bit varaible to receive the
17916  *			block size value from the command
17917  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
17918  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
17919  *			to use the USCSI "direct" chain and bypass the normal
17920  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
17921  *			command is issued as part of an error recovery action.
17922  *
17923  * Return Code: 0   - Success
17924  *		EIO - IO error
17925  *		EACCES - Reservation conflict detected
17926  *		EAGAIN - Device is becoming ready
17927  *		errno return code from sd_send_scsi_cmd()
17928  *
17929  *     Context: Can sleep.  Blocks until command completes.
17930  */
17931 
17932 #define	SD_CAPACITY_SIZE	sizeof (struct scsi_capacity)
17933 
17934 static int
17935 sd_send_scsi_READ_CAPACITY(struct sd_lun *un, uint64_t *capp, uint32_t *lbap,
17936 	int path_flag)
17937 {
17938 	struct	scsi_extended_sense	sense_buf;
17939 	struct	uscsi_cmd	ucmd_buf;
17940 	union	scsi_cdb	cdb;
17941 	uint32_t		*capacity_buf;
17942 	uint64_t		capacity;
17943 	uint32_t		lbasize;
17944 	int			status;
17945 
17946 	ASSERT(un != NULL);
17947 	ASSERT(!mutex_owned(SD_MUTEX(un)));
17948 	ASSERT(capp != NULL);
17949 	ASSERT(lbap != NULL);
17950 
17951 	SD_TRACE(SD_LOG_IO, un,
17952 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
17953 
17954 	/*
17955 	 * First send a READ_CAPACITY command to the target.
17956 	 * (This command is mandatory under SCSI-2.)
17957 	 *
17958 	 * Set up the CDB for the READ_CAPACITY command.  The Partial
17959 	 * Medium Indicator bit is cleared.  The address field must be
17960 	 * zero if the PMI bit is zero.
17961 	 */
17962 	bzero(&cdb, sizeof (cdb));
17963 	bzero(&ucmd_buf, sizeof (ucmd_buf));
17964 
17965 	capacity_buf = kmem_zalloc(SD_CAPACITY_SIZE, KM_SLEEP);
17966 
17967 	cdb.scc_cmd = SCMD_READ_CAPACITY;
17968 
17969 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
17970 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
17971 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity_buf;
17972 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_SIZE;
17973 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
17974 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
17975 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
17976 	ucmd_buf.uscsi_timeout	= 60;
17977 
17978 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
17979 	    UIO_SYSSPACE, path_flag);
17980 
17981 	switch (status) {
17982 	case 0:
17983 		/* Return failure if we did not get valid capacity data. */
17984 		if (ucmd_buf.uscsi_resid != 0) {
17985 			kmem_free(capacity_buf, SD_CAPACITY_SIZE);
17986 			return (EIO);
17987 		}
17988 
17989 		/*
17990 		 * Read capacity and block size from the READ CAPACITY 10 data.
17991 		 * This data may be adjusted later due to device specific
17992 		 * issues.
17993 		 *
17994 		 * According to the SCSI spec, the READ CAPACITY 10
17995 		 * command returns the following:
17996 		 *
17997 		 *  bytes 0-3: Maximum logical block address available.
17998 		 *		(MSB in byte:0 & LSB in byte:3)
17999 		 *
18000 		 *  bytes 4-7: Block length in bytes
18001 		 *		(MSB in byte:4 & LSB in byte:7)
18002 		 *
18003 		 */
18004 		capacity = BE_32(capacity_buf[0]);
18005 		lbasize = BE_32(capacity_buf[1]);
18006 
18007 		/*
18008 		 * Done with capacity_buf
18009 		 */
18010 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
18011 
18012 		/*
18013 		 * if the reported capacity is set to all 0xf's, then
18014 		 * this disk is too large and requires SBC-2 commands.
18015 		 * Reissue the request using READ CAPACITY 16.
18016 		 */
18017 		if (capacity == 0xffffffff) {
18018 			status = sd_send_scsi_READ_CAPACITY_16(un, &capacity,
18019 			    &lbasize, path_flag);
18020 			if (status != 0) {
18021 				return (status);
18022 			}
18023 		}
18024 		break;	/* Success! */
18025 	case EIO:
18026 		switch (ucmd_buf.uscsi_status) {
18027 		case STATUS_RESERVATION_CONFLICT:
18028 			status = EACCES;
18029 			break;
18030 		case STATUS_CHECK:
18031 			/*
18032 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
18033 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
18034 			 */
18035 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18036 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
18037 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
18038 				kmem_free(capacity_buf, SD_CAPACITY_SIZE);
18039 				return (EAGAIN);
18040 			}
18041 			break;
18042 		default:
18043 			break;
18044 		}
18045 		/* FALLTHRU */
18046 	default:
18047 		kmem_free(capacity_buf, SD_CAPACITY_SIZE);
18048 		return (status);
18049 	}
18050 
18051 	/*
18052 	 * Some ATAPI CD-ROM drives report inaccurate LBA size values
18053 	 * (2352 and 0 are common) so for these devices always force the value
18054 	 * to 2048 as required by the ATAPI specs.
18055 	 */
18056 	if ((un->un_f_cfg_is_atapi == TRUE) && (ISCD(un))) {
18057 		lbasize = 2048;
18058 	}
18059 
18060 	/*
18061 	 * Get the maximum LBA value from the READ CAPACITY data.
18062 	 * Here we assume that the Partial Medium Indicator (PMI) bit
18063 	 * was cleared when issuing the command. This means that the LBA
18064 	 * returned from the device is the LBA of the last logical block
18065 	 * on the logical unit.  The actual logical block count will be
18066 	 * this value plus one.
18067 	 *
18068 	 * Currently the capacity is saved in terms of un->un_sys_blocksize,
18069 	 * so scale the capacity value to reflect this.
18070 	 */
18071 	capacity = (capacity + 1) * (lbasize / un->un_sys_blocksize);
18072 
18073 	/*
18074 	 * Copy the values from the READ CAPACITY command into the space
18075 	 * provided by the caller.
18076 	 */
18077 	*capp = capacity;
18078 	*lbap = lbasize;
18079 
18080 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY: "
18081 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
18082 
18083 	/*
18084 	 * Both the lbasize and capacity from the device must be nonzero,
18085 	 * otherwise we assume that the values are not valid and return
18086 	 * failure to the caller. (4203735)
18087 	 */
18088 	if ((capacity == 0) || (lbasize == 0)) {
18089 		return (EIO);
18090 	}
18091 
18092 	return (0);
18093 }
18094 
18095 /*
18096  *    Function: sd_send_scsi_READ_CAPACITY_16
18097  *
18098  * Description: This routine uses the scsi READ CAPACITY 16 command to
18099  *		determine the device capacity in number of blocks and the
18100  *		device native block size.  If this function returns a failure,
18101  *		then the values in *capp and *lbap are undefined.
18102  *		This routine should always be called by
18103  *		sd_send_scsi_READ_CAPACITY which will appy any device
18104  *		specific adjustments to capacity and lbasize.
18105  *
18106  *   Arguments: un   - ptr to soft state struct for the target
18107  *		capp - ptr to unsigned 64-bit variable to receive the
18108  *			capacity value from the command.
18109  *		lbap - ptr to unsigned 32-bit varaible to receive the
18110  *			block size value from the command
18111  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
18112  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
18113  *			to use the USCSI "direct" chain and bypass the normal
18114  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when
18115  *			this command is issued as part of an error recovery
18116  *			action.
18117  *
18118  * Return Code: 0   - Success
18119  *		EIO - IO error
18120  *		EACCES - Reservation conflict detected
18121  *		EAGAIN - Device is becoming ready
18122  *		errno return code from sd_send_scsi_cmd()
18123  *
18124  *     Context: Can sleep.  Blocks until command completes.
18125  */
18126 
18127 #define	SD_CAPACITY_16_SIZE	sizeof (struct scsi_capacity_16)
18128 
18129 static int
18130 sd_send_scsi_READ_CAPACITY_16(struct sd_lun *un, uint64_t *capp,
18131 	uint32_t *lbap, int path_flag)
18132 {
18133 	struct	scsi_extended_sense	sense_buf;
18134 	struct	uscsi_cmd	ucmd_buf;
18135 	union	scsi_cdb	cdb;
18136 	uint64_t		*capacity16_buf;
18137 	uint64_t		capacity;
18138 	uint32_t		lbasize;
18139 	int			status;
18140 
18141 	ASSERT(un != NULL);
18142 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18143 	ASSERT(capp != NULL);
18144 	ASSERT(lbap != NULL);
18145 
18146 	SD_TRACE(SD_LOG_IO, un,
18147 	    "sd_send_scsi_READ_CAPACITY: entry: un:0x%p\n", un);
18148 
18149 	/*
18150 	 * First send a READ_CAPACITY_16 command to the target.
18151 	 *
18152 	 * Set up the CDB for the READ_CAPACITY_16 command.  The Partial
18153 	 * Medium Indicator bit is cleared.  The address field must be
18154 	 * zero if the PMI bit is zero.
18155 	 */
18156 	bzero(&cdb, sizeof (cdb));
18157 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18158 
18159 	capacity16_buf = kmem_zalloc(SD_CAPACITY_16_SIZE, KM_SLEEP);
18160 
18161 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18162 	ucmd_buf.uscsi_cdblen	= CDB_GROUP4;
18163 	ucmd_buf.uscsi_bufaddr	= (caddr_t)capacity16_buf;
18164 	ucmd_buf.uscsi_buflen	= SD_CAPACITY_16_SIZE;
18165 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18166 	ucmd_buf.uscsi_rqlen	= sizeof (sense_buf);
18167 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
18168 	ucmd_buf.uscsi_timeout	= 60;
18169 
18170 	/*
18171 	 * Read Capacity (16) is a Service Action In command.  One
18172 	 * command byte (0x9E) is overloaded for multiple operations,
18173 	 * with the second CDB byte specifying the desired operation
18174 	 */
18175 	cdb.scc_cmd = SCMD_SVC_ACTION_IN_G4;
18176 	cdb.cdb_opaque[1] = SSVC_ACTION_READ_CAPACITY_G4;
18177 
18178 	/*
18179 	 * Fill in allocation length field
18180 	 */
18181 	FORMG4COUNT(&cdb, ucmd_buf.uscsi_buflen);
18182 
18183 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18184 	    UIO_SYSSPACE, path_flag);
18185 
18186 	switch (status) {
18187 	case 0:
18188 		/* Return failure if we did not get valid capacity data. */
18189 		if (ucmd_buf.uscsi_resid > 20) {
18190 			kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
18191 			return (EIO);
18192 		}
18193 
18194 		/*
18195 		 * Read capacity and block size from the READ CAPACITY 10 data.
18196 		 * This data may be adjusted later due to device specific
18197 		 * issues.
18198 		 *
18199 		 * According to the SCSI spec, the READ CAPACITY 10
18200 		 * command returns the following:
18201 		 *
18202 		 *  bytes 0-7: Maximum logical block address available.
18203 		 *		(MSB in byte:0 & LSB in byte:7)
18204 		 *
18205 		 *  bytes 8-11: Block length in bytes
18206 		 *		(MSB in byte:8 & LSB in byte:11)
18207 		 *
18208 		 */
18209 		capacity = BE_64(capacity16_buf[0]);
18210 		lbasize = BE_32(*(uint32_t *)&capacity16_buf[1]);
18211 
18212 		/*
18213 		 * Done with capacity16_buf
18214 		 */
18215 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
18216 
18217 		/*
18218 		 * if the reported capacity is set to all 0xf's, then
18219 		 * this disk is too large.  This could only happen with
18220 		 * a device that supports LBAs larger than 64 bits which
18221 		 * are not defined by any current T10 standards.
18222 		 */
18223 		if (capacity == 0xffffffffffffffff) {
18224 			return (EIO);
18225 		}
18226 		break;	/* Success! */
18227 	case EIO:
18228 		switch (ucmd_buf.uscsi_status) {
18229 		case STATUS_RESERVATION_CONFLICT:
18230 			status = EACCES;
18231 			break;
18232 		case STATUS_CHECK:
18233 			/*
18234 			 * Check condition; look for ASC/ASCQ of 0x04/0x01
18235 			 * (LOGICAL UNIT IS IN PROCESS OF BECOMING READY)
18236 			 */
18237 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18238 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x04) &&
18239 			    (scsi_sense_ascq((uint8_t *)&sense_buf) == 0x01)) {
18240 				kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
18241 				return (EAGAIN);
18242 			}
18243 			break;
18244 		default:
18245 			break;
18246 		}
18247 		/* FALLTHRU */
18248 	default:
18249 		kmem_free(capacity16_buf, SD_CAPACITY_16_SIZE);
18250 		return (status);
18251 	}
18252 
18253 	*capp = capacity;
18254 	*lbap = lbasize;
18255 
18256 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_READ_CAPACITY_16: "
18257 	    "capacity:0x%llx  lbasize:0x%x\n", capacity, lbasize);
18258 
18259 	return (0);
18260 }
18261 
18262 
18263 /*
18264  *    Function: sd_send_scsi_START_STOP_UNIT
18265  *
18266  * Description: Issue a scsi START STOP UNIT command to the target.
18267  *
18268  *   Arguments: un    - pointer to driver soft state (unit) structure for
18269  *			this target.
18270  *		flag  - SD_TARGET_START
18271  *			SD_TARGET_STOP
18272  *			SD_TARGET_EJECT
18273  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
18274  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
18275  *			to use the USCSI "direct" chain and bypass the normal
18276  *			command waitq. SD_PATH_DIRECT_PRIORITY is used when this
18277  *			command is issued as part of an error recovery action.
18278  *
18279  * Return Code: 0   - Success
18280  *		EIO - IO error
18281  *		EACCES - Reservation conflict detected
18282  *		ENXIO  - Not Ready, medium not present
18283  *		errno return code from sd_send_scsi_cmd()
18284  *
18285  *     Context: Can sleep.
18286  */
18287 
18288 static int
18289 sd_send_scsi_START_STOP_UNIT(struct sd_lun *un, int flag, int path_flag)
18290 {
18291 	struct	scsi_extended_sense	sense_buf;
18292 	union scsi_cdb		cdb;
18293 	struct uscsi_cmd	ucmd_buf;
18294 	int			status;
18295 
18296 	ASSERT(un != NULL);
18297 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18298 
18299 	SD_TRACE(SD_LOG_IO, un,
18300 	    "sd_send_scsi_START_STOP_UNIT: entry: un:0x%p\n", un);
18301 
18302 	if (un->un_f_check_start_stop &&
18303 	    ((flag == SD_TARGET_START) || (flag == SD_TARGET_STOP)) &&
18304 	    (un->un_f_start_stop_supported != TRUE)) {
18305 		return (0);
18306 	}
18307 
18308 	/*
18309 	 * If we are performing an eject operation and
18310 	 * we receive any command other than SD_TARGET_EJECT
18311 	 * we should immediately return.
18312 	 */
18313 	if (flag != SD_TARGET_EJECT) {
18314 		mutex_enter(SD_MUTEX(un));
18315 		if (un->un_f_ejecting == TRUE) {
18316 			mutex_exit(SD_MUTEX(un));
18317 			return (EAGAIN);
18318 		}
18319 		mutex_exit(SD_MUTEX(un));
18320 	}
18321 
18322 	bzero(&cdb, sizeof (cdb));
18323 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18324 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18325 
18326 	cdb.scc_cmd = SCMD_START_STOP;
18327 	cdb.cdb_opaque[4] = (uchar_t)flag;
18328 
18329 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18330 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18331 	ucmd_buf.uscsi_bufaddr	= NULL;
18332 	ucmd_buf.uscsi_buflen	= 0;
18333 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18334 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18335 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18336 	ucmd_buf.uscsi_timeout	= 200;
18337 
18338 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18339 	    UIO_SYSSPACE, path_flag);
18340 
18341 	switch (status) {
18342 	case 0:
18343 		break;	/* Success! */
18344 	case EIO:
18345 		switch (ucmd_buf.uscsi_status) {
18346 		case STATUS_RESERVATION_CONFLICT:
18347 			status = EACCES;
18348 			break;
18349 		case STATUS_CHECK:
18350 			if (ucmd_buf.uscsi_rqstatus == STATUS_GOOD) {
18351 				switch (scsi_sense_key(
18352 				    (uint8_t *)&sense_buf)) {
18353 				case KEY_ILLEGAL_REQUEST:
18354 					status = ENOTSUP;
18355 					break;
18356 				case KEY_NOT_READY:
18357 					if (scsi_sense_asc(
18358 					    (uint8_t *)&sense_buf)
18359 					    == 0x3A) {
18360 						status = ENXIO;
18361 					}
18362 					break;
18363 				default:
18364 					break;
18365 				}
18366 			}
18367 			break;
18368 		default:
18369 			break;
18370 		}
18371 		break;
18372 	default:
18373 		break;
18374 	}
18375 
18376 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_START_STOP_UNIT: exit\n");
18377 
18378 	return (status);
18379 }
18380 
18381 
18382 /*
18383  *    Function: sd_start_stop_unit_callback
18384  *
18385  * Description: timeout(9F) callback to begin recovery process for a
18386  *		device that has spun down.
18387  *
18388  *   Arguments: arg - pointer to associated softstate struct.
18389  *
18390  *     Context: Executes in a timeout(9F) thread context
18391  */
18392 
18393 static void
18394 sd_start_stop_unit_callback(void *arg)
18395 {
18396 	struct sd_lun	*un = arg;
18397 	ASSERT(un != NULL);
18398 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18399 
18400 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_callback: entry\n");
18401 
18402 	(void) taskq_dispatch(sd_tq, sd_start_stop_unit_task, un, KM_NOSLEEP);
18403 }
18404 
18405 
18406 /*
18407  *    Function: sd_start_stop_unit_task
18408  *
18409  * Description: Recovery procedure when a drive is spun down.
18410  *
18411  *   Arguments: arg - pointer to associated softstate struct.
18412  *
18413  *     Context: Executes in a taskq() thread context
18414  */
18415 
18416 static void
18417 sd_start_stop_unit_task(void *arg)
18418 {
18419 	struct sd_lun	*un = arg;
18420 
18421 	ASSERT(un != NULL);
18422 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18423 
18424 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: entry\n");
18425 
18426 	/*
18427 	 * Some unformatted drives report not ready error, no need to
18428 	 * restart if format has been initiated.
18429 	 */
18430 	mutex_enter(SD_MUTEX(un));
18431 	if (un->un_f_format_in_progress == TRUE) {
18432 		mutex_exit(SD_MUTEX(un));
18433 		return;
18434 	}
18435 	mutex_exit(SD_MUTEX(un));
18436 
18437 	/*
18438 	 * When a START STOP command is issued from here, it is part of a
18439 	 * failure recovery operation and must be issued before any other
18440 	 * commands, including any pending retries. Thus it must be sent
18441 	 * using SD_PATH_DIRECT_PRIORITY. It doesn't matter if the spin up
18442 	 * succeeds or not, we will start I/O after the attempt.
18443 	 */
18444 	(void) sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
18445 	    SD_PATH_DIRECT_PRIORITY);
18446 
18447 	/*
18448 	 * The above call blocks until the START_STOP_UNIT command completes.
18449 	 * Now that it has completed, we must re-try the original IO that
18450 	 * received the NOT READY condition in the first place. There are
18451 	 * three possible conditions here:
18452 	 *
18453 	 *  (1) The original IO is on un_retry_bp.
18454 	 *  (2) The original IO is on the regular wait queue, and un_retry_bp
18455 	 *	is NULL.
18456 	 *  (3) The original IO is on the regular wait queue, and un_retry_bp
18457 	 *	points to some other, unrelated bp.
18458 	 *
18459 	 * For each case, we must call sd_start_cmds() with un_retry_bp
18460 	 * as the argument. If un_retry_bp is NULL, this will initiate
18461 	 * processing of the regular wait queue.  If un_retry_bp is not NULL,
18462 	 * then this will process the bp on un_retry_bp. That may or may not
18463 	 * be the original IO, but that does not matter: the important thing
18464 	 * is to keep the IO processing going at this point.
18465 	 *
18466 	 * Note: This is a very specific error recovery sequence associated
18467 	 * with a drive that is not spun up. We attempt a START_STOP_UNIT and
18468 	 * serialize the I/O with completion of the spin-up.
18469 	 */
18470 	mutex_enter(SD_MUTEX(un));
18471 	SD_TRACE(SD_LOG_IO_CORE | SD_LOG_ERROR, un,
18472 	    "sd_start_stop_unit_task: un:0x%p starting bp:0x%p\n",
18473 	    un, un->un_retry_bp);
18474 	un->un_startstop_timeid = NULL;	/* Timeout is no longer pending */
18475 	sd_start_cmds(un, un->un_retry_bp);
18476 	mutex_exit(SD_MUTEX(un));
18477 
18478 	SD_TRACE(SD_LOG_IO, un, "sd_start_stop_unit_task: exit\n");
18479 }
18480 
18481 
18482 /*
18483  *    Function: sd_send_scsi_INQUIRY
18484  *
18485  * Description: Issue the scsi INQUIRY command.
18486  *
18487  *   Arguments: un
18488  *		bufaddr
18489  *		buflen
18490  *		evpd
18491  *		page_code
18492  *		page_length
18493  *
18494  * Return Code: 0   - Success
18495  *		errno return code from sd_send_scsi_cmd()
18496  *
18497  *     Context: Can sleep. Does not return until command is completed.
18498  */
18499 
18500 static int
18501 sd_send_scsi_INQUIRY(struct sd_lun *un, uchar_t *bufaddr, size_t buflen,
18502 	uchar_t evpd, uchar_t page_code, size_t *residp)
18503 {
18504 	union scsi_cdb		cdb;
18505 	struct uscsi_cmd	ucmd_buf;
18506 	int			status;
18507 
18508 	ASSERT(un != NULL);
18509 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18510 	ASSERT(bufaddr != NULL);
18511 
18512 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: entry: un:0x%p\n", un);
18513 
18514 	bzero(&cdb, sizeof (cdb));
18515 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18516 	bzero(bufaddr, buflen);
18517 
18518 	cdb.scc_cmd = SCMD_INQUIRY;
18519 	cdb.cdb_opaque[1] = evpd;
18520 	cdb.cdb_opaque[2] = page_code;
18521 	FORMG0COUNT(&cdb, buflen);
18522 
18523 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18524 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18525 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
18526 	ucmd_buf.uscsi_buflen	= buflen;
18527 	ucmd_buf.uscsi_rqbuf	= NULL;
18528 	ucmd_buf.uscsi_rqlen	= 0;
18529 	ucmd_buf.uscsi_flags	= USCSI_READ | USCSI_SILENT;
18530 	ucmd_buf.uscsi_timeout	= 200;	/* Excessive legacy value */
18531 
18532 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18533 	    UIO_SYSSPACE, SD_PATH_DIRECT);
18534 
18535 	if ((status == 0) && (residp != NULL)) {
18536 		*residp = ucmd_buf.uscsi_resid;
18537 	}
18538 
18539 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_INQUIRY: exit\n");
18540 
18541 	return (status);
18542 }
18543 
18544 
18545 /*
18546  *    Function: sd_send_scsi_TEST_UNIT_READY
18547  *
18548  * Description: Issue the scsi TEST UNIT READY command.
18549  *		This routine can be told to set the flag USCSI_DIAGNOSE to
18550  *		prevent retrying failed commands. Use this when the intent
18551  *		is either to check for device readiness, to clear a Unit
18552  *		Attention, or to clear any outstanding sense data.
18553  *		However under specific conditions the expected behavior
18554  *		is for retries to bring a device ready, so use the flag
18555  *		with caution.
18556  *
18557  *   Arguments: un
18558  *		flag:   SD_CHECK_FOR_MEDIA: return ENXIO if no media present
18559  *			SD_DONT_RETRY_TUR: include uscsi flag USCSI_DIAGNOSE.
18560  *			0: dont check for media present, do retries on cmd.
18561  *
18562  * Return Code: 0   - Success
18563  *		EIO - IO error
18564  *		EACCES - Reservation conflict detected
18565  *		ENXIO  - Not Ready, medium not present
18566  *		errno return code from sd_send_scsi_cmd()
18567  *
18568  *     Context: Can sleep. Does not return until command is completed.
18569  */
18570 
18571 static int
18572 sd_send_scsi_TEST_UNIT_READY(struct sd_lun *un, int flag)
18573 {
18574 	struct	scsi_extended_sense	sense_buf;
18575 	union scsi_cdb		cdb;
18576 	struct uscsi_cmd	ucmd_buf;
18577 	int			status;
18578 
18579 	ASSERT(un != NULL);
18580 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18581 
18582 	SD_TRACE(SD_LOG_IO, un,
18583 	    "sd_send_scsi_TEST_UNIT_READY: entry: un:0x%p\n", un);
18584 
18585 	/*
18586 	 * Some Seagate elite1 TQ devices get hung with disconnect/reconnect
18587 	 * timeouts when they receive a TUR and the queue is not empty. Check
18588 	 * the configuration flag set during attach (indicating the drive has
18589 	 * this firmware bug) and un_ncmds_in_transport before issuing the
18590 	 * TUR. If there are
18591 	 * pending commands return success, this is a bit arbitrary but is ok
18592 	 * for non-removables (i.e. the eliteI disks) and non-clustering
18593 	 * configurations.
18594 	 */
18595 	if (un->un_f_cfg_tur_check == TRUE) {
18596 		mutex_enter(SD_MUTEX(un));
18597 		if (un->un_ncmds_in_transport != 0) {
18598 			mutex_exit(SD_MUTEX(un));
18599 			return (0);
18600 		}
18601 		mutex_exit(SD_MUTEX(un));
18602 	}
18603 
18604 	bzero(&cdb, sizeof (cdb));
18605 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18606 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18607 
18608 	cdb.scc_cmd = SCMD_TEST_UNIT_READY;
18609 
18610 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18611 	ucmd_buf.uscsi_cdblen	= CDB_GROUP0;
18612 	ucmd_buf.uscsi_bufaddr	= NULL;
18613 	ucmd_buf.uscsi_buflen	= 0;
18614 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18615 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18616 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_SILENT;
18617 
18618 	/* Use flag USCSI_DIAGNOSE to prevent retries if it fails. */
18619 	if ((flag & SD_DONT_RETRY_TUR) != 0) {
18620 		ucmd_buf.uscsi_flags |= USCSI_DIAGNOSE;
18621 	}
18622 	ucmd_buf.uscsi_timeout	= 60;
18623 
18624 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18625 	    UIO_SYSSPACE, ((flag & SD_BYPASS_PM) ? SD_PATH_DIRECT :
18626 	    SD_PATH_STANDARD));
18627 
18628 	switch (status) {
18629 	case 0:
18630 		break;	/* Success! */
18631 	case EIO:
18632 		switch (ucmd_buf.uscsi_status) {
18633 		case STATUS_RESERVATION_CONFLICT:
18634 			status = EACCES;
18635 			break;
18636 		case STATUS_CHECK:
18637 			if ((flag & SD_CHECK_FOR_MEDIA) == 0) {
18638 				break;
18639 			}
18640 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18641 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18642 			    KEY_NOT_READY) &&
18643 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x3A)) {
18644 				status = ENXIO;
18645 			}
18646 			break;
18647 		default:
18648 			break;
18649 		}
18650 		break;
18651 	default:
18652 		break;
18653 	}
18654 
18655 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_TEST_UNIT_READY: exit\n");
18656 
18657 	return (status);
18658 }
18659 
18660 
18661 /*
18662  *    Function: sd_send_scsi_PERSISTENT_RESERVE_IN
18663  *
18664  * Description: Issue the scsi PERSISTENT RESERVE IN command.
18665  *
18666  *   Arguments: un
18667  *
18668  * Return Code: 0   - Success
18669  *		EACCES
18670  *		ENOTSUP
18671  *		errno return code from sd_send_scsi_cmd()
18672  *
18673  *     Context: Can sleep. Does not return until command is completed.
18674  */
18675 
18676 static int
18677 sd_send_scsi_PERSISTENT_RESERVE_IN(struct sd_lun *un, uchar_t  usr_cmd,
18678 	uint16_t data_len, uchar_t *data_bufp)
18679 {
18680 	struct scsi_extended_sense	sense_buf;
18681 	union scsi_cdb		cdb;
18682 	struct uscsi_cmd	ucmd_buf;
18683 	int			status;
18684 	int			no_caller_buf = FALSE;
18685 
18686 	ASSERT(un != NULL);
18687 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18688 	ASSERT((usr_cmd == SD_READ_KEYS) || (usr_cmd == SD_READ_RESV));
18689 
18690 	SD_TRACE(SD_LOG_IO, un,
18691 	    "sd_send_scsi_PERSISTENT_RESERVE_IN: entry: un:0x%p\n", un);
18692 
18693 	bzero(&cdb, sizeof (cdb));
18694 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18695 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18696 	if (data_bufp == NULL) {
18697 		/* Allocate a default buf if the caller did not give one */
18698 		ASSERT(data_len == 0);
18699 		data_len  = MHIOC_RESV_KEY_SIZE;
18700 		data_bufp = kmem_zalloc(MHIOC_RESV_KEY_SIZE, KM_SLEEP);
18701 		no_caller_buf = TRUE;
18702 	}
18703 
18704 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_IN;
18705 	cdb.cdb_opaque[1] = usr_cmd;
18706 	FORMG1COUNT(&cdb, data_len);
18707 
18708 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18709 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18710 	ucmd_buf.uscsi_bufaddr	= (caddr_t)data_bufp;
18711 	ucmd_buf.uscsi_buflen	= data_len;
18712 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18713 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18714 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
18715 	ucmd_buf.uscsi_timeout	= 60;
18716 
18717 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18718 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18719 
18720 	switch (status) {
18721 	case 0:
18722 		break;	/* Success! */
18723 	case EIO:
18724 		switch (ucmd_buf.uscsi_status) {
18725 		case STATUS_RESERVATION_CONFLICT:
18726 			status = EACCES;
18727 			break;
18728 		case STATUS_CHECK:
18729 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18730 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18731 			    KEY_ILLEGAL_REQUEST)) {
18732 				status = ENOTSUP;
18733 			}
18734 			break;
18735 		default:
18736 			break;
18737 		}
18738 		break;
18739 	default:
18740 		break;
18741 	}
18742 
18743 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_IN: exit\n");
18744 
18745 	if (no_caller_buf == TRUE) {
18746 		kmem_free(data_bufp, data_len);
18747 	}
18748 
18749 	return (status);
18750 }
18751 
18752 
18753 /*
18754  *    Function: sd_send_scsi_PERSISTENT_RESERVE_OUT
18755  *
18756  * Description: This routine is the driver entry point for handling CD-ROM
18757  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS,
18758  *		MHIOCGRP_INRESV) by sending the SCSI-3 PROUT commands to the
18759  *		device.
18760  *
18761  *   Arguments: un  -   Pointer to soft state struct for the target.
18762  *		usr_cmd SCSI-3 reservation facility command (one of
18763  *			SD_SCSI3_REGISTER, SD_SCSI3_RESERVE, SD_SCSI3_RELEASE,
18764  *			SD_SCSI3_PREEMPTANDABORT)
18765  *		usr_bufp - user provided pointer register, reserve descriptor or
18766  *			preempt and abort structure (mhioc_register_t,
18767  *                      mhioc_resv_desc_t, mhioc_preemptandabort_t)
18768  *
18769  * Return Code: 0   - Success
18770  *		EACCES
18771  *		ENOTSUP
18772  *		errno return code from sd_send_scsi_cmd()
18773  *
18774  *     Context: Can sleep. Does not return until command is completed.
18775  */
18776 
18777 static int
18778 sd_send_scsi_PERSISTENT_RESERVE_OUT(struct sd_lun *un, uchar_t usr_cmd,
18779 	uchar_t	*usr_bufp)
18780 {
18781 	struct scsi_extended_sense	sense_buf;
18782 	union scsi_cdb		cdb;
18783 	struct uscsi_cmd	ucmd_buf;
18784 	int			status;
18785 	uchar_t			data_len = sizeof (sd_prout_t);
18786 	sd_prout_t		*prp;
18787 
18788 	ASSERT(un != NULL);
18789 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18790 	ASSERT(data_len == 24);	/* required by scsi spec */
18791 
18792 	SD_TRACE(SD_LOG_IO, un,
18793 	    "sd_send_scsi_PERSISTENT_RESERVE_OUT: entry: un:0x%p\n", un);
18794 
18795 	if (usr_bufp == NULL) {
18796 		return (EINVAL);
18797 	}
18798 
18799 	bzero(&cdb, sizeof (cdb));
18800 	bzero(&ucmd_buf, sizeof (ucmd_buf));
18801 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
18802 	prp = kmem_zalloc(data_len, KM_SLEEP);
18803 
18804 	cdb.scc_cmd = SCMD_PERSISTENT_RESERVE_OUT;
18805 	cdb.cdb_opaque[1] = usr_cmd;
18806 	FORMG1COUNT(&cdb, data_len);
18807 
18808 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
18809 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
18810 	ucmd_buf.uscsi_bufaddr	= (caddr_t)prp;
18811 	ucmd_buf.uscsi_buflen	= data_len;
18812 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
18813 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
18814 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
18815 	ucmd_buf.uscsi_timeout	= 60;
18816 
18817 	switch (usr_cmd) {
18818 	case SD_SCSI3_REGISTER: {
18819 		mhioc_register_t *ptr = (mhioc_register_t *)usr_bufp;
18820 
18821 		bcopy(ptr->oldkey.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18822 		bcopy(ptr->newkey.key, prp->service_key,
18823 		    MHIOC_RESV_KEY_SIZE);
18824 		prp->aptpl = ptr->aptpl;
18825 		break;
18826 	}
18827 	case SD_SCSI3_RESERVE:
18828 	case SD_SCSI3_RELEASE: {
18829 		mhioc_resv_desc_t *ptr = (mhioc_resv_desc_t *)usr_bufp;
18830 
18831 		bcopy(ptr->key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18832 		prp->scope_address = BE_32(ptr->scope_specific_addr);
18833 		cdb.cdb_opaque[2] = ptr->type;
18834 		break;
18835 	}
18836 	case SD_SCSI3_PREEMPTANDABORT: {
18837 		mhioc_preemptandabort_t *ptr =
18838 		    (mhioc_preemptandabort_t *)usr_bufp;
18839 
18840 		bcopy(ptr->resvdesc.key.key, prp->res_key, MHIOC_RESV_KEY_SIZE);
18841 		bcopy(ptr->victim_key.key, prp->service_key,
18842 		    MHIOC_RESV_KEY_SIZE);
18843 		prp->scope_address = BE_32(ptr->resvdesc.scope_specific_addr);
18844 		cdb.cdb_opaque[2] = ptr->resvdesc.type;
18845 		ucmd_buf.uscsi_flags |= USCSI_HEAD;
18846 		break;
18847 	}
18848 	case SD_SCSI3_REGISTERANDIGNOREKEY:
18849 	{
18850 		mhioc_registerandignorekey_t *ptr;
18851 		ptr = (mhioc_registerandignorekey_t *)usr_bufp;
18852 		bcopy(ptr->newkey.key,
18853 		    prp->service_key, MHIOC_RESV_KEY_SIZE);
18854 		prp->aptpl = ptr->aptpl;
18855 		break;
18856 	}
18857 	default:
18858 		ASSERT(FALSE);
18859 		break;
18860 	}
18861 
18862 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
18863 	    UIO_SYSSPACE, SD_PATH_STANDARD);
18864 
18865 	switch (status) {
18866 	case 0:
18867 		break;	/* Success! */
18868 	case EIO:
18869 		switch (ucmd_buf.uscsi_status) {
18870 		case STATUS_RESERVATION_CONFLICT:
18871 			status = EACCES;
18872 			break;
18873 		case STATUS_CHECK:
18874 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
18875 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
18876 			    KEY_ILLEGAL_REQUEST)) {
18877 				status = ENOTSUP;
18878 			}
18879 			break;
18880 		default:
18881 			break;
18882 		}
18883 		break;
18884 	default:
18885 		break;
18886 	}
18887 
18888 	kmem_free(prp, data_len);
18889 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_PERSISTENT_RESERVE_OUT: exit\n");
18890 	return (status);
18891 }
18892 
18893 
18894 /*
18895  *    Function: sd_send_scsi_SYNCHRONIZE_CACHE
18896  *
18897  * Description: Issues a scsi SYNCHRONIZE CACHE command to the target
18898  *
18899  *   Arguments: un - pointer to the target's soft state struct
18900  *              dkc - pointer to the callback structure
18901  *
18902  * Return Code: 0 - success
18903  *		errno-type error code
18904  *
18905  *     Context: kernel thread context only.
18906  *
18907  *  _______________________________________________________________
18908  * | dkc_flag &   | dkc_callback | DKIOCFLUSHWRITECACHE            |
18909  * |FLUSH_VOLATILE|              | operation                       |
18910  * |______________|______________|_________________________________|
18911  * | 0            | NULL         | Synchronous flush on both       |
18912  * |              |              | volatile and non-volatile cache |
18913  * |______________|______________|_________________________________|
18914  * | 1            | NULL         | Synchronous flush on volatile   |
18915  * |              |              | cache; disk drivers may suppress|
18916  * |              |              | flush if disk table indicates   |
18917  * |              |              | non-volatile cache              |
18918  * |______________|______________|_________________________________|
18919  * | 0            | !NULL        | Asynchronous flush on both      |
18920  * |              |              | volatile and non-volatile cache;|
18921  * |______________|______________|_________________________________|
18922  * | 1            | !NULL        | Asynchronous flush on volatile  |
18923  * |              |              | cache; disk drivers may suppress|
18924  * |              |              | flush if disk table indicates   |
18925  * |              |              | non-volatile cache              |
18926  * |______________|______________|_________________________________|
18927  *
18928  */
18929 
18930 static int
18931 sd_send_scsi_SYNCHRONIZE_CACHE(struct sd_lun *un, struct dk_callback *dkc)
18932 {
18933 	struct sd_uscsi_info	*uip;
18934 	struct uscsi_cmd	*uscmd;
18935 	union scsi_cdb		*cdb;
18936 	struct buf		*bp;
18937 	int			rval = 0;
18938 	int			is_async;
18939 
18940 	SD_TRACE(SD_LOG_IO, un,
18941 	    "sd_send_scsi_SYNCHRONIZE_CACHE: entry: un:0x%p\n", un);
18942 
18943 	ASSERT(un != NULL);
18944 	ASSERT(!mutex_owned(SD_MUTEX(un)));
18945 
18946 	if (dkc == NULL || dkc->dkc_callback == NULL) {
18947 		is_async = FALSE;
18948 	} else {
18949 		is_async = TRUE;
18950 	}
18951 
18952 	mutex_enter(SD_MUTEX(un));
18953 	/* check whether cache flush should be suppressed */
18954 	if (un->un_f_suppress_cache_flush == TRUE) {
18955 		mutex_exit(SD_MUTEX(un));
18956 		/*
18957 		 * suppress the cache flush if the device is told to do
18958 		 * so by sd.conf or disk table
18959 		 */
18960 		SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_SYNCHRONIZE_CACHE: \
18961 		    skip the cache flush since suppress_cache_flush is %d!\n",
18962 		    un->un_f_suppress_cache_flush);
18963 
18964 		if (is_async == TRUE) {
18965 			/* invoke callback for asynchronous flush */
18966 			(*dkc->dkc_callback)(dkc->dkc_cookie, 0);
18967 		}
18968 		return (rval);
18969 	}
18970 	mutex_exit(SD_MUTEX(un));
18971 
18972 	/*
18973 	 * check dkc_flag & FLUSH_VOLATILE so SYNC_NV bit can be
18974 	 * set properly
18975 	 */
18976 	cdb = kmem_zalloc(CDB_GROUP1, KM_SLEEP);
18977 	cdb->scc_cmd = SCMD_SYNCHRONIZE_CACHE;
18978 
18979 	mutex_enter(SD_MUTEX(un));
18980 	if (dkc != NULL && un->un_f_sync_nv_supported &&
18981 	    (dkc->dkc_flag & FLUSH_VOLATILE)) {
18982 		/*
18983 		 * if the device supports SYNC_NV bit, turn on
18984 		 * the SYNC_NV bit to only flush volatile cache
18985 		 */
18986 		cdb->cdb_un.tag |= SD_SYNC_NV_BIT;
18987 	}
18988 	mutex_exit(SD_MUTEX(un));
18989 
18990 	/*
18991 	 * First get some memory for the uscsi_cmd struct and cdb
18992 	 * and initialize for SYNCHRONIZE_CACHE cmd.
18993 	 */
18994 	uscmd = kmem_zalloc(sizeof (struct uscsi_cmd), KM_SLEEP);
18995 	uscmd->uscsi_cdblen = CDB_GROUP1;
18996 	uscmd->uscsi_cdb = (caddr_t)cdb;
18997 	uscmd->uscsi_bufaddr = NULL;
18998 	uscmd->uscsi_buflen = 0;
18999 	uscmd->uscsi_rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
19000 	uscmd->uscsi_rqlen = SENSE_LENGTH;
19001 	uscmd->uscsi_rqresid = SENSE_LENGTH;
19002 	uscmd->uscsi_flags = USCSI_RQENABLE | USCSI_SILENT;
19003 	uscmd->uscsi_timeout = sd_io_time;
19004 
19005 	/*
19006 	 * Allocate an sd_uscsi_info struct and fill it with the info
19007 	 * needed by sd_initpkt_for_uscsi().  Then put the pointer into
19008 	 * b_private in the buf for sd_initpkt_for_uscsi().  Note that
19009 	 * since we allocate the buf here in this function, we do not
19010 	 * need to preserve the prior contents of b_private.
19011 	 * The sd_uscsi_info struct is also used by sd_uscsi_strategy()
19012 	 */
19013 	uip = kmem_zalloc(sizeof (struct sd_uscsi_info), KM_SLEEP);
19014 	uip->ui_flags = SD_PATH_DIRECT;
19015 	uip->ui_cmdp  = uscmd;
19016 
19017 	bp = getrbuf(KM_SLEEP);
19018 	bp->b_private = uip;
19019 
19020 	/*
19021 	 * Setup buffer to carry uscsi request.
19022 	 */
19023 	bp->b_flags  = B_BUSY;
19024 	bp->b_bcount = 0;
19025 	bp->b_blkno  = 0;
19026 
19027 	if (is_async == TRUE) {
19028 		bp->b_iodone = sd_send_scsi_SYNCHRONIZE_CACHE_biodone;
19029 		uip->ui_dkc = *dkc;
19030 	}
19031 
19032 	bp->b_edev = SD_GET_DEV(un);
19033 	bp->b_dev = cmpdev(bp->b_edev);	/* maybe unnecessary? */
19034 
19035 	(void) sd_uscsi_strategy(bp);
19036 
19037 	/*
19038 	 * If synchronous request, wait for completion
19039 	 * If async just return and let b_iodone callback
19040 	 * cleanup.
19041 	 * NOTE: On return, u_ncmds_in_driver will be decremented,
19042 	 * but it was also incremented in sd_uscsi_strategy(), so
19043 	 * we should be ok.
19044 	 */
19045 	if (is_async == FALSE) {
19046 		(void) biowait(bp);
19047 		rval = sd_send_scsi_SYNCHRONIZE_CACHE_biodone(bp);
19048 	}
19049 
19050 	return (rval);
19051 }
19052 
19053 
19054 static int
19055 sd_send_scsi_SYNCHRONIZE_CACHE_biodone(struct buf *bp)
19056 {
19057 	struct sd_uscsi_info *uip;
19058 	struct uscsi_cmd *uscmd;
19059 	uint8_t *sense_buf;
19060 	struct sd_lun *un;
19061 	int status;
19062 	union scsi_cdb *cdb;
19063 
19064 	uip = (struct sd_uscsi_info *)(bp->b_private);
19065 	ASSERT(uip != NULL);
19066 
19067 	uscmd = uip->ui_cmdp;
19068 	ASSERT(uscmd != NULL);
19069 
19070 	sense_buf = (uint8_t *)uscmd->uscsi_rqbuf;
19071 	ASSERT(sense_buf != NULL);
19072 
19073 	un = ddi_get_soft_state(sd_state, SD_GET_INSTANCE_FROM_BUF(bp));
19074 	ASSERT(un != NULL);
19075 
19076 	cdb = (union scsi_cdb *)uscmd->uscsi_cdb;
19077 
19078 	status = geterror(bp);
19079 	switch (status) {
19080 	case 0:
19081 		break;	/* Success! */
19082 	case EIO:
19083 		switch (uscmd->uscsi_status) {
19084 		case STATUS_RESERVATION_CONFLICT:
19085 			/* Ignore reservation conflict */
19086 			status = 0;
19087 			goto done;
19088 
19089 		case STATUS_CHECK:
19090 			if ((uscmd->uscsi_rqstatus == STATUS_GOOD) &&
19091 			    (scsi_sense_key(sense_buf) ==
19092 			    KEY_ILLEGAL_REQUEST)) {
19093 				/* Ignore Illegal Request error */
19094 				if (cdb->cdb_un.tag&SD_SYNC_NV_BIT) {
19095 					mutex_enter(SD_MUTEX(un));
19096 					un->un_f_sync_nv_supported = FALSE;
19097 					mutex_exit(SD_MUTEX(un));
19098 					status = 0;
19099 					SD_TRACE(SD_LOG_IO, un,
19100 					    "un_f_sync_nv_supported \
19101 					    is set to false.\n");
19102 					goto done;
19103 				}
19104 
19105 				mutex_enter(SD_MUTEX(un));
19106 				un->un_f_sync_cache_supported = FALSE;
19107 				mutex_exit(SD_MUTEX(un));
19108 				SD_TRACE(SD_LOG_IO, un,
19109 				    "sd_send_scsi_SYNCHRONIZE_CACHE_biodone: \
19110 				    un_f_sync_cache_supported set to false \
19111 				    with asc = %x, ascq = %x\n",
19112 				    scsi_sense_asc(sense_buf),
19113 				    scsi_sense_ascq(sense_buf));
19114 				status = ENOTSUP;
19115 				goto done;
19116 			}
19117 			break;
19118 		default:
19119 			break;
19120 		}
19121 		/* FALLTHRU */
19122 	default:
19123 		/*
19124 		 * Don't log an error message if this device
19125 		 * has removable media.
19126 		 */
19127 		if (!un->un_f_has_removable_media) {
19128 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
19129 			    "SYNCHRONIZE CACHE command failed (%d)\n", status);
19130 		}
19131 		break;
19132 	}
19133 
19134 done:
19135 	if (uip->ui_dkc.dkc_callback != NULL) {
19136 		(*uip->ui_dkc.dkc_callback)(uip->ui_dkc.dkc_cookie, status);
19137 	}
19138 
19139 	ASSERT((bp->b_flags & B_REMAPPED) == 0);
19140 	freerbuf(bp);
19141 	kmem_free(uip, sizeof (struct sd_uscsi_info));
19142 	kmem_free(uscmd->uscsi_rqbuf, SENSE_LENGTH);
19143 	kmem_free(uscmd->uscsi_cdb, (size_t)uscmd->uscsi_cdblen);
19144 	kmem_free(uscmd, sizeof (struct uscsi_cmd));
19145 
19146 	return (status);
19147 }
19148 
19149 
19150 /*
19151  *    Function: sd_send_scsi_GET_CONFIGURATION
19152  *
19153  * Description: Issues the get configuration command to the device.
19154  *		Called from sd_check_for_writable_cd & sd_get_media_info
19155  *		caller needs to ensure that buflen = SD_PROFILE_HEADER_LEN
19156  *   Arguments: un
19157  *		ucmdbuf
19158  *		rqbuf
19159  *		rqbuflen
19160  *		bufaddr
19161  *		buflen
19162  *		path_flag
19163  *
19164  * Return Code: 0   - Success
19165  *		errno return code from sd_send_scsi_cmd()
19166  *
19167  *     Context: Can sleep. Does not return until command is completed.
19168  *
19169  */
19170 
19171 static int
19172 sd_send_scsi_GET_CONFIGURATION(struct sd_lun *un, struct uscsi_cmd *ucmdbuf,
19173 	uchar_t *rqbuf, uint_t rqbuflen, uchar_t *bufaddr, uint_t buflen,
19174 	int path_flag)
19175 {
19176 	char	cdb[CDB_GROUP1];
19177 	int	status;
19178 
19179 	ASSERT(un != NULL);
19180 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19181 	ASSERT(bufaddr != NULL);
19182 	ASSERT(ucmdbuf != NULL);
19183 	ASSERT(rqbuf != NULL);
19184 
19185 	SD_TRACE(SD_LOG_IO, un,
19186 	    "sd_send_scsi_GET_CONFIGURATION: entry: un:0x%p\n", un);
19187 
19188 	bzero(cdb, sizeof (cdb));
19189 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
19190 	bzero(rqbuf, rqbuflen);
19191 	bzero(bufaddr, buflen);
19192 
19193 	/*
19194 	 * Set up cdb field for the get configuration command.
19195 	 */
19196 	cdb[0] = SCMD_GET_CONFIGURATION;
19197 	cdb[1] = 0x02;  /* Requested Type */
19198 	cdb[8] = SD_PROFILE_HEADER_LEN;
19199 	ucmdbuf->uscsi_cdb = cdb;
19200 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
19201 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
19202 	ucmdbuf->uscsi_buflen = buflen;
19203 	ucmdbuf->uscsi_timeout = sd_io_time;
19204 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
19205 	ucmdbuf->uscsi_rqlen = rqbuflen;
19206 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
19207 
19208 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, FKIOCTL,
19209 	    UIO_SYSSPACE, path_flag);
19210 
19211 	switch (status) {
19212 	case 0:
19213 		break;  /* Success! */
19214 	case EIO:
19215 		switch (ucmdbuf->uscsi_status) {
19216 		case STATUS_RESERVATION_CONFLICT:
19217 			status = EACCES;
19218 			break;
19219 		default:
19220 			break;
19221 		}
19222 		break;
19223 	default:
19224 		break;
19225 	}
19226 
19227 	if (status == 0) {
19228 		SD_DUMP_MEMORY(un, SD_LOG_IO,
19229 		    "sd_send_scsi_GET_CONFIGURATION: data",
19230 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
19231 	}
19232 
19233 	SD_TRACE(SD_LOG_IO, un,
19234 	    "sd_send_scsi_GET_CONFIGURATION: exit\n");
19235 
19236 	return (status);
19237 }
19238 
19239 /*
19240  *    Function: sd_send_scsi_feature_GET_CONFIGURATION
19241  *
19242  * Description: Issues the get configuration command to the device to
19243  *              retrieve a specific feature. Called from
19244  *		sd_check_for_writable_cd & sd_set_mmc_caps.
19245  *   Arguments: un
19246  *              ucmdbuf
19247  *              rqbuf
19248  *              rqbuflen
19249  *              bufaddr
19250  *              buflen
19251  *		feature
19252  *
19253  * Return Code: 0   - Success
19254  *              errno return code from sd_send_scsi_cmd()
19255  *
19256  *     Context: Can sleep. Does not return until command is completed.
19257  *
19258  */
19259 static int
19260 sd_send_scsi_feature_GET_CONFIGURATION(struct sd_lun *un,
19261 	struct uscsi_cmd *ucmdbuf, uchar_t *rqbuf, uint_t rqbuflen,
19262 	uchar_t *bufaddr, uint_t buflen, char feature, int path_flag)
19263 {
19264 	char    cdb[CDB_GROUP1];
19265 	int	status;
19266 
19267 	ASSERT(un != NULL);
19268 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19269 	ASSERT(bufaddr != NULL);
19270 	ASSERT(ucmdbuf != NULL);
19271 	ASSERT(rqbuf != NULL);
19272 
19273 	SD_TRACE(SD_LOG_IO, un,
19274 	    "sd_send_scsi_feature_GET_CONFIGURATION: entry: un:0x%p\n", un);
19275 
19276 	bzero(cdb, sizeof (cdb));
19277 	bzero(ucmdbuf, sizeof (struct uscsi_cmd));
19278 	bzero(rqbuf, rqbuflen);
19279 	bzero(bufaddr, buflen);
19280 
19281 	/*
19282 	 * Set up cdb field for the get configuration command.
19283 	 */
19284 	cdb[0] = SCMD_GET_CONFIGURATION;
19285 	cdb[1] = 0x02;  /* Requested Type */
19286 	cdb[3] = feature;
19287 	cdb[8] = buflen;
19288 	ucmdbuf->uscsi_cdb = cdb;
19289 	ucmdbuf->uscsi_cdblen = CDB_GROUP1;
19290 	ucmdbuf->uscsi_bufaddr = (caddr_t)bufaddr;
19291 	ucmdbuf->uscsi_buflen = buflen;
19292 	ucmdbuf->uscsi_timeout = sd_io_time;
19293 	ucmdbuf->uscsi_rqbuf = (caddr_t)rqbuf;
19294 	ucmdbuf->uscsi_rqlen = rqbuflen;
19295 	ucmdbuf->uscsi_flags = USCSI_RQENABLE|USCSI_SILENT|USCSI_READ;
19296 
19297 	status = sd_send_scsi_cmd(SD_GET_DEV(un), ucmdbuf, FKIOCTL,
19298 	    UIO_SYSSPACE, path_flag);
19299 
19300 	switch (status) {
19301 	case 0:
19302 		break;  /* Success! */
19303 	case EIO:
19304 		switch (ucmdbuf->uscsi_status) {
19305 		case STATUS_RESERVATION_CONFLICT:
19306 			status = EACCES;
19307 			break;
19308 		default:
19309 			break;
19310 		}
19311 		break;
19312 	default:
19313 		break;
19314 	}
19315 
19316 	if (status == 0) {
19317 		SD_DUMP_MEMORY(un, SD_LOG_IO,
19318 		    "sd_send_scsi_feature_GET_CONFIGURATION: data",
19319 		    (uchar_t *)bufaddr, SD_PROFILE_HEADER_LEN, SD_LOG_HEX);
19320 	}
19321 
19322 	SD_TRACE(SD_LOG_IO, un,
19323 	    "sd_send_scsi_feature_GET_CONFIGURATION: exit\n");
19324 
19325 	return (status);
19326 }
19327 
19328 
19329 /*
19330  *    Function: sd_send_scsi_MODE_SENSE
19331  *
19332  * Description: Utility function for issuing a scsi MODE SENSE command.
19333  *		Note: This routine uses a consistent implementation for Group0,
19334  *		Group1, and Group2 commands across all platforms. ATAPI devices
19335  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
19336  *
19337  *   Arguments: un - pointer to the softstate struct for the target.
19338  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
19339  *			  CDB_GROUP[1|2] (10 byte).
19340  *		bufaddr - buffer for page data retrieved from the target.
19341  *		buflen - size of page to be retrieved.
19342  *		page_code - page code of data to be retrieved from the target.
19343  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19344  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19345  *			to use the USCSI "direct" chain and bypass the normal
19346  *			command waitq.
19347  *
19348  * Return Code: 0   - Success
19349  *		errno return code from sd_send_scsi_cmd()
19350  *
19351  *     Context: Can sleep. Does not return until command is completed.
19352  */
19353 
19354 static int
19355 sd_send_scsi_MODE_SENSE(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
19356 	size_t buflen,  uchar_t page_code, int path_flag)
19357 {
19358 	struct	scsi_extended_sense	sense_buf;
19359 	union scsi_cdb		cdb;
19360 	struct uscsi_cmd	ucmd_buf;
19361 	int			status;
19362 	int			headlen;
19363 
19364 	ASSERT(un != NULL);
19365 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19366 	ASSERT(bufaddr != NULL);
19367 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
19368 	    (cdbsize == CDB_GROUP2));
19369 
19370 	SD_TRACE(SD_LOG_IO, un,
19371 	    "sd_send_scsi_MODE_SENSE: entry: un:0x%p\n", un);
19372 
19373 	bzero(&cdb, sizeof (cdb));
19374 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19375 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19376 	bzero(bufaddr, buflen);
19377 
19378 	if (cdbsize == CDB_GROUP0) {
19379 		cdb.scc_cmd = SCMD_MODE_SENSE;
19380 		cdb.cdb_opaque[2] = page_code;
19381 		FORMG0COUNT(&cdb, buflen);
19382 		headlen = MODE_HEADER_LENGTH;
19383 	} else {
19384 		cdb.scc_cmd = SCMD_MODE_SENSE_G1;
19385 		cdb.cdb_opaque[2] = page_code;
19386 		FORMG1COUNT(&cdb, buflen);
19387 		headlen = MODE_HEADER_LENGTH_GRP2;
19388 	}
19389 
19390 	ASSERT(headlen <= buflen);
19391 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19392 
19393 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19394 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19395 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19396 	ucmd_buf.uscsi_buflen	= buflen;
19397 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19398 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19399 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19400 	ucmd_buf.uscsi_timeout	= 60;
19401 
19402 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19403 	    UIO_SYSSPACE, path_flag);
19404 
19405 	switch (status) {
19406 	case 0:
19407 		/*
19408 		 * sr_check_wp() uses 0x3f page code and check the header of
19409 		 * mode page to determine if target device is write-protected.
19410 		 * But some USB devices return 0 bytes for 0x3f page code. For
19411 		 * this case, make sure that mode page header is returned at
19412 		 * least.
19413 		 */
19414 		if (buflen - ucmd_buf.uscsi_resid <  headlen)
19415 			status = EIO;
19416 		break;	/* Success! */
19417 	case EIO:
19418 		switch (ucmd_buf.uscsi_status) {
19419 		case STATUS_RESERVATION_CONFLICT:
19420 			status = EACCES;
19421 			break;
19422 		default:
19423 			break;
19424 		}
19425 		break;
19426 	default:
19427 		break;
19428 	}
19429 
19430 	if (status == 0) {
19431 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SENSE: data",
19432 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19433 	}
19434 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SENSE: exit\n");
19435 
19436 	return (status);
19437 }
19438 
19439 
19440 /*
19441  *    Function: sd_send_scsi_MODE_SELECT
19442  *
19443  * Description: Utility function for issuing a scsi MODE SELECT command.
19444  *		Note: This routine uses a consistent implementation for Group0,
19445  *		Group1, and Group2 commands across all platforms. ATAPI devices
19446  *		use Group 1 Read/Write commands and Group 2 Mode Sense/Select
19447  *
19448  *   Arguments: un - pointer to the softstate struct for the target.
19449  *		cdbsize - size CDB to be used (CDB_GROUP0 (6 byte), or
19450  *			  CDB_GROUP[1|2] (10 byte).
19451  *		bufaddr - buffer for page data retrieved from the target.
19452  *		buflen - size of page to be retrieved.
19453  *		save_page - boolean to determin if SP bit should be set.
19454  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19455  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19456  *			to use the USCSI "direct" chain and bypass the normal
19457  *			command waitq.
19458  *
19459  * Return Code: 0   - Success
19460  *		errno return code from sd_send_scsi_cmd()
19461  *
19462  *     Context: Can sleep. Does not return until command is completed.
19463  */
19464 
19465 static int
19466 sd_send_scsi_MODE_SELECT(struct sd_lun *un, int cdbsize, uchar_t *bufaddr,
19467 	size_t buflen,  uchar_t save_page, int path_flag)
19468 {
19469 	struct	scsi_extended_sense	sense_buf;
19470 	union scsi_cdb		cdb;
19471 	struct uscsi_cmd	ucmd_buf;
19472 	int			status;
19473 
19474 	ASSERT(un != NULL);
19475 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19476 	ASSERT(bufaddr != NULL);
19477 	ASSERT((cdbsize == CDB_GROUP0) || (cdbsize == CDB_GROUP1) ||
19478 	    (cdbsize == CDB_GROUP2));
19479 
19480 	SD_TRACE(SD_LOG_IO, un,
19481 	    "sd_send_scsi_MODE_SELECT: entry: un:0x%p\n", un);
19482 
19483 	bzero(&cdb, sizeof (cdb));
19484 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19485 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19486 
19487 	/* Set the PF bit for many third party drives */
19488 	cdb.cdb_opaque[1] = 0x10;
19489 
19490 	/* Set the savepage(SP) bit if given */
19491 	if (save_page == SD_SAVE_PAGE) {
19492 		cdb.cdb_opaque[1] |= 0x01;
19493 	}
19494 
19495 	if (cdbsize == CDB_GROUP0) {
19496 		cdb.scc_cmd = SCMD_MODE_SELECT;
19497 		FORMG0COUNT(&cdb, buflen);
19498 	} else {
19499 		cdb.scc_cmd = SCMD_MODE_SELECT_G1;
19500 		FORMG1COUNT(&cdb, buflen);
19501 	}
19502 
19503 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19504 
19505 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19506 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19507 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19508 	ucmd_buf.uscsi_buflen	= buflen;
19509 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19510 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19511 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_WRITE | USCSI_SILENT;
19512 	ucmd_buf.uscsi_timeout	= 60;
19513 
19514 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19515 	    UIO_SYSSPACE, path_flag);
19516 
19517 	switch (status) {
19518 	case 0:
19519 		break;	/* Success! */
19520 	case EIO:
19521 		switch (ucmd_buf.uscsi_status) {
19522 		case STATUS_RESERVATION_CONFLICT:
19523 			status = EACCES;
19524 			break;
19525 		default:
19526 			break;
19527 		}
19528 		break;
19529 	default:
19530 		break;
19531 	}
19532 
19533 	if (status == 0) {
19534 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_MODE_SELECT: data",
19535 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19536 	}
19537 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_MODE_SELECT: exit\n");
19538 
19539 	return (status);
19540 }
19541 
19542 
19543 /*
19544  *    Function: sd_send_scsi_RDWR
19545  *
19546  * Description: Issue a scsi READ or WRITE command with the given parameters.
19547  *
19548  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19549  *		cmd:	 SCMD_READ or SCMD_WRITE
19550  *		bufaddr: Address of caller's buffer to receive the RDWR data
19551  *		buflen:  Length of caller's buffer receive the RDWR data.
19552  *		start_block: Block number for the start of the RDWR operation.
19553  *			 (Assumes target-native block size.)
19554  *		residp:  Pointer to variable to receive the redisual of the
19555  *			 RDWR operation (may be NULL of no residual requested).
19556  *		path_flag - SD_PATH_DIRECT to use the USCSI "direct" chain and
19557  *			the normal command waitq, or SD_PATH_DIRECT_PRIORITY
19558  *			to use the USCSI "direct" chain and bypass the normal
19559  *			command waitq.
19560  *
19561  * Return Code: 0   - Success
19562  *		errno return code from sd_send_scsi_cmd()
19563  *
19564  *     Context: Can sleep. Does not return until command is completed.
19565  */
19566 
19567 static int
19568 sd_send_scsi_RDWR(struct sd_lun *un, uchar_t cmd, void *bufaddr,
19569 	size_t buflen, daddr_t start_block, int path_flag)
19570 {
19571 	struct	scsi_extended_sense	sense_buf;
19572 	union scsi_cdb		cdb;
19573 	struct uscsi_cmd	ucmd_buf;
19574 	uint32_t		block_count;
19575 	int			status;
19576 	int			cdbsize;
19577 	uchar_t			flag;
19578 
19579 	ASSERT(un != NULL);
19580 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19581 	ASSERT(bufaddr != NULL);
19582 	ASSERT((cmd == SCMD_READ) || (cmd == SCMD_WRITE));
19583 
19584 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: entry: un:0x%p\n", un);
19585 
19586 	if (un->un_f_tgt_blocksize_is_valid != TRUE) {
19587 		return (EINVAL);
19588 	}
19589 
19590 	mutex_enter(SD_MUTEX(un));
19591 	block_count = SD_BYTES2TGTBLOCKS(un, buflen);
19592 	mutex_exit(SD_MUTEX(un));
19593 
19594 	flag = (cmd == SCMD_READ) ? USCSI_READ : USCSI_WRITE;
19595 
19596 	SD_INFO(SD_LOG_IO, un, "sd_send_scsi_RDWR: "
19597 	    "bufaddr:0x%p buflen:0x%x start_block:0x%p block_count:0x%x\n",
19598 	    bufaddr, buflen, start_block, block_count);
19599 
19600 	bzero(&cdb, sizeof (cdb));
19601 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19602 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19603 
19604 	/* Compute CDB size to use */
19605 	if (start_block > 0xffffffff)
19606 		cdbsize = CDB_GROUP4;
19607 	else if ((start_block & 0xFFE00000) ||
19608 	    (un->un_f_cfg_is_atapi == TRUE))
19609 		cdbsize = CDB_GROUP1;
19610 	else
19611 		cdbsize = CDB_GROUP0;
19612 
19613 	switch (cdbsize) {
19614 	case CDB_GROUP0:	/* 6-byte CDBs */
19615 		cdb.scc_cmd = cmd;
19616 		FORMG0ADDR(&cdb, start_block);
19617 		FORMG0COUNT(&cdb, block_count);
19618 		break;
19619 	case CDB_GROUP1:	/* 10-byte CDBs */
19620 		cdb.scc_cmd = cmd | SCMD_GROUP1;
19621 		FORMG1ADDR(&cdb, start_block);
19622 		FORMG1COUNT(&cdb, block_count);
19623 		break;
19624 	case CDB_GROUP4:	/* 16-byte CDBs */
19625 		cdb.scc_cmd = cmd | SCMD_GROUP4;
19626 		FORMG4LONGADDR(&cdb, (uint64_t)start_block);
19627 		FORMG4COUNT(&cdb, block_count);
19628 		break;
19629 	case CDB_GROUP5:	/* 12-byte CDBs (currently unsupported) */
19630 	default:
19631 		/* All others reserved */
19632 		return (EINVAL);
19633 	}
19634 
19635 	/* Set LUN bit(s) in CDB if this is a SCSI-1 device */
19636 	SD_FILL_SCSI1_LUN_CDB(un, &cdb);
19637 
19638 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19639 	ucmd_buf.uscsi_cdblen	= (uchar_t)cdbsize;
19640 	ucmd_buf.uscsi_bufaddr	= bufaddr;
19641 	ucmd_buf.uscsi_buflen	= buflen;
19642 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19643 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19644 	ucmd_buf.uscsi_flags	= flag | USCSI_RQENABLE | USCSI_SILENT;
19645 	ucmd_buf.uscsi_timeout	= 60;
19646 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19647 	    UIO_SYSSPACE, path_flag);
19648 	switch (status) {
19649 	case 0:
19650 		break;	/* Success! */
19651 	case EIO:
19652 		switch (ucmd_buf.uscsi_status) {
19653 		case STATUS_RESERVATION_CONFLICT:
19654 			status = EACCES;
19655 			break;
19656 		default:
19657 			break;
19658 		}
19659 		break;
19660 	default:
19661 		break;
19662 	}
19663 
19664 	if (status == 0) {
19665 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_RDWR: data",
19666 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19667 	}
19668 
19669 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_RDWR: exit\n");
19670 
19671 	return (status);
19672 }
19673 
19674 
19675 /*
19676  *    Function: sd_send_scsi_LOG_SENSE
19677  *
19678  * Description: Issue a scsi LOG_SENSE command with the given parameters.
19679  *
19680  *   Arguments: un:      Pointer to the sd_lun struct for the target.
19681  *
19682  * Return Code: 0   - Success
19683  *		errno return code from sd_send_scsi_cmd()
19684  *
19685  *     Context: Can sleep. Does not return until command is completed.
19686  */
19687 
19688 static int
19689 sd_send_scsi_LOG_SENSE(struct sd_lun *un, uchar_t *bufaddr, uint16_t buflen,
19690 	uchar_t page_code, uchar_t page_control, uint16_t param_ptr,
19691 	int path_flag)
19692 
19693 {
19694 	struct	scsi_extended_sense	sense_buf;
19695 	union scsi_cdb		cdb;
19696 	struct uscsi_cmd	ucmd_buf;
19697 	int			status;
19698 
19699 	ASSERT(un != NULL);
19700 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19701 
19702 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: entry: un:0x%p\n", un);
19703 
19704 	bzero(&cdb, sizeof (cdb));
19705 	bzero(&ucmd_buf, sizeof (ucmd_buf));
19706 	bzero(&sense_buf, sizeof (struct scsi_extended_sense));
19707 
19708 	cdb.scc_cmd = SCMD_LOG_SENSE_G1;
19709 	cdb.cdb_opaque[2] = (page_control << 6) | page_code;
19710 	cdb.cdb_opaque[5] = (uchar_t)((param_ptr & 0xFF00) >> 8);
19711 	cdb.cdb_opaque[6] = (uchar_t)(param_ptr  & 0x00FF);
19712 	FORMG1COUNT(&cdb, buflen);
19713 
19714 	ucmd_buf.uscsi_cdb	= (char *)&cdb;
19715 	ucmd_buf.uscsi_cdblen	= CDB_GROUP1;
19716 	ucmd_buf.uscsi_bufaddr	= (caddr_t)bufaddr;
19717 	ucmd_buf.uscsi_buflen	= buflen;
19718 	ucmd_buf.uscsi_rqbuf	= (caddr_t)&sense_buf;
19719 	ucmd_buf.uscsi_rqlen	= sizeof (struct scsi_extended_sense);
19720 	ucmd_buf.uscsi_flags	= USCSI_RQENABLE | USCSI_READ | USCSI_SILENT;
19721 	ucmd_buf.uscsi_timeout	= 60;
19722 
19723 	status = sd_send_scsi_cmd(SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19724 	    UIO_SYSSPACE, path_flag);
19725 
19726 	switch (status) {
19727 	case 0:
19728 		break;
19729 	case EIO:
19730 		switch (ucmd_buf.uscsi_status) {
19731 		case STATUS_RESERVATION_CONFLICT:
19732 			status = EACCES;
19733 			break;
19734 		case STATUS_CHECK:
19735 			if ((ucmd_buf.uscsi_rqstatus == STATUS_GOOD) &&
19736 			    (scsi_sense_key((uint8_t *)&sense_buf) ==
19737 				KEY_ILLEGAL_REQUEST) &&
19738 			    (scsi_sense_asc((uint8_t *)&sense_buf) == 0x24)) {
19739 				/*
19740 				 * ASC 0x24: INVALID FIELD IN CDB
19741 				 */
19742 				switch (page_code) {
19743 				case START_STOP_CYCLE_PAGE:
19744 					/*
19745 					 * The start stop cycle counter is
19746 					 * implemented as page 0x31 in earlier
19747 					 * generation disks. In new generation
19748 					 * disks the start stop cycle counter is
19749 					 * implemented as page 0xE. To properly
19750 					 * handle this case if an attempt for
19751 					 * log page 0xE is made and fails we
19752 					 * will try again using page 0x31.
19753 					 *
19754 					 * Network storage BU committed to
19755 					 * maintain the page 0x31 for this
19756 					 * purpose and will not have any other
19757 					 * page implemented with page code 0x31
19758 					 * until all disks transition to the
19759 					 * standard page.
19760 					 */
19761 					mutex_enter(SD_MUTEX(un));
19762 					un->un_start_stop_cycle_page =
19763 					    START_STOP_CYCLE_VU_PAGE;
19764 					cdb.cdb_opaque[2] =
19765 					    (char)(page_control << 6) |
19766 					    un->un_start_stop_cycle_page;
19767 					mutex_exit(SD_MUTEX(un));
19768 					status = sd_send_scsi_cmd(
19769 					    SD_GET_DEV(un), &ucmd_buf, FKIOCTL,
19770 					    UIO_SYSSPACE, path_flag);
19771 
19772 					break;
19773 				case TEMPERATURE_PAGE:
19774 					status = ENOTTY;
19775 					break;
19776 				default:
19777 					break;
19778 				}
19779 			}
19780 			break;
19781 		default:
19782 			break;
19783 		}
19784 		break;
19785 	default:
19786 		break;
19787 	}
19788 
19789 	if (status == 0) {
19790 		SD_DUMP_MEMORY(un, SD_LOG_IO, "sd_send_scsi_LOG_SENSE: data",
19791 		    (uchar_t *)bufaddr, buflen, SD_LOG_HEX);
19792 	}
19793 
19794 	SD_TRACE(SD_LOG_IO, un, "sd_send_scsi_LOG_SENSE: exit\n");
19795 
19796 	return (status);
19797 }
19798 
19799 
19800 /*
19801  *    Function: sdioctl
19802  *
19803  * Description: Driver's ioctl(9e) entry point function.
19804  *
19805  *   Arguments: dev     - device number
19806  *		cmd     - ioctl operation to be performed
19807  *		arg     - user argument, contains data to be set or reference
19808  *			  parameter for get
19809  *		flag    - bit flag, indicating open settings, 32/64 bit type
19810  *		cred_p  - user credential pointer
19811  *		rval_p  - calling process return value (OPT)
19812  *
19813  * Return Code: EINVAL
19814  *		ENOTTY
19815  *		ENXIO
19816  *		EIO
19817  *		EFAULT
19818  *		ENOTSUP
19819  *		EPERM
19820  *
19821  *     Context: Called from the device switch at normal priority.
19822  */
19823 
19824 static int
19825 sdioctl(dev_t dev, int cmd, intptr_t arg, int flag, cred_t *cred_p, int *rval_p)
19826 {
19827 	struct sd_lun	*un = NULL;
19828 	int		err = 0;
19829 	int		i = 0;
19830 	cred_t		*cr;
19831 	int		tmprval = EINVAL;
19832 	int 		is_valid;
19833 
19834 	/*
19835 	 * All device accesses go thru sdstrategy where we check on suspend
19836 	 * status
19837 	 */
19838 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
19839 		return (ENXIO);
19840 	}
19841 
19842 	ASSERT(!mutex_owned(SD_MUTEX(un)));
19843 
19844 
19845 	is_valid = SD_IS_VALID_LABEL(un);
19846 
19847 	/*
19848 	 * Moved this wait from sd_uscsi_strategy to here for
19849 	 * reasons of deadlock prevention. Internal driver commands,
19850 	 * specifically those to change a devices power level, result
19851 	 * in a call to sd_uscsi_strategy.
19852 	 */
19853 	mutex_enter(SD_MUTEX(un));
19854 	while ((un->un_state == SD_STATE_SUSPENDED) ||
19855 	    (un->un_state == SD_STATE_PM_CHANGING)) {
19856 		cv_wait(&un->un_suspend_cv, SD_MUTEX(un));
19857 	}
19858 	/*
19859 	 * Twiddling the counter here protects commands from now
19860 	 * through to the top of sd_uscsi_strategy. Without the
19861 	 * counter inc. a power down, for example, could get in
19862 	 * after the above check for state is made and before
19863 	 * execution gets to the top of sd_uscsi_strategy.
19864 	 * That would cause problems.
19865 	 */
19866 	un->un_ncmds_in_driver++;
19867 
19868 	if (!is_valid &&
19869 	    (flag & (FNDELAY | FNONBLOCK))) {
19870 		switch (cmd) {
19871 		case DKIOCGGEOM:	/* SD_PATH_DIRECT */
19872 		case DKIOCGVTOC:
19873 		case DKIOCGAPART:
19874 		case DKIOCPARTINFO:
19875 		case DKIOCSGEOM:
19876 		case DKIOCSAPART:
19877 		case DKIOCGETEFI:
19878 		case DKIOCPARTITION:
19879 		case DKIOCSVTOC:
19880 		case DKIOCSETEFI:
19881 		case DKIOCGMBOOT:
19882 		case DKIOCSMBOOT:
19883 		case DKIOCG_PHYGEOM:
19884 		case DKIOCG_VIRTGEOM:
19885 			/* let cmlb handle it */
19886 			goto skip_ready_valid;
19887 
19888 		case CDROMPAUSE:
19889 		case CDROMRESUME:
19890 		case CDROMPLAYMSF:
19891 		case CDROMPLAYTRKIND:
19892 		case CDROMREADTOCHDR:
19893 		case CDROMREADTOCENTRY:
19894 		case CDROMSTOP:
19895 		case CDROMSTART:
19896 		case CDROMVOLCTRL:
19897 		case CDROMSUBCHNL:
19898 		case CDROMREADMODE2:
19899 		case CDROMREADMODE1:
19900 		case CDROMREADOFFSET:
19901 		case CDROMSBLKMODE:
19902 		case CDROMGBLKMODE:
19903 		case CDROMGDRVSPEED:
19904 		case CDROMSDRVSPEED:
19905 		case CDROMCDDA:
19906 		case CDROMCDXA:
19907 		case CDROMSUBCODE:
19908 			if (!ISCD(un)) {
19909 				un->un_ncmds_in_driver--;
19910 				ASSERT(un->un_ncmds_in_driver >= 0);
19911 				mutex_exit(SD_MUTEX(un));
19912 				return (ENOTTY);
19913 			}
19914 			break;
19915 		case FDEJECT:
19916 		case DKIOCEJECT:
19917 		case CDROMEJECT:
19918 			if (!un->un_f_eject_media_supported) {
19919 				un->un_ncmds_in_driver--;
19920 				ASSERT(un->un_ncmds_in_driver >= 0);
19921 				mutex_exit(SD_MUTEX(un));
19922 				return (ENOTTY);
19923 			}
19924 			break;
19925 		case DKIOCFLUSHWRITECACHE:
19926 			mutex_exit(SD_MUTEX(un));
19927 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
19928 			if (err != 0) {
19929 				mutex_enter(SD_MUTEX(un));
19930 				un->un_ncmds_in_driver--;
19931 				ASSERT(un->un_ncmds_in_driver >= 0);
19932 				mutex_exit(SD_MUTEX(un));
19933 				return (EIO);
19934 			}
19935 			mutex_enter(SD_MUTEX(un));
19936 			/* FALLTHROUGH */
19937 		case DKIOCREMOVABLE:
19938 		case DKIOCHOTPLUGGABLE:
19939 		case DKIOCINFO:
19940 		case DKIOCGMEDIAINFO:
19941 		case MHIOCENFAILFAST:
19942 		case MHIOCSTATUS:
19943 		case MHIOCTKOWN:
19944 		case MHIOCRELEASE:
19945 		case MHIOCGRP_INKEYS:
19946 		case MHIOCGRP_INRESV:
19947 		case MHIOCGRP_REGISTER:
19948 		case MHIOCGRP_RESERVE:
19949 		case MHIOCGRP_PREEMPTANDABORT:
19950 		case MHIOCGRP_REGISTERANDIGNOREKEY:
19951 		case CDROMCLOSETRAY:
19952 		case USCSICMD:
19953 			goto skip_ready_valid;
19954 		default:
19955 			break;
19956 		}
19957 
19958 		mutex_exit(SD_MUTEX(un));
19959 		err = sd_ready_and_valid(un);
19960 		mutex_enter(SD_MUTEX(un));
19961 
19962 		if (err != SD_READY_VALID) {
19963 			switch (cmd) {
19964 			case DKIOCSTATE:
19965 			case CDROMGDRVSPEED:
19966 			case CDROMSDRVSPEED:
19967 			case FDEJECT:	/* for eject command */
19968 			case DKIOCEJECT:
19969 			case CDROMEJECT:
19970 			case DKIOCREMOVABLE:
19971 			case DKIOCHOTPLUGGABLE:
19972 				break;
19973 			default:
19974 				if (un->un_f_has_removable_media) {
19975 					err = ENXIO;
19976 				} else {
19977 				/* Do not map SD_RESERVED_BY_OTHERS to EIO */
19978 					if (err == SD_RESERVED_BY_OTHERS) {
19979 						err = EACCES;
19980 					} else {
19981 						err = EIO;
19982 					}
19983 				}
19984 				un->un_ncmds_in_driver--;
19985 				ASSERT(un->un_ncmds_in_driver >= 0);
19986 				mutex_exit(SD_MUTEX(un));
19987 				return (err);
19988 			}
19989 		}
19990 	}
19991 
19992 skip_ready_valid:
19993 	mutex_exit(SD_MUTEX(un));
19994 
19995 	switch (cmd) {
19996 	case DKIOCINFO:
19997 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCINFO\n");
19998 		err = sd_dkio_ctrl_info(dev, (caddr_t)arg, flag);
19999 		break;
20000 
20001 	case DKIOCGMEDIAINFO:
20002 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGMEDIAINFO\n");
20003 		err = sd_get_media_info(dev, (caddr_t)arg, flag);
20004 		break;
20005 
20006 	case DKIOCGGEOM:
20007 	case DKIOCGVTOC:
20008 	case DKIOCGAPART:
20009 	case DKIOCPARTINFO:
20010 	case DKIOCSGEOM:
20011 	case DKIOCSAPART:
20012 	case DKIOCGETEFI:
20013 	case DKIOCPARTITION:
20014 	case DKIOCSVTOC:
20015 	case DKIOCSETEFI:
20016 	case DKIOCGMBOOT:
20017 	case DKIOCSMBOOT:
20018 	case DKIOCG_PHYGEOM:
20019 	case DKIOCG_VIRTGEOM:
20020 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOC %d\n", cmd);
20021 
20022 		/* TUR should spin up */
20023 
20024 		if (un->un_f_has_removable_media)
20025 			err = sd_send_scsi_TEST_UNIT_READY(un,
20026 			    SD_CHECK_FOR_MEDIA);
20027 		else
20028 			err = sd_send_scsi_TEST_UNIT_READY(un, 0);
20029 
20030 		if (err != 0)
20031 			break;
20032 
20033 		err = cmlb_ioctl(un->un_cmlbhandle, dev,
20034 		    cmd, arg, flag, cred_p, rval_p, (void *)SD_PATH_DIRECT);
20035 
20036 		if ((err == 0) &&
20037 		    ((cmd == DKIOCSETEFI) ||
20038 		    (un->un_f_pkstats_enabled) &&
20039 		    (cmd == DKIOCSAPART || cmd == DKIOCSVTOC))) {
20040 
20041 			tmprval = cmlb_validate(un->un_cmlbhandle, CMLB_SILENT,
20042 			    (void *)SD_PATH_DIRECT);
20043 			if ((tmprval == 0) && un->un_f_pkstats_enabled) {
20044 				sd_set_pstats(un);
20045 				SD_TRACE(SD_LOG_IO_PARTITION, un,
20046 				    "sd_ioctl: un:0x%p pstats created and "
20047 				    "set\n", un);
20048 			}
20049 		}
20050 
20051 		if ((cmd == DKIOCSVTOC) ||
20052 		    ((cmd == DKIOCSETEFI) && (tmprval == 0))) {
20053 
20054 			mutex_enter(SD_MUTEX(un));
20055 			if (un->un_f_devid_supported &&
20056 			    (un->un_f_opt_fab_devid == TRUE)) {
20057 				if (un->un_devid == NULL) {
20058 					sd_register_devid(un, SD_DEVINFO(un),
20059 					    SD_TARGET_IS_UNRESERVED);
20060 				} else {
20061 					/*
20062 					 * The device id for this disk
20063 					 * has been fabricated. The
20064 					 * device id must be preserved
20065 					 * by writing it back out to
20066 					 * disk.
20067 					 */
20068 					if (sd_write_deviceid(un) != 0) {
20069 						ddi_devid_free(un->un_devid);
20070 						un->un_devid = NULL;
20071 					}
20072 				}
20073 			}
20074 			mutex_exit(SD_MUTEX(un));
20075 		}
20076 
20077 		break;
20078 
20079 	case DKIOCLOCK:
20080 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCLOCK\n");
20081 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
20082 		    SD_PATH_STANDARD);
20083 		break;
20084 
20085 	case DKIOCUNLOCK:
20086 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCUNLOCK\n");
20087 		err = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
20088 		    SD_PATH_STANDARD);
20089 		break;
20090 
20091 	case DKIOCSTATE: {
20092 		enum dkio_state		state;
20093 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCSTATE\n");
20094 
20095 		if (ddi_copyin((void *)arg, &state, sizeof (int), flag) != 0) {
20096 			err = EFAULT;
20097 		} else {
20098 			err = sd_check_media(dev, state);
20099 			if (err == 0) {
20100 				if (ddi_copyout(&un->un_mediastate, (void *)arg,
20101 				    sizeof (int), flag) != 0)
20102 					err = EFAULT;
20103 			}
20104 		}
20105 		break;
20106 	}
20107 
20108 	case DKIOCREMOVABLE:
20109 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCREMOVABLE\n");
20110 		i = un->un_f_has_removable_media ? 1 : 0;
20111 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
20112 			err = EFAULT;
20113 		} else {
20114 			err = 0;
20115 		}
20116 		break;
20117 
20118 	case DKIOCHOTPLUGGABLE:
20119 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCHOTPLUGGABLE\n");
20120 		i = un->un_f_is_hotpluggable ? 1 : 0;
20121 		if (ddi_copyout(&i, (void *)arg, sizeof (int), flag) != 0) {
20122 			err = EFAULT;
20123 		} else {
20124 			err = 0;
20125 		}
20126 		break;
20127 
20128 	case DKIOCGTEMPERATURE:
20129 		SD_TRACE(SD_LOG_IOCTL, un, "DKIOCGTEMPERATURE\n");
20130 		err = sd_dkio_get_temp(dev, (caddr_t)arg, flag);
20131 		break;
20132 
20133 	case MHIOCENFAILFAST:
20134 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCENFAILFAST\n");
20135 		if ((err = drv_priv(cred_p)) == 0) {
20136 			err = sd_mhdioc_failfast(dev, (caddr_t)arg, flag);
20137 		}
20138 		break;
20139 
20140 	case MHIOCTKOWN:
20141 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCTKOWN\n");
20142 		if ((err = drv_priv(cred_p)) == 0) {
20143 			err = sd_mhdioc_takeown(dev, (caddr_t)arg, flag);
20144 		}
20145 		break;
20146 
20147 	case MHIOCRELEASE:
20148 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCRELEASE\n");
20149 		if ((err = drv_priv(cred_p)) == 0) {
20150 			err = sd_mhdioc_release(dev);
20151 		}
20152 		break;
20153 
20154 	case MHIOCSTATUS:
20155 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCSTATUS\n");
20156 		if ((err = drv_priv(cred_p)) == 0) {
20157 			switch (sd_send_scsi_TEST_UNIT_READY(un, 0)) {
20158 			case 0:
20159 				err = 0;
20160 				break;
20161 			case EACCES:
20162 				*rval_p = 1;
20163 				err = 0;
20164 				break;
20165 			default:
20166 				err = EIO;
20167 				break;
20168 			}
20169 		}
20170 		break;
20171 
20172 	case MHIOCQRESERVE:
20173 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCQRESERVE\n");
20174 		if ((err = drv_priv(cred_p)) == 0) {
20175 			err = sd_reserve_release(dev, SD_RESERVE);
20176 		}
20177 		break;
20178 
20179 	case MHIOCREREGISTERDEVID:
20180 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCREREGISTERDEVID\n");
20181 		if (drv_priv(cred_p) == EPERM) {
20182 			err = EPERM;
20183 		} else if (!un->un_f_devid_supported) {
20184 			err = ENOTTY;
20185 		} else {
20186 			err = sd_mhdioc_register_devid(dev);
20187 		}
20188 		break;
20189 
20190 	case MHIOCGRP_INKEYS:
20191 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INKEYS\n");
20192 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
20193 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20194 				err = ENOTSUP;
20195 			} else {
20196 				err = sd_mhdioc_inkeys(dev, (caddr_t)arg,
20197 				    flag);
20198 			}
20199 		}
20200 		break;
20201 
20202 	case MHIOCGRP_INRESV:
20203 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_INRESV\n");
20204 		if (((err = drv_priv(cred_p)) != EPERM) && arg != NULL) {
20205 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20206 				err = ENOTSUP;
20207 			} else {
20208 				err = sd_mhdioc_inresv(dev, (caddr_t)arg, flag);
20209 			}
20210 		}
20211 		break;
20212 
20213 	case MHIOCGRP_REGISTER:
20214 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTER\n");
20215 		if ((err = drv_priv(cred_p)) != EPERM) {
20216 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20217 				err = ENOTSUP;
20218 			} else if (arg != NULL) {
20219 				mhioc_register_t reg;
20220 				if (ddi_copyin((void *)arg, &reg,
20221 				    sizeof (mhioc_register_t), flag) != 0) {
20222 					err = EFAULT;
20223 				} else {
20224 					err =
20225 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20226 					    un, SD_SCSI3_REGISTER,
20227 					    (uchar_t *)&reg);
20228 				}
20229 			}
20230 		}
20231 		break;
20232 
20233 	case MHIOCGRP_RESERVE:
20234 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_RESERVE\n");
20235 		if ((err = drv_priv(cred_p)) != EPERM) {
20236 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20237 				err = ENOTSUP;
20238 			} else if (arg != NULL) {
20239 				mhioc_resv_desc_t resv_desc;
20240 				if (ddi_copyin((void *)arg, &resv_desc,
20241 				    sizeof (mhioc_resv_desc_t), flag) != 0) {
20242 					err = EFAULT;
20243 				} else {
20244 					err =
20245 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20246 					    un, SD_SCSI3_RESERVE,
20247 					    (uchar_t *)&resv_desc);
20248 				}
20249 			}
20250 		}
20251 		break;
20252 
20253 	case MHIOCGRP_PREEMPTANDABORT:
20254 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_PREEMPTANDABORT\n");
20255 		if ((err = drv_priv(cred_p)) != EPERM) {
20256 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20257 				err = ENOTSUP;
20258 			} else if (arg != NULL) {
20259 				mhioc_preemptandabort_t preempt_abort;
20260 				if (ddi_copyin((void *)arg, &preempt_abort,
20261 				    sizeof (mhioc_preemptandabort_t),
20262 				    flag) != 0) {
20263 					err = EFAULT;
20264 				} else {
20265 					err =
20266 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20267 					    un, SD_SCSI3_PREEMPTANDABORT,
20268 					    (uchar_t *)&preempt_abort);
20269 				}
20270 			}
20271 		}
20272 		break;
20273 
20274 	case MHIOCGRP_REGISTERANDIGNOREKEY:
20275 		SD_TRACE(SD_LOG_IOCTL, un, "MHIOCGRP_REGISTERANDIGNOREKEY\n");
20276 		if ((err = drv_priv(cred_p)) != EPERM) {
20277 			if (un->un_reservation_type == SD_SCSI2_RESERVATION) {
20278 				err = ENOTSUP;
20279 			} else if (arg != NULL) {
20280 				mhioc_registerandignorekey_t r_and_i;
20281 				if (ddi_copyin((void *)arg, (void *)&r_and_i,
20282 				    sizeof (mhioc_registerandignorekey_t),
20283 				    flag) != 0) {
20284 					err = EFAULT;
20285 				} else {
20286 					err =
20287 					    sd_send_scsi_PERSISTENT_RESERVE_OUT(
20288 					    un, SD_SCSI3_REGISTERANDIGNOREKEY,
20289 					    (uchar_t *)&r_and_i);
20290 				}
20291 			}
20292 		}
20293 		break;
20294 
20295 	case USCSICMD:
20296 		SD_TRACE(SD_LOG_IOCTL, un, "USCSICMD\n");
20297 		cr = ddi_get_cred();
20298 		if ((drv_priv(cred_p) != 0) && (drv_priv(cr) != 0)) {
20299 			err = EPERM;
20300 		} else {
20301 			enum uio_seg	uioseg;
20302 			uioseg = (flag & FKIOCTL) ? UIO_SYSSPACE :
20303 			    UIO_USERSPACE;
20304 			if (un->un_f_format_in_progress == TRUE) {
20305 				err = EAGAIN;
20306 				break;
20307 			}
20308 			err = sd_send_scsi_cmd(dev, (struct uscsi_cmd *)arg,
20309 			    flag, uioseg, SD_PATH_STANDARD);
20310 		}
20311 		break;
20312 
20313 	case CDROMPAUSE:
20314 	case CDROMRESUME:
20315 		SD_TRACE(SD_LOG_IOCTL, un, "PAUSE-RESUME\n");
20316 		if (!ISCD(un)) {
20317 			err = ENOTTY;
20318 		} else {
20319 			err = sr_pause_resume(dev, cmd);
20320 		}
20321 		break;
20322 
20323 	case CDROMPLAYMSF:
20324 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYMSF\n");
20325 		if (!ISCD(un)) {
20326 			err = ENOTTY;
20327 		} else {
20328 			err = sr_play_msf(dev, (caddr_t)arg, flag);
20329 		}
20330 		break;
20331 
20332 	case CDROMPLAYTRKIND:
20333 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMPLAYTRKIND\n");
20334 #if defined(__i386) || defined(__amd64)
20335 		/*
20336 		 * not supported on ATAPI CD drives, use CDROMPLAYMSF instead
20337 		 */
20338 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
20339 #else
20340 		if (!ISCD(un)) {
20341 #endif
20342 			err = ENOTTY;
20343 		} else {
20344 			err = sr_play_trkind(dev, (caddr_t)arg, flag);
20345 		}
20346 		break;
20347 
20348 	case CDROMREADTOCHDR:
20349 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCHDR\n");
20350 		if (!ISCD(un)) {
20351 			err = ENOTTY;
20352 		} else {
20353 			err = sr_read_tochdr(dev, (caddr_t)arg, flag);
20354 		}
20355 		break;
20356 
20357 	case CDROMREADTOCENTRY:
20358 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADTOCENTRY\n");
20359 		if (!ISCD(un)) {
20360 			err = ENOTTY;
20361 		} else {
20362 			err = sr_read_tocentry(dev, (caddr_t)arg, flag);
20363 		}
20364 		break;
20365 
20366 	case CDROMSTOP:
20367 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTOP\n");
20368 		if (!ISCD(un)) {
20369 			err = ENOTTY;
20370 		} else {
20371 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_STOP,
20372 			    SD_PATH_STANDARD);
20373 		}
20374 		break;
20375 
20376 	case CDROMSTART:
20377 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSTART\n");
20378 		if (!ISCD(un)) {
20379 			err = ENOTTY;
20380 		} else {
20381 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_START,
20382 			    SD_PATH_STANDARD);
20383 		}
20384 		break;
20385 
20386 	case CDROMCLOSETRAY:
20387 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCLOSETRAY\n");
20388 		if (!ISCD(un)) {
20389 			err = ENOTTY;
20390 		} else {
20391 			err = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_CLOSE,
20392 			    SD_PATH_STANDARD);
20393 		}
20394 		break;
20395 
20396 	case FDEJECT:	/* for eject command */
20397 	case DKIOCEJECT:
20398 	case CDROMEJECT:
20399 		SD_TRACE(SD_LOG_IOCTL, un, "EJECT\n");
20400 		if (!un->un_f_eject_media_supported) {
20401 			err = ENOTTY;
20402 		} else {
20403 			err = sr_eject(dev);
20404 		}
20405 		break;
20406 
20407 	case CDROMVOLCTRL:
20408 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMVOLCTRL\n");
20409 		if (!ISCD(un)) {
20410 			err = ENOTTY;
20411 		} else {
20412 			err = sr_volume_ctrl(dev, (caddr_t)arg, flag);
20413 		}
20414 		break;
20415 
20416 	case CDROMSUBCHNL:
20417 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCHNL\n");
20418 		if (!ISCD(un)) {
20419 			err = ENOTTY;
20420 		} else {
20421 			err = sr_read_subchannel(dev, (caddr_t)arg, flag);
20422 		}
20423 		break;
20424 
20425 	case CDROMREADMODE2:
20426 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE2\n");
20427 		if (!ISCD(un)) {
20428 			err = ENOTTY;
20429 		} else if (un->un_f_cfg_is_atapi == TRUE) {
20430 			/*
20431 			 * If the drive supports READ CD, use that instead of
20432 			 * switching the LBA size via a MODE SELECT
20433 			 * Block Descriptor
20434 			 */
20435 			err = sr_read_cd_mode2(dev, (caddr_t)arg, flag);
20436 		} else {
20437 			err = sr_read_mode2(dev, (caddr_t)arg, flag);
20438 		}
20439 		break;
20440 
20441 	case CDROMREADMODE1:
20442 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADMODE1\n");
20443 		if (!ISCD(un)) {
20444 			err = ENOTTY;
20445 		} else {
20446 			err = sr_read_mode1(dev, (caddr_t)arg, flag);
20447 		}
20448 		break;
20449 
20450 	case CDROMREADOFFSET:
20451 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMREADOFFSET\n");
20452 		if (!ISCD(un)) {
20453 			err = ENOTTY;
20454 		} else {
20455 			err = sr_read_sony_session_offset(dev, (caddr_t)arg,
20456 			    flag);
20457 		}
20458 		break;
20459 
20460 	case CDROMSBLKMODE:
20461 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSBLKMODE\n");
20462 		/*
20463 		 * There is no means of changing block size in case of atapi
20464 		 * drives, thus return ENOTTY if drive type is atapi
20465 		 */
20466 		if (!ISCD(un) || (un->un_f_cfg_is_atapi == TRUE)) {
20467 			err = ENOTTY;
20468 		} else if (un->un_f_mmc_cap == TRUE) {
20469 
20470 			/*
20471 			 * MMC Devices do not support changing the
20472 			 * logical block size
20473 			 *
20474 			 * Note: EINVAL is being returned instead of ENOTTY to
20475 			 * maintain consistancy with the original mmc
20476 			 * driver update.
20477 			 */
20478 			err = EINVAL;
20479 		} else {
20480 			mutex_enter(SD_MUTEX(un));
20481 			if ((!(un->un_exclopen & (1<<SDPART(dev)))) ||
20482 			    (un->un_ncmds_in_transport > 0)) {
20483 				mutex_exit(SD_MUTEX(un));
20484 				err = EINVAL;
20485 			} else {
20486 				mutex_exit(SD_MUTEX(un));
20487 				err = sr_change_blkmode(dev, cmd, arg, flag);
20488 			}
20489 		}
20490 		break;
20491 
20492 	case CDROMGBLKMODE:
20493 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMGBLKMODE\n");
20494 		if (!ISCD(un)) {
20495 			err = ENOTTY;
20496 		} else if ((un->un_f_cfg_is_atapi != FALSE) &&
20497 		    (un->un_f_blockcount_is_valid != FALSE)) {
20498 			/*
20499 			 * Drive is an ATAPI drive so return target block
20500 			 * size for ATAPI drives since we cannot change the
20501 			 * blocksize on ATAPI drives. Used primarily to detect
20502 			 * if an ATAPI cdrom is present.
20503 			 */
20504 			if (ddi_copyout(&un->un_tgt_blocksize, (void *)arg,
20505 			    sizeof (int), flag) != 0) {
20506 				err = EFAULT;
20507 			} else {
20508 				err = 0;
20509 			}
20510 
20511 		} else {
20512 			/*
20513 			 * Drive supports changing block sizes via a Mode
20514 			 * Select.
20515 			 */
20516 			err = sr_change_blkmode(dev, cmd, arg, flag);
20517 		}
20518 		break;
20519 
20520 	case CDROMGDRVSPEED:
20521 	case CDROMSDRVSPEED:
20522 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMXDRVSPEED\n");
20523 		if (!ISCD(un)) {
20524 			err = ENOTTY;
20525 		} else if (un->un_f_mmc_cap == TRUE) {
20526 			/*
20527 			 * Note: In the future the driver implementation
20528 			 * for getting and
20529 			 * setting cd speed should entail:
20530 			 * 1) If non-mmc try the Toshiba mode page
20531 			 *    (sr_change_speed)
20532 			 * 2) If mmc but no support for Real Time Streaming try
20533 			 *    the SET CD SPEED (0xBB) command
20534 			 *   (sr_atapi_change_speed)
20535 			 * 3) If mmc and support for Real Time Streaming
20536 			 *    try the GET PERFORMANCE and SET STREAMING
20537 			 *    commands (not yet implemented, 4380808)
20538 			 */
20539 			/*
20540 			 * As per recent MMC spec, CD-ROM speed is variable
20541 			 * and changes with LBA. Since there is no such
20542 			 * things as drive speed now, fail this ioctl.
20543 			 *
20544 			 * Note: EINVAL is returned for consistancy of original
20545 			 * implementation which included support for getting
20546 			 * the drive speed of mmc devices but not setting
20547 			 * the drive speed. Thus EINVAL would be returned
20548 			 * if a set request was made for an mmc device.
20549 			 * We no longer support get or set speed for
20550 			 * mmc but need to remain consistent with regard
20551 			 * to the error code returned.
20552 			 */
20553 			err = EINVAL;
20554 		} else if (un->un_f_cfg_is_atapi == TRUE) {
20555 			err = sr_atapi_change_speed(dev, cmd, arg, flag);
20556 		} else {
20557 			err = sr_change_speed(dev, cmd, arg, flag);
20558 		}
20559 		break;
20560 
20561 	case CDROMCDDA:
20562 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDDA\n");
20563 		if (!ISCD(un)) {
20564 			err = ENOTTY;
20565 		} else {
20566 			err = sr_read_cdda(dev, (void *)arg, flag);
20567 		}
20568 		break;
20569 
20570 	case CDROMCDXA:
20571 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMCDXA\n");
20572 		if (!ISCD(un)) {
20573 			err = ENOTTY;
20574 		} else {
20575 			err = sr_read_cdxa(dev, (caddr_t)arg, flag);
20576 		}
20577 		break;
20578 
20579 	case CDROMSUBCODE:
20580 		SD_TRACE(SD_LOG_IOCTL, un, "CDROMSUBCODE\n");
20581 		if (!ISCD(un)) {
20582 			err = ENOTTY;
20583 		} else {
20584 			err = sr_read_all_subcodes(dev, (caddr_t)arg, flag);
20585 		}
20586 		break;
20587 
20588 
20589 #ifdef SDDEBUG
20590 /* RESET/ABORTS testing ioctls */
20591 	case DKIOCRESET: {
20592 		int	reset_level;
20593 
20594 		if (ddi_copyin((void *)arg, &reset_level, sizeof (int), flag)) {
20595 			err = EFAULT;
20596 		} else {
20597 			SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCRESET: "
20598 			    "reset_level = 0x%lx\n", reset_level);
20599 			if (scsi_reset(SD_ADDRESS(un), reset_level)) {
20600 				err = 0;
20601 			} else {
20602 				err = EIO;
20603 			}
20604 		}
20605 		break;
20606 	}
20607 
20608 	case DKIOCABORT:
20609 		SD_INFO(SD_LOG_IOCTL, un, "sdioctl: DKIOCABORT:\n");
20610 		if (scsi_abort(SD_ADDRESS(un), NULL)) {
20611 			err = 0;
20612 		} else {
20613 			err = EIO;
20614 		}
20615 		break;
20616 #endif
20617 
20618 #ifdef SD_FAULT_INJECTION
20619 /* SDIOC FaultInjection testing ioctls */
20620 	case SDIOCSTART:
20621 	case SDIOCSTOP:
20622 	case SDIOCINSERTPKT:
20623 	case SDIOCINSERTXB:
20624 	case SDIOCINSERTUN:
20625 	case SDIOCINSERTARQ:
20626 	case SDIOCPUSH:
20627 	case SDIOCRETRIEVE:
20628 	case SDIOCRUN:
20629 		SD_INFO(SD_LOG_SDTEST, un, "sdioctl:"
20630 		    "SDIOC detected cmd:0x%X:\n", cmd);
20631 		/* call error generator */
20632 		sd_faultinjection_ioctl(cmd, arg, un);
20633 		err = 0;
20634 		break;
20635 
20636 #endif /* SD_FAULT_INJECTION */
20637 
20638 	case DKIOCFLUSHWRITECACHE:
20639 		{
20640 			struct dk_callback *dkc = (struct dk_callback *)arg;
20641 
20642 			mutex_enter(SD_MUTEX(un));
20643 			if (!un->un_f_sync_cache_supported ||
20644 			    !un->un_f_write_cache_enabled) {
20645 				err = un->un_f_sync_cache_supported ?
20646 				    0 : ENOTSUP;
20647 				mutex_exit(SD_MUTEX(un));
20648 				if ((flag & FKIOCTL) && dkc != NULL &&
20649 				    dkc->dkc_callback != NULL) {
20650 					(*dkc->dkc_callback)(dkc->dkc_cookie,
20651 					    err);
20652 					/*
20653 					 * Did callback and reported error.
20654 					 * Since we did a callback, ioctl
20655 					 * should return 0.
20656 					 */
20657 					err = 0;
20658 				}
20659 				break;
20660 			}
20661 			mutex_exit(SD_MUTEX(un));
20662 
20663 			if ((flag & FKIOCTL) && dkc != NULL &&
20664 			    dkc->dkc_callback != NULL) {
20665 				/* async SYNC CACHE request */
20666 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, dkc);
20667 			} else {
20668 				/* synchronous SYNC CACHE request */
20669 				err = sd_send_scsi_SYNCHRONIZE_CACHE(un, NULL);
20670 			}
20671 		}
20672 		break;
20673 
20674 	case DKIOCGETWCE: {
20675 
20676 		int wce;
20677 
20678 		if ((err = sd_get_write_cache_enabled(un, &wce)) != 0) {
20679 			break;
20680 		}
20681 
20682 		if (ddi_copyout(&wce, (void *)arg, sizeof (wce), flag)) {
20683 			err = EFAULT;
20684 		}
20685 		break;
20686 	}
20687 
20688 	case DKIOCSETWCE: {
20689 
20690 		int wce, sync_supported;
20691 
20692 		if (ddi_copyin((void *)arg, &wce, sizeof (wce), flag)) {
20693 			err = EFAULT;
20694 			break;
20695 		}
20696 
20697 		/*
20698 		 * Synchronize multiple threads trying to enable
20699 		 * or disable the cache via the un_f_wcc_cv
20700 		 * condition variable.
20701 		 */
20702 		mutex_enter(SD_MUTEX(un));
20703 
20704 		/*
20705 		 * Don't allow the cache to be enabled if the
20706 		 * config file has it disabled.
20707 		 */
20708 		if (un->un_f_opt_disable_cache && wce) {
20709 			mutex_exit(SD_MUTEX(un));
20710 			err = EINVAL;
20711 			break;
20712 		}
20713 
20714 		/*
20715 		 * Wait for write cache change in progress
20716 		 * bit to be clear before proceeding.
20717 		 */
20718 		while (un->un_f_wcc_inprog)
20719 			cv_wait(&un->un_wcc_cv, SD_MUTEX(un));
20720 
20721 		un->un_f_wcc_inprog = 1;
20722 
20723 		if (un->un_f_write_cache_enabled && wce == 0) {
20724 			/*
20725 			 * Disable the write cache.  Don't clear
20726 			 * un_f_write_cache_enabled until after
20727 			 * the mode select and flush are complete.
20728 			 */
20729 			sync_supported = un->un_f_sync_cache_supported;
20730 
20731 			/*
20732 			 * If cache flush is suppressed, we assume that the
20733 			 * controller firmware will take care of managing the
20734 			 * write cache for us: no need to explicitly
20735 			 * disable it.
20736 			 */
20737 			if (!un->un_f_suppress_cache_flush) {
20738 				mutex_exit(SD_MUTEX(un));
20739 				if ((err = sd_cache_control(un,
20740 				    SD_CACHE_NOCHANGE,
20741 				    SD_CACHE_DISABLE)) == 0 &&
20742 				    sync_supported) {
20743 					err = sd_send_scsi_SYNCHRONIZE_CACHE(un,
20744 					    NULL);
20745 				}
20746 			} else {
20747 				mutex_exit(SD_MUTEX(un));
20748 			}
20749 
20750 			mutex_enter(SD_MUTEX(un));
20751 			if (err == 0) {
20752 				un->un_f_write_cache_enabled = 0;
20753 			}
20754 
20755 		} else if (!un->un_f_write_cache_enabled && wce != 0) {
20756 			/*
20757 			 * Set un_f_write_cache_enabled first, so there is
20758 			 * no window where the cache is enabled, but the
20759 			 * bit says it isn't.
20760 			 */
20761 			un->un_f_write_cache_enabled = 1;
20762 
20763 			/*
20764 			 * If cache flush is suppressed, we assume that the
20765 			 * controller firmware will take care of managing the
20766 			 * write cache for us: no need to explicitly
20767 			 * enable it.
20768 			 */
20769 			if (!un->un_f_suppress_cache_flush) {
20770 				mutex_exit(SD_MUTEX(un));
20771 				err = sd_cache_control(un, SD_CACHE_NOCHANGE,
20772 				    SD_CACHE_ENABLE);
20773 			} else {
20774 				mutex_exit(SD_MUTEX(un));
20775 			}
20776 
20777 			mutex_enter(SD_MUTEX(un));
20778 
20779 			if (err) {
20780 				un->un_f_write_cache_enabled = 0;
20781 			}
20782 		}
20783 
20784 		un->un_f_wcc_inprog = 0;
20785 		cv_broadcast(&un->un_wcc_cv);
20786 		mutex_exit(SD_MUTEX(un));
20787 		break;
20788 	}
20789 
20790 	default:
20791 		err = ENOTTY;
20792 		break;
20793 	}
20794 	mutex_enter(SD_MUTEX(un));
20795 	un->un_ncmds_in_driver--;
20796 	ASSERT(un->un_ncmds_in_driver >= 0);
20797 	mutex_exit(SD_MUTEX(un));
20798 
20799 	SD_TRACE(SD_LOG_IOCTL, un, "sdioctl: exit: %d\n", err);
20800 	return (err);
20801 }
20802 
20803 
20804 /*
20805  *    Function: sd_dkio_ctrl_info
20806  *
20807  * Description: This routine is the driver entry point for handling controller
20808  *		information ioctl requests (DKIOCINFO).
20809  *
20810  *   Arguments: dev  - the device number
20811  *		arg  - pointer to user provided dk_cinfo structure
20812  *		       specifying the controller type and attributes.
20813  *		flag - this argument is a pass through to ddi_copyxxx()
20814  *		       directly from the mode argument of ioctl().
20815  *
20816  * Return Code: 0
20817  *		EFAULT
20818  *		ENXIO
20819  */
20820 
20821 static int
20822 sd_dkio_ctrl_info(dev_t dev, caddr_t arg, int flag)
20823 {
20824 	struct sd_lun	*un = NULL;
20825 	struct dk_cinfo	*info;
20826 	dev_info_t	*pdip;
20827 	int		lun, tgt;
20828 
20829 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
20830 		return (ENXIO);
20831 	}
20832 
20833 	info = (struct dk_cinfo *)
20834 	    kmem_zalloc(sizeof (struct dk_cinfo), KM_SLEEP);
20835 
20836 	switch (un->un_ctype) {
20837 	case CTYPE_CDROM:
20838 		info->dki_ctype = DKC_CDROM;
20839 		break;
20840 	default:
20841 		info->dki_ctype = DKC_SCSI_CCS;
20842 		break;
20843 	}
20844 	pdip = ddi_get_parent(SD_DEVINFO(un));
20845 	info->dki_cnum = ddi_get_instance(pdip);
20846 	if (strlen(ddi_get_name(pdip)) < DK_DEVLEN) {
20847 		(void) strcpy(info->dki_cname, ddi_get_name(pdip));
20848 	} else {
20849 		(void) strncpy(info->dki_cname, ddi_node_name(pdip),
20850 		    DK_DEVLEN - 1);
20851 	}
20852 
20853 	lun = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20854 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_LUN, 0);
20855 	tgt = ddi_prop_get_int(DDI_DEV_T_ANY, SD_DEVINFO(un),
20856 	    DDI_PROP_DONTPASS, SCSI_ADDR_PROP_TARGET, 0);
20857 
20858 	/* Unit Information */
20859 	info->dki_unit = ddi_get_instance(SD_DEVINFO(un));
20860 	info->dki_slave = ((tgt << 3) | lun);
20861 	(void) strncpy(info->dki_dname, ddi_driver_name(SD_DEVINFO(un)),
20862 	    DK_DEVLEN - 1);
20863 	info->dki_flags = DKI_FMTVOL;
20864 	info->dki_partition = SDPART(dev);
20865 
20866 	/* Max Transfer size of this device in blocks */
20867 	info->dki_maxtransfer = un->un_max_xfer_size / un->un_sys_blocksize;
20868 	info->dki_addr = 0;
20869 	info->dki_space = 0;
20870 	info->dki_prio = 0;
20871 	info->dki_vec = 0;
20872 
20873 	if (ddi_copyout(info, arg, sizeof (struct dk_cinfo), flag) != 0) {
20874 		kmem_free(info, sizeof (struct dk_cinfo));
20875 		return (EFAULT);
20876 	} else {
20877 		kmem_free(info, sizeof (struct dk_cinfo));
20878 		return (0);
20879 	}
20880 }
20881 
20882 
20883 /*
20884  *    Function: sd_get_media_info
20885  *
20886  * Description: This routine is the driver entry point for handling ioctl
20887  *		requests for the media type or command set profile used by the
20888  *		drive to operate on the media (DKIOCGMEDIAINFO).
20889  *
20890  *   Arguments: dev	- the device number
20891  *		arg	- pointer to user provided dk_minfo structure
20892  *			  specifying the media type, logical block size and
20893  *			  drive capacity.
20894  *		flag	- this argument is a pass through to ddi_copyxxx()
20895  *			  directly from the mode argument of ioctl().
20896  *
20897  * Return Code: 0
20898  *		EACCESS
20899  *		EFAULT
20900  *		ENXIO
20901  *		EIO
20902  */
20903 
20904 static int
20905 sd_get_media_info(dev_t dev, caddr_t arg, int flag)
20906 {
20907 	struct sd_lun		*un = NULL;
20908 	struct uscsi_cmd	com;
20909 	struct scsi_inquiry	*sinq;
20910 	struct dk_minfo		media_info;
20911 	u_longlong_t		media_capacity;
20912 	uint64_t		capacity;
20913 	uint_t			lbasize;
20914 	uchar_t			*out_data;
20915 	uchar_t			*rqbuf;
20916 	int			rval = 0;
20917 	int			rtn;
20918 
20919 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
20920 	    (un->un_state == SD_STATE_OFFLINE)) {
20921 		return (ENXIO);
20922 	}
20923 
20924 	SD_TRACE(SD_LOG_IOCTL_DKIO, un, "sd_get_media_info: entry\n");
20925 
20926 	out_data = kmem_zalloc(SD_PROFILE_HEADER_LEN, KM_SLEEP);
20927 	rqbuf = kmem_zalloc(SENSE_LENGTH, KM_SLEEP);
20928 
20929 	/* Issue a TUR to determine if the drive is ready with media present */
20930 	rval = sd_send_scsi_TEST_UNIT_READY(un, SD_CHECK_FOR_MEDIA);
20931 	if (rval == ENXIO) {
20932 		goto done;
20933 	}
20934 
20935 	/* Now get configuration data */
20936 	if (ISCD(un)) {
20937 		media_info.dki_media_type = DK_CDROM;
20938 
20939 		/* Allow SCMD_GET_CONFIGURATION to MMC devices only */
20940 		if (un->un_f_mmc_cap == TRUE) {
20941 			rtn = sd_send_scsi_GET_CONFIGURATION(un, &com, rqbuf,
20942 			    SENSE_LENGTH, out_data, SD_PROFILE_HEADER_LEN,
20943 			    SD_PATH_STANDARD);
20944 
20945 			if (rtn) {
20946 				/*
20947 				 * Failed for other than an illegal request
20948 				 * or command not supported
20949 				 */
20950 				if ((com.uscsi_status == STATUS_CHECK) &&
20951 				    (com.uscsi_rqstatus == STATUS_GOOD)) {
20952 					if ((rqbuf[2] != KEY_ILLEGAL_REQUEST) ||
20953 					    (rqbuf[12] != 0x20)) {
20954 						rval = EIO;
20955 						goto done;
20956 					}
20957 				}
20958 			} else {
20959 				/*
20960 				 * The GET CONFIGURATION command succeeded
20961 				 * so set the media type according to the
20962 				 * returned data
20963 				 */
20964 				media_info.dki_media_type = out_data[6];
20965 				media_info.dki_media_type <<= 8;
20966 				media_info.dki_media_type |= out_data[7];
20967 			}
20968 		}
20969 	} else {
20970 		/*
20971 		 * The profile list is not available, so we attempt to identify
20972 		 * the media type based on the inquiry data
20973 		 */
20974 		sinq = un->un_sd->sd_inq;
20975 		if ((sinq->inq_dtype == DTYPE_DIRECT) ||
20976 		    (sinq->inq_dtype == DTYPE_OPTICAL)) {
20977 			/* This is a direct access device  or optical disk */
20978 			media_info.dki_media_type = DK_FIXED_DISK;
20979 
20980 			if ((bcmp(sinq->inq_vid, "IOMEGA", 6) == 0) ||
20981 			    (bcmp(sinq->inq_vid, "iomega", 6) == 0)) {
20982 				if ((bcmp(sinq->inq_pid, "ZIP", 3) == 0)) {
20983 					media_info.dki_media_type = DK_ZIP;
20984 				} else if (
20985 				    (bcmp(sinq->inq_pid, "jaz", 3) == 0)) {
20986 					media_info.dki_media_type = DK_JAZ;
20987 				}
20988 			}
20989 		} else {
20990 			/*
20991 			 * Not a CD, direct access or optical disk so return
20992 			 * unknown media
20993 			 */
20994 			media_info.dki_media_type = DK_UNKNOWN;
20995 		}
20996 	}
20997 
20998 	/* Now read the capacity so we can provide the lbasize and capacity */
20999 	switch (sd_send_scsi_READ_CAPACITY(un, &capacity, &lbasize,
21000 	    SD_PATH_DIRECT)) {
21001 	case 0:
21002 		break;
21003 	case EACCES:
21004 		rval = EACCES;
21005 		goto done;
21006 	default:
21007 		rval = EIO;
21008 		goto done;
21009 	}
21010 
21011 	/*
21012 	 * If lun is expanded dynamically, update the un structure.
21013 	 */
21014 	mutex_enter(SD_MUTEX(un));
21015 	if ((un->un_f_blockcount_is_valid == TRUE) &&
21016 	    (un->un_f_tgt_blocksize_is_valid == TRUE) &&
21017 	    (capacity > un->un_blockcount)) {
21018 		sd_update_block_info(un, lbasize, capacity);
21019 	}
21020 	mutex_exit(SD_MUTEX(un));
21021 
21022 	media_info.dki_lbsize = lbasize;
21023 	media_capacity = capacity;
21024 
21025 	/*
21026 	 * sd_send_scsi_READ_CAPACITY() reports capacity in
21027 	 * un->un_sys_blocksize chunks. So we need to convert it into
21028 	 * cap.lbasize chunks.
21029 	 */
21030 	media_capacity *= un->un_sys_blocksize;
21031 	media_capacity /= lbasize;
21032 	media_info.dki_capacity = media_capacity;
21033 
21034 	if (ddi_copyout(&media_info, arg, sizeof (struct dk_minfo), flag)) {
21035 		rval = EFAULT;
21036 		/* Put goto. Anybody might add some code below in future */
21037 		goto done;
21038 	}
21039 done:
21040 	kmem_free(out_data, SD_PROFILE_HEADER_LEN);
21041 	kmem_free(rqbuf, SENSE_LENGTH);
21042 	return (rval);
21043 }
21044 
21045 
21046 /*
21047  *    Function: sd_check_media
21048  *
21049  * Description: This utility routine implements the functionality for the
21050  *		DKIOCSTATE ioctl. This ioctl blocks the user thread until the
21051  *		driver state changes from that specified by the user
21052  *		(inserted or ejected). For example, if the user specifies
21053  *		DKIO_EJECTED and the current media state is inserted this
21054  *		routine will immediately return DKIO_INSERTED. However, if the
21055  *		current media state is not inserted the user thread will be
21056  *		blocked until the drive state changes. If DKIO_NONE is specified
21057  *		the user thread will block until a drive state change occurs.
21058  *
21059  *   Arguments: dev  - the device number
21060  *		state  - user pointer to a dkio_state, updated with the current
21061  *			drive state at return.
21062  *
21063  * Return Code: ENXIO
21064  *		EIO
21065  *		EAGAIN
21066  *		EINTR
21067  */
21068 
21069 static int
21070 sd_check_media(dev_t dev, enum dkio_state state)
21071 {
21072 	struct sd_lun		*un = NULL;
21073 	enum dkio_state		prev_state;
21074 	opaque_t		token = NULL;
21075 	int			rval = 0;
21076 
21077 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21078 		return (ENXIO);
21079 	}
21080 
21081 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: entry\n");
21082 
21083 	mutex_enter(SD_MUTEX(un));
21084 
21085 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: "
21086 	    "state=%x, mediastate=%x\n", state, un->un_mediastate);
21087 
21088 	prev_state = un->un_mediastate;
21089 
21090 	/* is there anything to do? */
21091 	if (state == un->un_mediastate || un->un_mediastate == DKIO_NONE) {
21092 		/*
21093 		 * submit the request to the scsi_watch service;
21094 		 * scsi_media_watch_cb() does the real work
21095 		 */
21096 		mutex_exit(SD_MUTEX(un));
21097 
21098 		/*
21099 		 * This change handles the case where a scsi watch request is
21100 		 * added to a device that is powered down. To accomplish this
21101 		 * we power up the device before adding the scsi watch request,
21102 		 * since the scsi watch sends a TUR directly to the device
21103 		 * which the device cannot handle if it is powered down.
21104 		 */
21105 		if (sd_pm_entry(un) != DDI_SUCCESS) {
21106 			mutex_enter(SD_MUTEX(un));
21107 			goto done;
21108 		}
21109 
21110 		token = scsi_watch_request_submit(SD_SCSI_DEVP(un),
21111 		    sd_check_media_time, SENSE_LENGTH, sd_media_watch_cb,
21112 		    (caddr_t)dev);
21113 
21114 		sd_pm_exit(un);
21115 
21116 		mutex_enter(SD_MUTEX(un));
21117 		if (token == NULL) {
21118 			rval = EAGAIN;
21119 			goto done;
21120 		}
21121 
21122 		/*
21123 		 * This is a special case IOCTL that doesn't return
21124 		 * until the media state changes. Routine sdpower
21125 		 * knows about and handles this so don't count it
21126 		 * as an active cmd in the driver, which would
21127 		 * keep the device busy to the pm framework.
21128 		 * If the count isn't decremented the device can't
21129 		 * be powered down.
21130 		 */
21131 		un->un_ncmds_in_driver--;
21132 		ASSERT(un->un_ncmds_in_driver >= 0);
21133 
21134 		/*
21135 		 * if a prior request had been made, this will be the same
21136 		 * token, as scsi_watch was designed that way.
21137 		 */
21138 		un->un_swr_token = token;
21139 		un->un_specified_mediastate = state;
21140 
21141 		/*
21142 		 * now wait for media change
21143 		 * we will not be signalled unless mediastate == state but it is
21144 		 * still better to test for this condition, since there is a
21145 		 * 2 sec cv_broadcast delay when mediastate == DKIO_INSERTED
21146 		 */
21147 		SD_TRACE(SD_LOG_COMMON, un,
21148 		    "sd_check_media: waiting for media state change\n");
21149 		while (un->un_mediastate == state) {
21150 			if (cv_wait_sig(&un->un_state_cv, SD_MUTEX(un)) == 0) {
21151 				SD_TRACE(SD_LOG_COMMON, un,
21152 				    "sd_check_media: waiting for media state "
21153 				    "was interrupted\n");
21154 				un->un_ncmds_in_driver++;
21155 				rval = EINTR;
21156 				goto done;
21157 			}
21158 			SD_TRACE(SD_LOG_COMMON, un,
21159 			    "sd_check_media: received signal, state=%x\n",
21160 			    un->un_mediastate);
21161 		}
21162 		/*
21163 		 * Inc the counter to indicate the device once again
21164 		 * has an active outstanding cmd.
21165 		 */
21166 		un->un_ncmds_in_driver++;
21167 	}
21168 
21169 	/* invalidate geometry */
21170 	if (prev_state == DKIO_INSERTED && un->un_mediastate == DKIO_EJECTED) {
21171 		sr_ejected(un);
21172 	}
21173 
21174 	if (un->un_mediastate == DKIO_INSERTED && prev_state != DKIO_INSERTED) {
21175 		uint64_t	capacity;
21176 		uint_t		lbasize;
21177 
21178 		SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: media inserted\n");
21179 		mutex_exit(SD_MUTEX(un));
21180 		/*
21181 		 * Since the following routines use SD_PATH_DIRECT, we must
21182 		 * call PM directly before the upcoming disk accesses. This
21183 		 * may cause the disk to be power/spin up.
21184 		 */
21185 
21186 		if (sd_pm_entry(un) == DDI_SUCCESS) {
21187 			rval = sd_send_scsi_READ_CAPACITY(un,
21188 			    &capacity,
21189 			    &lbasize, SD_PATH_DIRECT);
21190 			if (rval != 0) {
21191 				sd_pm_exit(un);
21192 				mutex_enter(SD_MUTEX(un));
21193 				goto done;
21194 			}
21195 		} else {
21196 			rval = EIO;
21197 			mutex_enter(SD_MUTEX(un));
21198 			goto done;
21199 		}
21200 		mutex_enter(SD_MUTEX(un));
21201 
21202 		sd_update_block_info(un, lbasize, capacity);
21203 
21204 		/*
21205 		 *  Check if the media in the device is writable or not
21206 		 */
21207 		if (ISCD(un))
21208 			sd_check_for_writable_cd(un, SD_PATH_DIRECT);
21209 
21210 		mutex_exit(SD_MUTEX(un));
21211 		cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT);
21212 		if ((cmlb_validate(un->un_cmlbhandle, 0,
21213 		    (void *)SD_PATH_DIRECT) == 0) && un->un_f_pkstats_enabled) {
21214 			sd_set_pstats(un);
21215 			SD_TRACE(SD_LOG_IO_PARTITION, un,
21216 			    "sd_check_media: un:0x%p pstats created and "
21217 			    "set\n", un);
21218 		}
21219 
21220 		rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_PREVENT,
21221 		    SD_PATH_DIRECT);
21222 		sd_pm_exit(un);
21223 
21224 		mutex_enter(SD_MUTEX(un));
21225 	}
21226 done:
21227 	un->un_f_watcht_stopped = FALSE;
21228 	if (un->un_swr_token) {
21229 		/*
21230 		 * Use of this local token and the mutex ensures that we avoid
21231 		 * some race conditions associated with terminating the
21232 		 * scsi watch.
21233 		 */
21234 		token = un->un_swr_token;
21235 		un->un_swr_token = (opaque_t)NULL;
21236 		mutex_exit(SD_MUTEX(un));
21237 		(void) scsi_watch_request_terminate(token,
21238 		    SCSI_WATCH_TERMINATE_WAIT);
21239 		mutex_enter(SD_MUTEX(un));
21240 	}
21241 
21242 	/*
21243 	 * Update the capacity kstat value, if no media previously
21244 	 * (capacity kstat is 0) and a media has been inserted
21245 	 * (un_f_blockcount_is_valid == TRUE)
21246 	 */
21247 	if (un->un_errstats) {
21248 		struct sd_errstats	*stp = NULL;
21249 
21250 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
21251 		if ((stp->sd_capacity.value.ui64 == 0) &&
21252 		    (un->un_f_blockcount_is_valid == TRUE)) {
21253 			stp->sd_capacity.value.ui64 =
21254 			    (uint64_t)((uint64_t)un->un_blockcount *
21255 			    un->un_sys_blocksize);
21256 		}
21257 	}
21258 	mutex_exit(SD_MUTEX(un));
21259 	SD_TRACE(SD_LOG_COMMON, un, "sd_check_media: done\n");
21260 	return (rval);
21261 }
21262 
21263 
21264 /*
21265  *    Function: sd_delayed_cv_broadcast
21266  *
21267  * Description: Delayed cv_broadcast to allow for target to recover from media
21268  *		insertion.
21269  *
21270  *   Arguments: arg - driver soft state (unit) structure
21271  */
21272 
21273 static void
21274 sd_delayed_cv_broadcast(void *arg)
21275 {
21276 	struct sd_lun *un = arg;
21277 
21278 	SD_TRACE(SD_LOG_COMMON, un, "sd_delayed_cv_broadcast\n");
21279 
21280 	mutex_enter(SD_MUTEX(un));
21281 	un->un_dcvb_timeid = NULL;
21282 	cv_broadcast(&un->un_state_cv);
21283 	mutex_exit(SD_MUTEX(un));
21284 }
21285 
21286 
21287 /*
21288  *    Function: sd_media_watch_cb
21289  *
21290  * Description: Callback routine used for support of the DKIOCSTATE ioctl. This
21291  *		routine processes the TUR sense data and updates the driver
21292  *		state if a transition has occurred. The user thread
21293  *		(sd_check_media) is then signalled.
21294  *
21295  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
21296  *			among multiple watches that share this callback function
21297  *		resultp - scsi watch facility result packet containing scsi
21298  *			  packet, status byte and sense data
21299  *
21300  * Return Code: 0 for success, -1 for failure
21301  */
21302 
21303 static int
21304 sd_media_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
21305 {
21306 	struct sd_lun			*un;
21307 	struct scsi_status		*statusp = resultp->statusp;
21308 	uint8_t				*sensep = (uint8_t *)resultp->sensep;
21309 	enum dkio_state			state = DKIO_NONE;
21310 	dev_t				dev = (dev_t)arg;
21311 	uchar_t				actual_sense_length;
21312 	uint8_t				skey, asc, ascq;
21313 
21314 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21315 		return (-1);
21316 	}
21317 	actual_sense_length = resultp->actual_sense_length;
21318 
21319 	mutex_enter(SD_MUTEX(un));
21320 	SD_TRACE(SD_LOG_COMMON, un,
21321 	    "sd_media_watch_cb: status=%x, sensep=%p, len=%x\n",
21322 	    *((char *)statusp), (void *)sensep, actual_sense_length);
21323 
21324 	if (resultp->pkt->pkt_reason == CMD_DEV_GONE) {
21325 		un->un_mediastate = DKIO_DEV_GONE;
21326 		cv_broadcast(&un->un_state_cv);
21327 		mutex_exit(SD_MUTEX(un));
21328 
21329 		return (0);
21330 	}
21331 
21332 	/*
21333 	 * If there was a check condition then sensep points to valid sense data
21334 	 * If status was not a check condition but a reservation or busy status
21335 	 * then the new state is DKIO_NONE
21336 	 */
21337 	if (sensep != NULL) {
21338 		skey = scsi_sense_key(sensep);
21339 		asc = scsi_sense_asc(sensep);
21340 		ascq = scsi_sense_ascq(sensep);
21341 
21342 		SD_INFO(SD_LOG_COMMON, un,
21343 		    "sd_media_watch_cb: sense KEY=%x, ASC=%x, ASCQ=%x\n",
21344 		    skey, asc, ascq);
21345 		/* This routine only uses up to 13 bytes of sense data. */
21346 		if (actual_sense_length >= 13) {
21347 			if (skey == KEY_UNIT_ATTENTION) {
21348 				if (asc == 0x28) {
21349 					state = DKIO_INSERTED;
21350 				}
21351 			} else if (skey == KEY_NOT_READY) {
21352 				/*
21353 				 * if 02/04/02  means that the host
21354 				 * should send start command. Explicitly
21355 				 * leave the media state as is
21356 				 * (inserted) as the media is inserted
21357 				 * and host has stopped device for PM
21358 				 * reasons. Upon next true read/write
21359 				 * to this media will bring the
21360 				 * device to the right state good for
21361 				 * media access.
21362 				 */
21363 				if (asc == 0x3a) {
21364 					state = DKIO_EJECTED;
21365 				} else {
21366 					/*
21367 					 * If the drive is busy with an
21368 					 * operation or long write, keep the
21369 					 * media in an inserted state.
21370 					 */
21371 
21372 					if ((asc == 0x04) &&
21373 					    ((ascq == 0x02) ||
21374 					    (ascq == 0x07) ||
21375 					    (ascq == 0x08))) {
21376 						state = DKIO_INSERTED;
21377 					}
21378 				}
21379 			} else if (skey == KEY_NO_SENSE) {
21380 				if ((asc == 0x00) && (ascq == 0x00)) {
21381 					/*
21382 					 * Sense Data 00/00/00 does not provide
21383 					 * any information about the state of
21384 					 * the media. Ignore it.
21385 					 */
21386 					mutex_exit(SD_MUTEX(un));
21387 					return (0);
21388 				}
21389 			}
21390 		}
21391 	} else if ((*((char *)statusp) == STATUS_GOOD) &&
21392 	    (resultp->pkt->pkt_reason == CMD_CMPLT)) {
21393 		state = DKIO_INSERTED;
21394 	}
21395 
21396 	SD_TRACE(SD_LOG_COMMON, un,
21397 	    "sd_media_watch_cb: state=%x, specified=%x\n",
21398 	    state, un->un_specified_mediastate);
21399 
21400 	/*
21401 	 * now signal the waiting thread if this is *not* the specified state;
21402 	 * delay the signal if the state is DKIO_INSERTED to allow the target
21403 	 * to recover
21404 	 */
21405 	if (state != un->un_specified_mediastate) {
21406 		un->un_mediastate = state;
21407 		if (state == DKIO_INSERTED) {
21408 			/*
21409 			 * delay the signal to give the drive a chance
21410 			 * to do what it apparently needs to do
21411 			 */
21412 			SD_TRACE(SD_LOG_COMMON, un,
21413 			    "sd_media_watch_cb: delayed cv_broadcast\n");
21414 			if (un->un_dcvb_timeid == NULL) {
21415 				un->un_dcvb_timeid =
21416 				    timeout(sd_delayed_cv_broadcast, un,
21417 				    drv_usectohz((clock_t)MEDIA_ACCESS_DELAY));
21418 			}
21419 		} else {
21420 			SD_TRACE(SD_LOG_COMMON, un,
21421 			    "sd_media_watch_cb: immediate cv_broadcast\n");
21422 			cv_broadcast(&un->un_state_cv);
21423 		}
21424 	}
21425 	mutex_exit(SD_MUTEX(un));
21426 	return (0);
21427 }
21428 
21429 
21430 /*
21431  *    Function: sd_dkio_get_temp
21432  *
21433  * Description: This routine is the driver entry point for handling ioctl
21434  *		requests to get the disk temperature.
21435  *
21436  *   Arguments: dev  - the device number
21437  *		arg  - pointer to user provided dk_temperature structure.
21438  *		flag - this argument is a pass through to ddi_copyxxx()
21439  *		       directly from the mode argument of ioctl().
21440  *
21441  * Return Code: 0
21442  *		EFAULT
21443  *		ENXIO
21444  *		EAGAIN
21445  */
21446 
21447 static int
21448 sd_dkio_get_temp(dev_t dev, caddr_t arg, int flag)
21449 {
21450 	struct sd_lun		*un = NULL;
21451 	struct dk_temperature	*dktemp = NULL;
21452 	uchar_t			*temperature_page;
21453 	int			rval = 0;
21454 	int			path_flag = SD_PATH_STANDARD;
21455 
21456 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21457 		return (ENXIO);
21458 	}
21459 
21460 	dktemp = kmem_zalloc(sizeof (struct dk_temperature), KM_SLEEP);
21461 
21462 	/* copyin the disk temp argument to get the user flags */
21463 	if (ddi_copyin((void *)arg, dktemp,
21464 	    sizeof (struct dk_temperature), flag) != 0) {
21465 		rval = EFAULT;
21466 		goto done;
21467 	}
21468 
21469 	/* Initialize the temperature to invalid. */
21470 	dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
21471 	dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
21472 
21473 	/*
21474 	 * Note: Investigate removing the "bypass pm" semantic.
21475 	 * Can we just bypass PM always?
21476 	 */
21477 	if (dktemp->dkt_flags & DKT_BYPASS_PM) {
21478 		path_flag = SD_PATH_DIRECT;
21479 		ASSERT(!mutex_owned(&un->un_pm_mutex));
21480 		mutex_enter(&un->un_pm_mutex);
21481 		if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
21482 			/*
21483 			 * If DKT_BYPASS_PM is set, and the drive happens to be
21484 			 * in low power mode, we can not wake it up, Need to
21485 			 * return EAGAIN.
21486 			 */
21487 			mutex_exit(&un->un_pm_mutex);
21488 			rval = EAGAIN;
21489 			goto done;
21490 		} else {
21491 			/*
21492 			 * Indicate to PM the device is busy. This is required
21493 			 * to avoid a race - i.e. the ioctl is issuing a
21494 			 * command and the pm framework brings down the device
21495 			 * to low power mode (possible power cut-off on some
21496 			 * platforms).
21497 			 */
21498 			mutex_exit(&un->un_pm_mutex);
21499 			if (sd_pm_entry(un) != DDI_SUCCESS) {
21500 				rval = EAGAIN;
21501 				goto done;
21502 			}
21503 		}
21504 	}
21505 
21506 	temperature_page = kmem_zalloc(TEMPERATURE_PAGE_SIZE, KM_SLEEP);
21507 
21508 	if ((rval = sd_send_scsi_LOG_SENSE(un, temperature_page,
21509 	    TEMPERATURE_PAGE_SIZE, TEMPERATURE_PAGE, 1, 0, path_flag)) != 0) {
21510 		goto done2;
21511 	}
21512 
21513 	/*
21514 	 * For the current temperature verify that the parameter length is 0x02
21515 	 * and the parameter code is 0x00
21516 	 */
21517 	if ((temperature_page[7] == 0x02) && (temperature_page[4] == 0x00) &&
21518 	    (temperature_page[5] == 0x00)) {
21519 		if (temperature_page[9] == 0xFF) {
21520 			dktemp->dkt_cur_temp = (short)DKT_INVALID_TEMP;
21521 		} else {
21522 			dktemp->dkt_cur_temp = (short)(temperature_page[9]);
21523 		}
21524 	}
21525 
21526 	/*
21527 	 * For the reference temperature verify that the parameter
21528 	 * length is 0x02 and the parameter code is 0x01
21529 	 */
21530 	if ((temperature_page[13] == 0x02) && (temperature_page[10] == 0x00) &&
21531 	    (temperature_page[11] == 0x01)) {
21532 		if (temperature_page[15] == 0xFF) {
21533 			dktemp->dkt_ref_temp = (short)DKT_INVALID_TEMP;
21534 		} else {
21535 			dktemp->dkt_ref_temp = (short)(temperature_page[15]);
21536 		}
21537 	}
21538 
21539 	/* Do the copyout regardless of the temperature commands status. */
21540 	if (ddi_copyout(dktemp, (void *)arg, sizeof (struct dk_temperature),
21541 	    flag) != 0) {
21542 		rval = EFAULT;
21543 	}
21544 
21545 done2:
21546 	if (path_flag == SD_PATH_DIRECT) {
21547 		sd_pm_exit(un);
21548 	}
21549 
21550 	kmem_free(temperature_page, TEMPERATURE_PAGE_SIZE);
21551 done:
21552 	if (dktemp != NULL) {
21553 		kmem_free(dktemp, sizeof (struct dk_temperature));
21554 	}
21555 
21556 	return (rval);
21557 }
21558 
21559 
21560 /*
21561  *    Function: sd_log_page_supported
21562  *
21563  * Description: This routine uses sd_send_scsi_LOG_SENSE to find the list of
21564  *		supported log pages.
21565  *
21566  *   Arguments: un -
21567  *		log_page -
21568  *
21569  * Return Code: -1 - on error (log sense is optional and may not be supported).
21570  *		0  - log page not found.
21571  *  		1  - log page found.
21572  */
21573 
21574 static int
21575 sd_log_page_supported(struct sd_lun *un, int log_page)
21576 {
21577 	uchar_t *log_page_data;
21578 	int	i;
21579 	int	match = 0;
21580 	int	log_size;
21581 
21582 	log_page_data = kmem_zalloc(0xFF, KM_SLEEP);
21583 
21584 	if (sd_send_scsi_LOG_SENSE(un, log_page_data, 0xFF, 0, 0x01, 0,
21585 	    SD_PATH_DIRECT) != 0) {
21586 		SD_ERROR(SD_LOG_COMMON, un,
21587 		    "sd_log_page_supported: failed log page retrieval\n");
21588 		kmem_free(log_page_data, 0xFF);
21589 		return (-1);
21590 	}
21591 	log_size = log_page_data[3];
21592 
21593 	/*
21594 	 * The list of supported log pages start from the fourth byte. Check
21595 	 * until we run out of log pages or a match is found.
21596 	 */
21597 	for (i = 4; (i < (log_size + 4)) && !match; i++) {
21598 		if (log_page_data[i] == log_page) {
21599 			match++;
21600 		}
21601 	}
21602 	kmem_free(log_page_data, 0xFF);
21603 	return (match);
21604 }
21605 
21606 
21607 /*
21608  *    Function: sd_mhdioc_failfast
21609  *
21610  * Description: This routine is the driver entry point for handling ioctl
21611  *		requests to enable/disable the multihost failfast option.
21612  *		(MHIOCENFAILFAST)
21613  *
21614  *   Arguments: dev	- the device number
21615  *		arg	- user specified probing interval.
21616  *		flag	- this argument is a pass through to ddi_copyxxx()
21617  *			  directly from the mode argument of ioctl().
21618  *
21619  * Return Code: 0
21620  *		EFAULT
21621  *		ENXIO
21622  */
21623 
21624 static int
21625 sd_mhdioc_failfast(dev_t dev, caddr_t arg, int flag)
21626 {
21627 	struct sd_lun	*un = NULL;
21628 	int		mh_time;
21629 	int		rval = 0;
21630 
21631 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21632 		return (ENXIO);
21633 	}
21634 
21635 	if (ddi_copyin((void *)arg, &mh_time, sizeof (int), flag))
21636 		return (EFAULT);
21637 
21638 	if (mh_time) {
21639 		mutex_enter(SD_MUTEX(un));
21640 		un->un_resvd_status |= SD_FAILFAST;
21641 		mutex_exit(SD_MUTEX(un));
21642 		/*
21643 		 * If mh_time is INT_MAX, then this ioctl is being used for
21644 		 * SCSI-3 PGR purposes, and we don't need to spawn watch thread.
21645 		 */
21646 		if (mh_time != INT_MAX) {
21647 			rval = sd_check_mhd(dev, mh_time);
21648 		}
21649 	} else {
21650 		(void) sd_check_mhd(dev, 0);
21651 		mutex_enter(SD_MUTEX(un));
21652 		un->un_resvd_status &= ~SD_FAILFAST;
21653 		mutex_exit(SD_MUTEX(un));
21654 	}
21655 	return (rval);
21656 }
21657 
21658 
21659 /*
21660  *    Function: sd_mhdioc_takeown
21661  *
21662  * Description: This routine is the driver entry point for handling ioctl
21663  *		requests to forcefully acquire exclusive access rights to the
21664  *		multihost disk (MHIOCTKOWN).
21665  *
21666  *   Arguments: dev	- the device number
21667  *		arg	- user provided structure specifying the delay
21668  *			  parameters in milliseconds
21669  *		flag	- this argument is a pass through to ddi_copyxxx()
21670  *			  directly from the mode argument of ioctl().
21671  *
21672  * Return Code: 0
21673  *		EFAULT
21674  *		ENXIO
21675  */
21676 
21677 static int
21678 sd_mhdioc_takeown(dev_t dev, caddr_t arg, int flag)
21679 {
21680 	struct sd_lun		*un = NULL;
21681 	struct mhioctkown	*tkown = NULL;
21682 	int			rval = 0;
21683 
21684 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21685 		return (ENXIO);
21686 	}
21687 
21688 	if (arg != NULL) {
21689 		tkown = (struct mhioctkown *)
21690 		    kmem_zalloc(sizeof (struct mhioctkown), KM_SLEEP);
21691 		rval = ddi_copyin(arg, tkown, sizeof (struct mhioctkown), flag);
21692 		if (rval != 0) {
21693 			rval = EFAULT;
21694 			goto error;
21695 		}
21696 	}
21697 
21698 	rval = sd_take_ownership(dev, tkown);
21699 	mutex_enter(SD_MUTEX(un));
21700 	if (rval == 0) {
21701 		un->un_resvd_status |= SD_RESERVE;
21702 		if (tkown != NULL && tkown->reinstate_resv_delay != 0) {
21703 			sd_reinstate_resv_delay =
21704 			    tkown->reinstate_resv_delay * 1000;
21705 		} else {
21706 			sd_reinstate_resv_delay = SD_REINSTATE_RESV_DELAY;
21707 		}
21708 		/*
21709 		 * Give the scsi_watch routine interval set by
21710 		 * the MHIOCENFAILFAST ioctl precedence here.
21711 		 */
21712 		if ((un->un_resvd_status & SD_FAILFAST) == 0) {
21713 			mutex_exit(SD_MUTEX(un));
21714 			(void) sd_check_mhd(dev, sd_reinstate_resv_delay/1000);
21715 			SD_TRACE(SD_LOG_IOCTL_MHD, un,
21716 			    "sd_mhdioc_takeown : %d\n",
21717 			    sd_reinstate_resv_delay);
21718 		} else {
21719 			mutex_exit(SD_MUTEX(un));
21720 		}
21721 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_NOTIFY,
21722 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21723 	} else {
21724 		un->un_resvd_status &= ~SD_RESERVE;
21725 		mutex_exit(SD_MUTEX(un));
21726 	}
21727 
21728 error:
21729 	if (tkown != NULL) {
21730 		kmem_free(tkown, sizeof (struct mhioctkown));
21731 	}
21732 	return (rval);
21733 }
21734 
21735 
21736 /*
21737  *    Function: sd_mhdioc_release
21738  *
21739  * Description: This routine is the driver entry point for handling ioctl
21740  *		requests to release exclusive access rights to the multihost
21741  *		disk (MHIOCRELEASE).
21742  *
21743  *   Arguments: dev	- the device number
21744  *
21745  * Return Code: 0
21746  *		ENXIO
21747  */
21748 
21749 static int
21750 sd_mhdioc_release(dev_t dev)
21751 {
21752 	struct sd_lun		*un = NULL;
21753 	timeout_id_t		resvd_timeid_save;
21754 	int			resvd_status_save;
21755 	int			rval = 0;
21756 
21757 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21758 		return (ENXIO);
21759 	}
21760 
21761 	mutex_enter(SD_MUTEX(un));
21762 	resvd_status_save = un->un_resvd_status;
21763 	un->un_resvd_status &=
21764 	    ~(SD_RESERVE | SD_LOST_RESERVE | SD_WANT_RESERVE);
21765 	if (un->un_resvd_timeid) {
21766 		resvd_timeid_save = un->un_resvd_timeid;
21767 		un->un_resvd_timeid = NULL;
21768 		mutex_exit(SD_MUTEX(un));
21769 		(void) untimeout(resvd_timeid_save);
21770 	} else {
21771 		mutex_exit(SD_MUTEX(un));
21772 	}
21773 
21774 	/*
21775 	 * destroy any pending timeout thread that may be attempting to
21776 	 * reinstate reservation on this device.
21777 	 */
21778 	sd_rmv_resv_reclaim_req(dev);
21779 
21780 	if ((rval = sd_reserve_release(dev, SD_RELEASE)) == 0) {
21781 		mutex_enter(SD_MUTEX(un));
21782 		if ((un->un_mhd_token) &&
21783 		    ((un->un_resvd_status & SD_FAILFAST) == 0)) {
21784 			mutex_exit(SD_MUTEX(un));
21785 			(void) sd_check_mhd(dev, 0);
21786 		} else {
21787 			mutex_exit(SD_MUTEX(un));
21788 		}
21789 		(void) scsi_reset_notify(SD_ADDRESS(un), SCSI_RESET_CANCEL,
21790 		    sd_mhd_reset_notify_cb, (caddr_t)un);
21791 	} else {
21792 		/*
21793 		 * sd_mhd_watch_cb will restart the resvd recover timeout thread
21794 		 */
21795 		mutex_enter(SD_MUTEX(un));
21796 		un->un_resvd_status = resvd_status_save;
21797 		mutex_exit(SD_MUTEX(un));
21798 	}
21799 	return (rval);
21800 }
21801 
21802 
21803 /*
21804  *    Function: sd_mhdioc_register_devid
21805  *
21806  * Description: This routine is the driver entry point for handling ioctl
21807  *		requests to register the device id (MHIOCREREGISTERDEVID).
21808  *
21809  *		Note: The implementation for this ioctl has been updated to
21810  *		be consistent with the original PSARC case (1999/357)
21811  *		(4375899, 4241671, 4220005)
21812  *
21813  *   Arguments: dev	- the device number
21814  *
21815  * Return Code: 0
21816  *		ENXIO
21817  */
21818 
21819 static int
21820 sd_mhdioc_register_devid(dev_t dev)
21821 {
21822 	struct sd_lun	*un = NULL;
21823 	int		rval = 0;
21824 
21825 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21826 		return (ENXIO);
21827 	}
21828 
21829 	ASSERT(!mutex_owned(SD_MUTEX(un)));
21830 
21831 	mutex_enter(SD_MUTEX(un));
21832 
21833 	/* If a devid already exists, de-register it */
21834 	if (un->un_devid != NULL) {
21835 		ddi_devid_unregister(SD_DEVINFO(un));
21836 		/*
21837 		 * After unregister devid, needs to free devid memory
21838 		 */
21839 		ddi_devid_free(un->un_devid);
21840 		un->un_devid = NULL;
21841 	}
21842 
21843 	/* Check for reservation conflict */
21844 	mutex_exit(SD_MUTEX(un));
21845 	rval = sd_send_scsi_TEST_UNIT_READY(un, 0);
21846 	mutex_enter(SD_MUTEX(un));
21847 
21848 	switch (rval) {
21849 	case 0:
21850 		sd_register_devid(un, SD_DEVINFO(un), SD_TARGET_IS_UNRESERVED);
21851 		break;
21852 	case EACCES:
21853 		break;
21854 	default:
21855 		rval = EIO;
21856 	}
21857 
21858 	mutex_exit(SD_MUTEX(un));
21859 	return (rval);
21860 }
21861 
21862 
21863 /*
21864  *    Function: sd_mhdioc_inkeys
21865  *
21866  * Description: This routine is the driver entry point for handling ioctl
21867  *		requests to issue the SCSI-3 Persistent In Read Keys command
21868  *		to the device (MHIOCGRP_INKEYS).
21869  *
21870  *   Arguments: dev	- the device number
21871  *		arg	- user provided in_keys structure
21872  *		flag	- this argument is a pass through to ddi_copyxxx()
21873  *			  directly from the mode argument of ioctl().
21874  *
21875  * Return Code: code returned by sd_persistent_reservation_in_read_keys()
21876  *		ENXIO
21877  *		EFAULT
21878  */
21879 
21880 static int
21881 sd_mhdioc_inkeys(dev_t dev, caddr_t arg, int flag)
21882 {
21883 	struct sd_lun		*un;
21884 	mhioc_inkeys_t		inkeys;
21885 	int			rval = 0;
21886 
21887 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21888 		return (ENXIO);
21889 	}
21890 
21891 #ifdef _MULTI_DATAMODEL
21892 	switch (ddi_model_convert_from(flag & FMODELS)) {
21893 	case DDI_MODEL_ILP32: {
21894 		struct mhioc_inkeys32	inkeys32;
21895 
21896 		if (ddi_copyin(arg, &inkeys32,
21897 		    sizeof (struct mhioc_inkeys32), flag) != 0) {
21898 			return (EFAULT);
21899 		}
21900 		inkeys.li = (mhioc_key_list_t *)(uintptr_t)inkeys32.li;
21901 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21902 		    &inkeys, flag)) != 0) {
21903 			return (rval);
21904 		}
21905 		inkeys32.generation = inkeys.generation;
21906 		if (ddi_copyout(&inkeys32, arg, sizeof (struct mhioc_inkeys32),
21907 		    flag) != 0) {
21908 			return (EFAULT);
21909 		}
21910 		break;
21911 	}
21912 	case DDI_MODEL_NONE:
21913 		if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t),
21914 		    flag) != 0) {
21915 			return (EFAULT);
21916 		}
21917 		if ((rval = sd_persistent_reservation_in_read_keys(un,
21918 		    &inkeys, flag)) != 0) {
21919 			return (rval);
21920 		}
21921 		if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t),
21922 		    flag) != 0) {
21923 			return (EFAULT);
21924 		}
21925 		break;
21926 	}
21927 
21928 #else /* ! _MULTI_DATAMODEL */
21929 
21930 	if (ddi_copyin(arg, &inkeys, sizeof (mhioc_inkeys_t), flag) != 0) {
21931 		return (EFAULT);
21932 	}
21933 	rval = sd_persistent_reservation_in_read_keys(un, &inkeys, flag);
21934 	if (rval != 0) {
21935 		return (rval);
21936 	}
21937 	if (ddi_copyout(&inkeys, arg, sizeof (mhioc_inkeys_t), flag) != 0) {
21938 		return (EFAULT);
21939 	}
21940 
21941 #endif /* _MULTI_DATAMODEL */
21942 
21943 	return (rval);
21944 }
21945 
21946 
21947 /*
21948  *    Function: sd_mhdioc_inresv
21949  *
21950  * Description: This routine is the driver entry point for handling ioctl
21951  *		requests to issue the SCSI-3 Persistent In Read Reservations
21952  *		command to the device (MHIOCGRP_INKEYS).
21953  *
21954  *   Arguments: dev	- the device number
21955  *		arg	- user provided in_resv structure
21956  *		flag	- this argument is a pass through to ddi_copyxxx()
21957  *			  directly from the mode argument of ioctl().
21958  *
21959  * Return Code: code returned by sd_persistent_reservation_in_read_resv()
21960  *		ENXIO
21961  *		EFAULT
21962  */
21963 
21964 static int
21965 sd_mhdioc_inresv(dev_t dev, caddr_t arg, int flag)
21966 {
21967 	struct sd_lun		*un;
21968 	mhioc_inresvs_t		inresvs;
21969 	int			rval = 0;
21970 
21971 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
21972 		return (ENXIO);
21973 	}
21974 
21975 #ifdef _MULTI_DATAMODEL
21976 
21977 	switch (ddi_model_convert_from(flag & FMODELS)) {
21978 	case DDI_MODEL_ILP32: {
21979 		struct mhioc_inresvs32	inresvs32;
21980 
21981 		if (ddi_copyin(arg, &inresvs32,
21982 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21983 			return (EFAULT);
21984 		}
21985 		inresvs.li = (mhioc_resv_desc_list_t *)(uintptr_t)inresvs32.li;
21986 		if ((rval = sd_persistent_reservation_in_read_resv(un,
21987 		    &inresvs, flag)) != 0) {
21988 			return (rval);
21989 		}
21990 		inresvs32.generation = inresvs.generation;
21991 		if (ddi_copyout(&inresvs32, arg,
21992 		    sizeof (struct mhioc_inresvs32), flag) != 0) {
21993 			return (EFAULT);
21994 		}
21995 		break;
21996 	}
21997 	case DDI_MODEL_NONE:
21998 		if (ddi_copyin(arg, &inresvs,
21999 		    sizeof (mhioc_inresvs_t), flag) != 0) {
22000 			return (EFAULT);
22001 		}
22002 		if ((rval = sd_persistent_reservation_in_read_resv(un,
22003 		    &inresvs, flag)) != 0) {
22004 			return (rval);
22005 		}
22006 		if (ddi_copyout(&inresvs, arg,
22007 		    sizeof (mhioc_inresvs_t), flag) != 0) {
22008 			return (EFAULT);
22009 		}
22010 		break;
22011 	}
22012 
22013 #else /* ! _MULTI_DATAMODEL */
22014 
22015 	if (ddi_copyin(arg, &inresvs, sizeof (mhioc_inresvs_t), flag) != 0) {
22016 		return (EFAULT);
22017 	}
22018 	rval = sd_persistent_reservation_in_read_resv(un, &inresvs, flag);
22019 	if (rval != 0) {
22020 		return (rval);
22021 	}
22022 	if (ddi_copyout(&inresvs, arg, sizeof (mhioc_inresvs_t), flag)) {
22023 		return (EFAULT);
22024 	}
22025 
22026 #endif /* ! _MULTI_DATAMODEL */
22027 
22028 	return (rval);
22029 }
22030 
22031 
22032 /*
22033  * The following routines support the clustering functionality described below
22034  * and implement lost reservation reclaim functionality.
22035  *
22036  * Clustering
22037  * ----------
22038  * The clustering code uses two different, independent forms of SCSI
22039  * reservation. Traditional SCSI-2 Reserve/Release and the newer SCSI-3
22040  * Persistent Group Reservations. For any particular disk, it will use either
22041  * SCSI-2 or SCSI-3 PGR but never both at the same time for the same disk.
22042  *
22043  * SCSI-2
22044  * The cluster software takes ownership of a multi-hosted disk by issuing the
22045  * MHIOCTKOWN ioctl to the disk driver. It releases ownership by issuing the
22046  * MHIOCRELEASE ioctl.  Closely related is the MHIOCENFAILFAST ioctl -- a
22047  * cluster, just after taking ownership of the disk with the MHIOCTKOWN ioctl
22048  * then issues the MHIOCENFAILFAST ioctl.  This ioctl "enables failfast" in the
22049  * driver. The meaning of failfast is that if the driver (on this host) ever
22050  * encounters the scsi error return code RESERVATION_CONFLICT from the device,
22051  * it should immediately panic the host. The motivation for this ioctl is that
22052  * if this host does encounter reservation conflict, the underlying cause is
22053  * that some other host of the cluster has decided that this host is no longer
22054  * in the cluster and has seized control of the disks for itself. Since this
22055  * host is no longer in the cluster, it ought to panic itself. The
22056  * MHIOCENFAILFAST ioctl does two things:
22057  *	(a) it sets a flag that will cause any returned RESERVATION_CONFLICT
22058  *      error to panic the host
22059  *      (b) it sets up a periodic timer to test whether this host still has
22060  *      "access" (in that no other host has reserved the device):  if the
22061  *      periodic timer gets RESERVATION_CONFLICT, the host is panicked. The
22062  *      purpose of that periodic timer is to handle scenarios where the host is
22063  *      otherwise temporarily quiescent, temporarily doing no real i/o.
22064  * The MHIOCTKOWN ioctl will "break" a reservation that is held by another host,
22065  * by issuing a SCSI Bus Device Reset.  It will then issue a SCSI Reserve for
22066  * the device itself.
22067  *
22068  * SCSI-3 PGR
22069  * A direct semantic implementation of the SCSI-3 Persistent Reservation
22070  * facility is supported through the shared multihost disk ioctls
22071  * (MHIOCGRP_INKEYS, MHIOCGRP_INRESV, MHIOCGRP_REGISTER, MHIOCGRP_RESERVE,
22072  * MHIOCGRP_PREEMPTANDABORT)
22073  *
22074  * Reservation Reclaim:
22075  * --------------------
22076  * To support the lost reservation reclaim operations this driver creates a
22077  * single thread to handle reinstating reservations on all devices that have
22078  * lost reservations sd_resv_reclaim_requests are logged for all devices that
22079  * have LOST RESERVATIONS when the scsi watch facility callsback sd_mhd_watch_cb
22080  * and the reservation reclaim thread loops through the requests to regain the
22081  * lost reservations.
22082  */
22083 
22084 /*
22085  *    Function: sd_check_mhd()
22086  *
22087  * Description: This function sets up and submits a scsi watch request or
22088  *		terminates an existing watch request. This routine is used in
22089  *		support of reservation reclaim.
22090  *
22091  *   Arguments: dev    - the device 'dev_t' is used for context to discriminate
22092  *			 among multiple watches that share the callback function
22093  *		interval - the number of microseconds specifying the watch
22094  *			   interval for issuing TEST UNIT READY commands. If
22095  *			   set to 0 the watch should be terminated. If the
22096  *			   interval is set to 0 and if the device is required
22097  *			   to hold reservation while disabling failfast, the
22098  *			   watch is restarted with an interval of
22099  *			   reinstate_resv_delay.
22100  *
22101  * Return Code: 0	   - Successful submit/terminate of scsi watch request
22102  *		ENXIO      - Indicates an invalid device was specified
22103  *		EAGAIN     - Unable to submit the scsi watch request
22104  */
22105 
22106 static int
22107 sd_check_mhd(dev_t dev, int interval)
22108 {
22109 	struct sd_lun	*un;
22110 	opaque_t	token;
22111 
22112 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22113 		return (ENXIO);
22114 	}
22115 
22116 	/* is this a watch termination request? */
22117 	if (interval == 0) {
22118 		mutex_enter(SD_MUTEX(un));
22119 		/* if there is an existing watch task then terminate it */
22120 		if (un->un_mhd_token) {
22121 			token = un->un_mhd_token;
22122 			un->un_mhd_token = NULL;
22123 			mutex_exit(SD_MUTEX(un));
22124 			(void) scsi_watch_request_terminate(token,
22125 			    SCSI_WATCH_TERMINATE_WAIT);
22126 			mutex_enter(SD_MUTEX(un));
22127 		} else {
22128 			mutex_exit(SD_MUTEX(un));
22129 			/*
22130 			 * Note: If we return here we don't check for the
22131 			 * failfast case. This is the original legacy
22132 			 * implementation but perhaps we should be checking
22133 			 * the failfast case.
22134 			 */
22135 			return (0);
22136 		}
22137 		/*
22138 		 * If the device is required to hold reservation while
22139 		 * disabling failfast, we need to restart the scsi_watch
22140 		 * routine with an interval of reinstate_resv_delay.
22141 		 */
22142 		if (un->un_resvd_status & SD_RESERVE) {
22143 			interval = sd_reinstate_resv_delay/1000;
22144 		} else {
22145 			/* no failfast so bail */
22146 			mutex_exit(SD_MUTEX(un));
22147 			return (0);
22148 		}
22149 		mutex_exit(SD_MUTEX(un));
22150 	}
22151 
22152 	/*
22153 	 * adjust minimum time interval to 1 second,
22154 	 * and convert from msecs to usecs
22155 	 */
22156 	if (interval > 0 && interval < 1000) {
22157 		interval = 1000;
22158 	}
22159 	interval *= 1000;
22160 
22161 	/*
22162 	 * submit the request to the scsi_watch service
22163 	 */
22164 	token = scsi_watch_request_submit(SD_SCSI_DEVP(un), interval,
22165 	    SENSE_LENGTH, sd_mhd_watch_cb, (caddr_t)dev);
22166 	if (token == NULL) {
22167 		return (EAGAIN);
22168 	}
22169 
22170 	/*
22171 	 * save token for termination later on
22172 	 */
22173 	mutex_enter(SD_MUTEX(un));
22174 	un->un_mhd_token = token;
22175 	mutex_exit(SD_MUTEX(un));
22176 	return (0);
22177 }
22178 
22179 
22180 /*
22181  *    Function: sd_mhd_watch_cb()
22182  *
22183  * Description: This function is the call back function used by the scsi watch
22184  *		facility. The scsi watch facility sends the "Test Unit Ready"
22185  *		and processes the status. If applicable (i.e. a "Unit Attention"
22186  *		status and automatic "Request Sense" not used) the scsi watch
22187  *		facility will send a "Request Sense" and retrieve the sense data
22188  *		to be passed to this callback function. In either case the
22189  *		automatic "Request Sense" or the facility submitting one, this
22190  *		callback is passed the status and sense data.
22191  *
22192  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
22193  *			among multiple watches that share this callback function
22194  *		resultp - scsi watch facility result packet containing scsi
22195  *			  packet, status byte and sense data
22196  *
22197  * Return Code: 0 - continue the watch task
22198  *		non-zero - terminate the watch task
22199  */
22200 
22201 static int
22202 sd_mhd_watch_cb(caddr_t arg, struct scsi_watch_result *resultp)
22203 {
22204 	struct sd_lun			*un;
22205 	struct scsi_status		*statusp;
22206 	uint8_t				*sensep;
22207 	struct scsi_pkt			*pkt;
22208 	uchar_t				actual_sense_length;
22209 	dev_t  				dev = (dev_t)arg;
22210 
22211 	ASSERT(resultp != NULL);
22212 	statusp			= resultp->statusp;
22213 	sensep			= (uint8_t *)resultp->sensep;
22214 	pkt			= resultp->pkt;
22215 	actual_sense_length	= resultp->actual_sense_length;
22216 
22217 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22218 		return (ENXIO);
22219 	}
22220 
22221 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
22222 	    "sd_mhd_watch_cb: reason '%s', status '%s'\n",
22223 	    scsi_rname(pkt->pkt_reason), sd_sname(*((unsigned char *)statusp)));
22224 
22225 	/* Begin processing of the status and/or sense data */
22226 	if (pkt->pkt_reason != CMD_CMPLT) {
22227 		/* Handle the incomplete packet */
22228 		sd_mhd_watch_incomplete(un, pkt);
22229 		return (0);
22230 	} else if (*((unsigned char *)statusp) != STATUS_GOOD) {
22231 		if (*((unsigned char *)statusp)
22232 		    == STATUS_RESERVATION_CONFLICT) {
22233 			/*
22234 			 * Handle a reservation conflict by panicking if
22235 			 * configured for failfast or by logging the conflict
22236 			 * and updating the reservation status
22237 			 */
22238 			mutex_enter(SD_MUTEX(un));
22239 			if ((un->un_resvd_status & SD_FAILFAST) &&
22240 			    (sd_failfast_enable)) {
22241 				sd_panic_for_res_conflict(un);
22242 				/*NOTREACHED*/
22243 			}
22244 			SD_INFO(SD_LOG_IOCTL_MHD, un,
22245 			    "sd_mhd_watch_cb: Reservation Conflict\n");
22246 			un->un_resvd_status |= SD_RESERVATION_CONFLICT;
22247 			mutex_exit(SD_MUTEX(un));
22248 		}
22249 	}
22250 
22251 	if (sensep != NULL) {
22252 		if (actual_sense_length >= (SENSE_LENGTH - 2)) {
22253 			mutex_enter(SD_MUTEX(un));
22254 			if ((scsi_sense_asc(sensep) ==
22255 			    SD_SCSI_RESET_SENSE_CODE) &&
22256 			    (un->un_resvd_status & SD_RESERVE)) {
22257 				/*
22258 				 * The additional sense code indicates a power
22259 				 * on or bus device reset has occurred; update
22260 				 * the reservation status.
22261 				 */
22262 				un->un_resvd_status |=
22263 				    (SD_LOST_RESERVE | SD_WANT_RESERVE);
22264 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22265 				    "sd_mhd_watch_cb: Lost Reservation\n");
22266 			}
22267 		} else {
22268 			return (0);
22269 		}
22270 	} else {
22271 		mutex_enter(SD_MUTEX(un));
22272 	}
22273 
22274 	if ((un->un_resvd_status & SD_RESERVE) &&
22275 	    (un->un_resvd_status & SD_LOST_RESERVE)) {
22276 		if (un->un_resvd_status & SD_WANT_RESERVE) {
22277 			/*
22278 			 * A reset occurred in between the last probe and this
22279 			 * one so if a timeout is pending cancel it.
22280 			 */
22281 			if (un->un_resvd_timeid) {
22282 				timeout_id_t temp_id = un->un_resvd_timeid;
22283 				un->un_resvd_timeid = NULL;
22284 				mutex_exit(SD_MUTEX(un));
22285 				(void) untimeout(temp_id);
22286 				mutex_enter(SD_MUTEX(un));
22287 			}
22288 			un->un_resvd_status &= ~SD_WANT_RESERVE;
22289 		}
22290 		if (un->un_resvd_timeid == 0) {
22291 			/* Schedule a timeout to handle the lost reservation */
22292 			un->un_resvd_timeid = timeout(sd_mhd_resvd_recover,
22293 			    (void *)dev,
22294 			    drv_usectohz(sd_reinstate_resv_delay));
22295 		}
22296 	}
22297 	mutex_exit(SD_MUTEX(un));
22298 	return (0);
22299 }
22300 
22301 
22302 /*
22303  *    Function: sd_mhd_watch_incomplete()
22304  *
22305  * Description: This function is used to find out why a scsi pkt sent by the
22306  *		scsi watch facility was not completed. Under some scenarios this
22307  *		routine will return. Otherwise it will send a bus reset to see
22308  *		if the drive is still online.
22309  *
22310  *   Arguments: un  - driver soft state (unit) structure
22311  *		pkt - incomplete scsi pkt
22312  */
22313 
22314 static void
22315 sd_mhd_watch_incomplete(struct sd_lun *un, struct scsi_pkt *pkt)
22316 {
22317 	int	be_chatty;
22318 	int	perr;
22319 
22320 	ASSERT(pkt != NULL);
22321 	ASSERT(un != NULL);
22322 	be_chatty	= (!(pkt->pkt_flags & FLAG_SILENT));
22323 	perr		= (pkt->pkt_statistics & STAT_PERR);
22324 
22325 	mutex_enter(SD_MUTEX(un));
22326 	if (un->un_state == SD_STATE_DUMPING) {
22327 		mutex_exit(SD_MUTEX(un));
22328 		return;
22329 	}
22330 
22331 	switch (pkt->pkt_reason) {
22332 	case CMD_UNX_BUS_FREE:
22333 		/*
22334 		 * If we had a parity error that caused the target to drop BSY*,
22335 		 * don't be chatty about it.
22336 		 */
22337 		if (perr && be_chatty) {
22338 			be_chatty = 0;
22339 		}
22340 		break;
22341 	case CMD_TAG_REJECT:
22342 		/*
22343 		 * The SCSI-2 spec states that a tag reject will be sent by the
22344 		 * target if tagged queuing is not supported. A tag reject may
22345 		 * also be sent during certain initialization periods or to
22346 		 * control internal resources. For the latter case the target
22347 		 * may also return Queue Full.
22348 		 *
22349 		 * If this driver receives a tag reject from a target that is
22350 		 * going through an init period or controlling internal
22351 		 * resources tagged queuing will be disabled. This is a less
22352 		 * than optimal behavior but the driver is unable to determine
22353 		 * the target state and assumes tagged queueing is not supported
22354 		 */
22355 		pkt->pkt_flags = 0;
22356 		un->un_tagflags = 0;
22357 
22358 		if (un->un_f_opt_queueing == TRUE) {
22359 			un->un_throttle = min(un->un_throttle, 3);
22360 		} else {
22361 			un->un_throttle = 1;
22362 		}
22363 		mutex_exit(SD_MUTEX(un));
22364 		(void) scsi_ifsetcap(SD_ADDRESS(un), "tagged-qing", 0, 1);
22365 		mutex_enter(SD_MUTEX(un));
22366 		break;
22367 	case CMD_INCOMPLETE:
22368 		/*
22369 		 * The transport stopped with an abnormal state, fallthrough and
22370 		 * reset the target and/or bus unless selection did not complete
22371 		 * (indicated by STATE_GOT_BUS) in which case we don't want to
22372 		 * go through a target/bus reset
22373 		 */
22374 		if (pkt->pkt_state == STATE_GOT_BUS) {
22375 			break;
22376 		}
22377 		/*FALLTHROUGH*/
22378 
22379 	case CMD_TIMEOUT:
22380 	default:
22381 		/*
22382 		 * The lun may still be running the command, so a lun reset
22383 		 * should be attempted. If the lun reset fails or cannot be
22384 		 * issued, than try a target reset. Lastly try a bus reset.
22385 		 */
22386 		if ((pkt->pkt_statistics &
22387 		    (STAT_BUS_RESET|STAT_DEV_RESET|STAT_ABORTED)) == 0) {
22388 			int reset_retval = 0;
22389 			mutex_exit(SD_MUTEX(un));
22390 			if (un->un_f_allow_bus_device_reset == TRUE) {
22391 				if (un->un_f_lun_reset_enabled == TRUE) {
22392 					reset_retval =
22393 					    scsi_reset(SD_ADDRESS(un),
22394 					    RESET_LUN);
22395 				}
22396 				if (reset_retval == 0) {
22397 					reset_retval =
22398 					    scsi_reset(SD_ADDRESS(un),
22399 					    RESET_TARGET);
22400 				}
22401 			}
22402 			if (reset_retval == 0) {
22403 				(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
22404 			}
22405 			mutex_enter(SD_MUTEX(un));
22406 		}
22407 		break;
22408 	}
22409 
22410 	/* A device/bus reset has occurred; update the reservation status. */
22411 	if ((pkt->pkt_reason == CMD_RESET) || (pkt->pkt_statistics &
22412 	    (STAT_BUS_RESET | STAT_DEV_RESET))) {
22413 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22414 			un->un_resvd_status |=
22415 			    (SD_LOST_RESERVE | SD_WANT_RESERVE);
22416 			SD_INFO(SD_LOG_IOCTL_MHD, un,
22417 			    "sd_mhd_watch_incomplete: Lost Reservation\n");
22418 		}
22419 	}
22420 
22421 	/*
22422 	 * The disk has been turned off; Update the device state.
22423 	 *
22424 	 * Note: Should we be offlining the disk here?
22425 	 */
22426 	if (pkt->pkt_state == STATE_GOT_BUS) {
22427 		SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_watch_incomplete: "
22428 		    "Disk not responding to selection\n");
22429 		if (un->un_state != SD_STATE_OFFLINE) {
22430 			New_state(un, SD_STATE_OFFLINE);
22431 		}
22432 	} else if (be_chatty) {
22433 		/*
22434 		 * suppress messages if they are all the same pkt reason;
22435 		 * with TQ, many (up to 256) are returned with the same
22436 		 * pkt_reason
22437 		 */
22438 		if (pkt->pkt_reason != un->un_last_pkt_reason) {
22439 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
22440 			    "sd_mhd_watch_incomplete: "
22441 			    "SCSI transport failed: reason '%s'\n",
22442 			    scsi_rname(pkt->pkt_reason));
22443 		}
22444 	}
22445 	un->un_last_pkt_reason = pkt->pkt_reason;
22446 	mutex_exit(SD_MUTEX(un));
22447 }
22448 
22449 
22450 /*
22451  *    Function: sd_sname()
22452  *
22453  * Description: This is a simple little routine to return a string containing
22454  *		a printable description of command status byte for use in
22455  *		logging.
22456  *
22457  *   Arguments: status - pointer to a status byte
22458  *
22459  * Return Code: char * - string containing status description.
22460  */
22461 
22462 static char *
22463 sd_sname(uchar_t status)
22464 {
22465 	switch (status & STATUS_MASK) {
22466 	case STATUS_GOOD:
22467 		return ("good status");
22468 	case STATUS_CHECK:
22469 		return ("check condition");
22470 	case STATUS_MET:
22471 		return ("condition met");
22472 	case STATUS_BUSY:
22473 		return ("busy");
22474 	case STATUS_INTERMEDIATE:
22475 		return ("intermediate");
22476 	case STATUS_INTERMEDIATE_MET:
22477 		return ("intermediate - condition met");
22478 	case STATUS_RESERVATION_CONFLICT:
22479 		return ("reservation_conflict");
22480 	case STATUS_TERMINATED:
22481 		return ("command terminated");
22482 	case STATUS_QFULL:
22483 		return ("queue full");
22484 	default:
22485 		return ("<unknown status>");
22486 	}
22487 }
22488 
22489 
22490 /*
22491  *    Function: sd_mhd_resvd_recover()
22492  *
22493  * Description: This function adds a reservation entry to the
22494  *		sd_resv_reclaim_request list and signals the reservation
22495  *		reclaim thread that there is work pending. If the reservation
22496  *		reclaim thread has not been previously created this function
22497  *		will kick it off.
22498  *
22499  *   Arguments: arg -   the device 'dev_t' is used for context to discriminate
22500  *			among multiple watches that share this callback function
22501  *
22502  *     Context: This routine is called by timeout() and is run in interrupt
22503  *		context. It must not sleep or call other functions which may
22504  *		sleep.
22505  */
22506 
22507 static void
22508 sd_mhd_resvd_recover(void *arg)
22509 {
22510 	dev_t			dev = (dev_t)arg;
22511 	struct sd_lun		*un;
22512 	struct sd_thr_request	*sd_treq = NULL;
22513 	struct sd_thr_request	*sd_cur = NULL;
22514 	struct sd_thr_request	*sd_prev = NULL;
22515 	int			already_there = 0;
22516 
22517 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22518 		return;
22519 	}
22520 
22521 	mutex_enter(SD_MUTEX(un));
22522 	un->un_resvd_timeid = NULL;
22523 	if (un->un_resvd_status & SD_WANT_RESERVE) {
22524 		/*
22525 		 * There was a reset so don't issue the reserve, allow the
22526 		 * sd_mhd_watch_cb callback function to notice this and
22527 		 * reschedule the timeout for reservation.
22528 		 */
22529 		mutex_exit(SD_MUTEX(un));
22530 		return;
22531 	}
22532 	mutex_exit(SD_MUTEX(un));
22533 
22534 	/*
22535 	 * Add this device to the sd_resv_reclaim_request list and the
22536 	 * sd_resv_reclaim_thread should take care of the rest.
22537 	 *
22538 	 * Note: We can't sleep in this context so if the memory allocation
22539 	 * fails allow the sd_mhd_watch_cb callback function to notice this and
22540 	 * reschedule the timeout for reservation.  (4378460)
22541 	 */
22542 	sd_treq = (struct sd_thr_request *)
22543 	    kmem_zalloc(sizeof (struct sd_thr_request), KM_NOSLEEP);
22544 	if (sd_treq == NULL) {
22545 		return;
22546 	}
22547 
22548 	sd_treq->sd_thr_req_next = NULL;
22549 	sd_treq->dev = dev;
22550 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22551 	if (sd_tr.srq_thr_req_head == NULL) {
22552 		sd_tr.srq_thr_req_head = sd_treq;
22553 	} else {
22554 		sd_cur = sd_prev = sd_tr.srq_thr_req_head;
22555 		for (; sd_cur != NULL; sd_cur = sd_cur->sd_thr_req_next) {
22556 			if (sd_cur->dev == dev) {
22557 				/*
22558 				 * already in Queue so don't log
22559 				 * another request for the device
22560 				 */
22561 				already_there = 1;
22562 				break;
22563 			}
22564 			sd_prev = sd_cur;
22565 		}
22566 		if (!already_there) {
22567 			SD_INFO(SD_LOG_IOCTL_MHD, un, "sd_mhd_resvd_recover: "
22568 			    "logging request for %lx\n", dev);
22569 			sd_prev->sd_thr_req_next = sd_treq;
22570 		} else {
22571 			kmem_free(sd_treq, sizeof (struct sd_thr_request));
22572 		}
22573 	}
22574 
22575 	/*
22576 	 * Create a kernel thread to do the reservation reclaim and free up this
22577 	 * thread. We cannot block this thread while we go away to do the
22578 	 * reservation reclaim
22579 	 */
22580 	if (sd_tr.srq_resv_reclaim_thread == NULL)
22581 		sd_tr.srq_resv_reclaim_thread = thread_create(NULL, 0,
22582 		    sd_resv_reclaim_thread, NULL,
22583 		    0, &p0, TS_RUN, v.v_maxsyspri - 2);
22584 
22585 	/* Tell the reservation reclaim thread that it has work to do */
22586 	cv_signal(&sd_tr.srq_resv_reclaim_cv);
22587 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22588 }
22589 
22590 /*
22591  *    Function: sd_resv_reclaim_thread()
22592  *
22593  * Description: This function implements the reservation reclaim operations
22594  *
22595  *   Arguments: arg - the device 'dev_t' is used for context to discriminate
22596  *		      among multiple watches that share this callback function
22597  */
22598 
22599 static void
22600 sd_resv_reclaim_thread()
22601 {
22602 	struct sd_lun		*un;
22603 	struct sd_thr_request	*sd_mhreq;
22604 
22605 	/* Wait for work */
22606 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22607 	if (sd_tr.srq_thr_req_head == NULL) {
22608 		cv_wait(&sd_tr.srq_resv_reclaim_cv,
22609 		    &sd_tr.srq_resv_reclaim_mutex);
22610 	}
22611 
22612 	/* Loop while we have work */
22613 	while ((sd_tr.srq_thr_cur_req = sd_tr.srq_thr_req_head) != NULL) {
22614 		un = ddi_get_soft_state(sd_state,
22615 		    SDUNIT(sd_tr.srq_thr_cur_req->dev));
22616 		if (un == NULL) {
22617 			/*
22618 			 * softstate structure is NULL so just
22619 			 * dequeue the request and continue
22620 			 */
22621 			sd_tr.srq_thr_req_head =
22622 			    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22623 			kmem_free(sd_tr.srq_thr_cur_req,
22624 			    sizeof (struct sd_thr_request));
22625 			continue;
22626 		}
22627 
22628 		/* dequeue the request */
22629 		sd_mhreq = sd_tr.srq_thr_cur_req;
22630 		sd_tr.srq_thr_req_head =
22631 		    sd_tr.srq_thr_cur_req->sd_thr_req_next;
22632 		mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22633 
22634 		/*
22635 		 * Reclaim reservation only if SD_RESERVE is still set. There
22636 		 * may have been a call to MHIOCRELEASE before we got here.
22637 		 */
22638 		mutex_enter(SD_MUTEX(un));
22639 		if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22640 			/*
22641 			 * Note: The SD_LOST_RESERVE flag is cleared before
22642 			 * reclaiming the reservation. If this is done after the
22643 			 * call to sd_reserve_release a reservation loss in the
22644 			 * window between pkt completion of reserve cmd and
22645 			 * mutex_enter below may not be recognized
22646 			 */
22647 			un->un_resvd_status &= ~SD_LOST_RESERVE;
22648 			mutex_exit(SD_MUTEX(un));
22649 
22650 			if (sd_reserve_release(sd_mhreq->dev,
22651 			    SD_RESERVE) == 0) {
22652 				mutex_enter(SD_MUTEX(un));
22653 				un->un_resvd_status |= SD_RESERVE;
22654 				mutex_exit(SD_MUTEX(un));
22655 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22656 				    "sd_resv_reclaim_thread: "
22657 				    "Reservation Recovered\n");
22658 			} else {
22659 				mutex_enter(SD_MUTEX(un));
22660 				un->un_resvd_status |= SD_LOST_RESERVE;
22661 				mutex_exit(SD_MUTEX(un));
22662 				SD_INFO(SD_LOG_IOCTL_MHD, un,
22663 				    "sd_resv_reclaim_thread: Failed "
22664 				    "Reservation Recovery\n");
22665 			}
22666 		} else {
22667 			mutex_exit(SD_MUTEX(un));
22668 		}
22669 		mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22670 		ASSERT(sd_mhreq == sd_tr.srq_thr_cur_req);
22671 		kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22672 		sd_mhreq = sd_tr.srq_thr_cur_req = NULL;
22673 		/*
22674 		 * wakeup the destroy thread if anyone is waiting on
22675 		 * us to complete.
22676 		 */
22677 		cv_signal(&sd_tr.srq_inprocess_cv);
22678 		SD_TRACE(SD_LOG_IOCTL_MHD, un,
22679 		    "sd_resv_reclaim_thread: cv_signalling current request \n");
22680 	}
22681 
22682 	/*
22683 	 * cleanup the sd_tr structure now that this thread will not exist
22684 	 */
22685 	ASSERT(sd_tr.srq_thr_req_head == NULL);
22686 	ASSERT(sd_tr.srq_thr_cur_req == NULL);
22687 	sd_tr.srq_resv_reclaim_thread = NULL;
22688 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22689 	thread_exit();
22690 }
22691 
22692 
22693 /*
22694  *    Function: sd_rmv_resv_reclaim_req()
22695  *
22696  * Description: This function removes any pending reservation reclaim requests
22697  *		for the specified device.
22698  *
22699  *   Arguments: dev - the device 'dev_t'
22700  */
22701 
22702 static void
22703 sd_rmv_resv_reclaim_req(dev_t dev)
22704 {
22705 	struct sd_thr_request *sd_mhreq;
22706 	struct sd_thr_request *sd_prev;
22707 
22708 	/* Remove a reservation reclaim request from the list */
22709 	mutex_enter(&sd_tr.srq_resv_reclaim_mutex);
22710 	if (sd_tr.srq_thr_cur_req && sd_tr.srq_thr_cur_req->dev == dev) {
22711 		/*
22712 		 * We are attempting to reinstate reservation for
22713 		 * this device. We wait for sd_reserve_release()
22714 		 * to return before we return.
22715 		 */
22716 		cv_wait(&sd_tr.srq_inprocess_cv,
22717 		    &sd_tr.srq_resv_reclaim_mutex);
22718 	} else {
22719 		sd_prev = sd_mhreq = sd_tr.srq_thr_req_head;
22720 		if (sd_mhreq && sd_mhreq->dev == dev) {
22721 			sd_tr.srq_thr_req_head = sd_mhreq->sd_thr_req_next;
22722 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22723 			mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22724 			return;
22725 		}
22726 		for (; sd_mhreq != NULL; sd_mhreq = sd_mhreq->sd_thr_req_next) {
22727 			if (sd_mhreq && sd_mhreq->dev == dev) {
22728 				break;
22729 			}
22730 			sd_prev = sd_mhreq;
22731 		}
22732 		if (sd_mhreq != NULL) {
22733 			sd_prev->sd_thr_req_next = sd_mhreq->sd_thr_req_next;
22734 			kmem_free(sd_mhreq, sizeof (struct sd_thr_request));
22735 		}
22736 	}
22737 	mutex_exit(&sd_tr.srq_resv_reclaim_mutex);
22738 }
22739 
22740 
22741 /*
22742  *    Function: sd_mhd_reset_notify_cb()
22743  *
22744  * Description: This is a call back function for scsi_reset_notify. This
22745  *		function updates the softstate reserved status and logs the
22746  *		reset. The driver scsi watch facility callback function
22747  *		(sd_mhd_watch_cb) and reservation reclaim thread functionality
22748  *		will reclaim the reservation.
22749  *
22750  *   Arguments: arg  - driver soft state (unit) structure
22751  */
22752 
22753 static void
22754 sd_mhd_reset_notify_cb(caddr_t arg)
22755 {
22756 	struct sd_lun *un = (struct sd_lun *)arg;
22757 
22758 	mutex_enter(SD_MUTEX(un));
22759 	if ((un->un_resvd_status & SD_RESERVE) == SD_RESERVE) {
22760 		un->un_resvd_status |= (SD_LOST_RESERVE | SD_WANT_RESERVE);
22761 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22762 		    "sd_mhd_reset_notify_cb: Lost Reservation\n");
22763 	}
22764 	mutex_exit(SD_MUTEX(un));
22765 }
22766 
22767 
22768 /*
22769  *    Function: sd_take_ownership()
22770  *
22771  * Description: This routine implements an algorithm to achieve a stable
22772  *		reservation on disks which don't implement priority reserve,
22773  *		and makes sure that other host lose re-reservation attempts.
22774  *		This algorithm contains of a loop that keeps issuing the RESERVE
22775  *		for some period of time (min_ownership_delay, default 6 seconds)
22776  *		During that loop, it looks to see if there has been a bus device
22777  *		reset or bus reset (both of which cause an existing reservation
22778  *		to be lost). If the reservation is lost issue RESERVE until a
22779  *		period of min_ownership_delay with no resets has gone by, or
22780  *		until max_ownership_delay has expired. This loop ensures that
22781  *		the host really did manage to reserve the device, in spite of
22782  *		resets. The looping for min_ownership_delay (default six
22783  *		seconds) is important to early generation clustering products,
22784  *		Solstice HA 1.x and Sun Cluster 2.x. Those products use an
22785  *		MHIOCENFAILFAST periodic timer of two seconds. By having
22786  *		MHIOCTKOWN issue Reserves in a loop for six seconds, and having
22787  *		MHIOCENFAILFAST poll every two seconds, the idea is that by the
22788  *		time the MHIOCTKOWN ioctl returns, the other host (if any) will
22789  *		have already noticed, via the MHIOCENFAILFAST polling, that it
22790  *		no longer "owns" the disk and will have panicked itself.  Thus,
22791  *		the host issuing the MHIOCTKOWN is assured (with timing
22792  *		dependencies) that by the time it actually starts to use the
22793  *		disk for real work, the old owner is no longer accessing it.
22794  *
22795  *		min_ownership_delay is the minimum amount of time for which the
22796  *		disk must be reserved continuously devoid of resets before the
22797  *		MHIOCTKOWN ioctl will return success.
22798  *
22799  *		max_ownership_delay indicates the amount of time by which the
22800  *		take ownership should succeed or timeout with an error.
22801  *
22802  *   Arguments: dev - the device 'dev_t'
22803  *		*p  - struct containing timing info.
22804  *
22805  * Return Code: 0 for success or error code
22806  */
22807 
22808 static int
22809 sd_take_ownership(dev_t dev, struct mhioctkown *p)
22810 {
22811 	struct sd_lun	*un;
22812 	int		rval;
22813 	int		err;
22814 	int		reservation_count   = 0;
22815 	int		min_ownership_delay =  6000000; /* in usec */
22816 	int		max_ownership_delay = 30000000; /* in usec */
22817 	clock_t		start_time;	/* starting time of this algorithm */
22818 	clock_t		end_time;	/* time limit for giving up */
22819 	clock_t		ownership_time;	/* time limit for stable ownership */
22820 	clock_t		current_time;
22821 	clock_t		previous_current_time;
22822 
22823 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22824 		return (ENXIO);
22825 	}
22826 
22827 	/*
22828 	 * Attempt a device reservation. A priority reservation is requested.
22829 	 */
22830 	if ((rval = sd_reserve_release(dev, SD_PRIORITY_RESERVE))
22831 	    != SD_SUCCESS) {
22832 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
22833 		    "sd_take_ownership: return(1)=%d\n", rval);
22834 		return (rval);
22835 	}
22836 
22837 	/* Update the softstate reserved status to indicate the reservation */
22838 	mutex_enter(SD_MUTEX(un));
22839 	un->un_resvd_status |= SD_RESERVE;
22840 	un->un_resvd_status &=
22841 	    ~(SD_LOST_RESERVE | SD_WANT_RESERVE | SD_RESERVATION_CONFLICT);
22842 	mutex_exit(SD_MUTEX(un));
22843 
22844 	if (p != NULL) {
22845 		if (p->min_ownership_delay != 0) {
22846 			min_ownership_delay = p->min_ownership_delay * 1000;
22847 		}
22848 		if (p->max_ownership_delay != 0) {
22849 			max_ownership_delay = p->max_ownership_delay * 1000;
22850 		}
22851 	}
22852 	SD_INFO(SD_LOG_IOCTL_MHD, un,
22853 	    "sd_take_ownership: min, max delays: %d, %d\n",
22854 	    min_ownership_delay, max_ownership_delay);
22855 
22856 	start_time = ddi_get_lbolt();
22857 	current_time	= start_time;
22858 	ownership_time	= current_time + drv_usectohz(min_ownership_delay);
22859 	end_time	= start_time + drv_usectohz(max_ownership_delay);
22860 
22861 	while (current_time - end_time < 0) {
22862 		delay(drv_usectohz(500000));
22863 
22864 		if ((err = sd_reserve_release(dev, SD_RESERVE)) != 0) {
22865 			if ((sd_reserve_release(dev, SD_RESERVE)) != 0) {
22866 				mutex_enter(SD_MUTEX(un));
22867 				rval = (un->un_resvd_status &
22868 				    SD_RESERVATION_CONFLICT) ? EACCES : EIO;
22869 				mutex_exit(SD_MUTEX(un));
22870 				break;
22871 			}
22872 		}
22873 		previous_current_time = current_time;
22874 		current_time = ddi_get_lbolt();
22875 		mutex_enter(SD_MUTEX(un));
22876 		if (err || (un->un_resvd_status & SD_LOST_RESERVE)) {
22877 			ownership_time = ddi_get_lbolt() +
22878 			    drv_usectohz(min_ownership_delay);
22879 			reservation_count = 0;
22880 		} else {
22881 			reservation_count++;
22882 		}
22883 		un->un_resvd_status |= SD_RESERVE;
22884 		un->un_resvd_status &= ~(SD_LOST_RESERVE | SD_WANT_RESERVE);
22885 		mutex_exit(SD_MUTEX(un));
22886 
22887 		SD_INFO(SD_LOG_IOCTL_MHD, un,
22888 		    "sd_take_ownership: ticks for loop iteration=%ld, "
22889 		    "reservation=%s\n", (current_time - previous_current_time),
22890 		    reservation_count ? "ok" : "reclaimed");
22891 
22892 		if (current_time - ownership_time >= 0 &&
22893 		    reservation_count >= 4) {
22894 			rval = 0; /* Achieved a stable ownership */
22895 			break;
22896 		}
22897 		if (current_time - end_time >= 0) {
22898 			rval = EACCES; /* No ownership in max possible time */
22899 			break;
22900 		}
22901 	}
22902 	SD_TRACE(SD_LOG_IOCTL_MHD, un,
22903 	    "sd_take_ownership: return(2)=%d\n", rval);
22904 	return (rval);
22905 }
22906 
22907 
22908 /*
22909  *    Function: sd_reserve_release()
22910  *
22911  * Description: This function builds and sends scsi RESERVE, RELEASE, and
22912  *		PRIORITY RESERVE commands based on a user specified command type
22913  *
22914  *   Arguments: dev - the device 'dev_t'
22915  *		cmd - user specified command type; one of SD_PRIORITY_RESERVE,
22916  *		      SD_RESERVE, SD_RELEASE
22917  *
22918  * Return Code: 0 or Error Code
22919  */
22920 
22921 static int
22922 sd_reserve_release(dev_t dev, int cmd)
22923 {
22924 	struct uscsi_cmd	*com = NULL;
22925 	struct sd_lun		*un = NULL;
22926 	char			cdb[CDB_GROUP0];
22927 	int			rval;
22928 
22929 	ASSERT((cmd == SD_RELEASE) || (cmd == SD_RESERVE) ||
22930 	    (cmd == SD_PRIORITY_RESERVE));
22931 
22932 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
22933 		return (ENXIO);
22934 	}
22935 
22936 	/* instantiate and initialize the command and cdb */
22937 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
22938 	bzero(cdb, CDB_GROUP0);
22939 	com->uscsi_flags   = USCSI_SILENT;
22940 	com->uscsi_timeout = un->un_reserve_release_time;
22941 	com->uscsi_cdblen  = CDB_GROUP0;
22942 	com->uscsi_cdb	   = cdb;
22943 	if (cmd == SD_RELEASE) {
22944 		cdb[0] = SCMD_RELEASE;
22945 	} else {
22946 		cdb[0] = SCMD_RESERVE;
22947 	}
22948 
22949 	/* Send the command. */
22950 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22951 	    SD_PATH_STANDARD);
22952 
22953 	/*
22954 	 * "break" a reservation that is held by another host, by issuing a
22955 	 * reset if priority reserve is desired, and we could not get the
22956 	 * device.
22957 	 */
22958 	if ((cmd == SD_PRIORITY_RESERVE) &&
22959 	    (rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22960 		/*
22961 		 * First try to reset the LUN. If we cannot, then try a target
22962 		 * reset, followed by a bus reset if the target reset fails.
22963 		 */
22964 		int reset_retval = 0;
22965 		if (un->un_f_lun_reset_enabled == TRUE) {
22966 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_LUN);
22967 		}
22968 		if (reset_retval == 0) {
22969 			/* The LUN reset either failed or was not issued */
22970 			reset_retval = scsi_reset(SD_ADDRESS(un), RESET_TARGET);
22971 		}
22972 		if ((reset_retval == 0) &&
22973 		    (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0)) {
22974 			rval = EIO;
22975 			kmem_free(com, sizeof (*com));
22976 			return (rval);
22977 		}
22978 
22979 		bzero(com, sizeof (struct uscsi_cmd));
22980 		com->uscsi_flags   = USCSI_SILENT;
22981 		com->uscsi_cdb	   = cdb;
22982 		com->uscsi_cdblen  = CDB_GROUP0;
22983 		com->uscsi_timeout = 5;
22984 
22985 		/*
22986 		 * Reissue the last reserve command, this time without request
22987 		 * sense.  Assume that it is just a regular reserve command.
22988 		 */
22989 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
22990 		    SD_PATH_STANDARD);
22991 	}
22992 
22993 	/* Return an error if still getting a reservation conflict. */
22994 	if ((rval != 0) && (com->uscsi_status == STATUS_RESERVATION_CONFLICT)) {
22995 		rval = EACCES;
22996 	}
22997 
22998 	kmem_free(com, sizeof (*com));
22999 	return (rval);
23000 }
23001 
23002 
23003 #define	SD_NDUMP_RETRIES	12
23004 /*
23005  *	System Crash Dump routine
23006  */
23007 
23008 static int
23009 sddump(dev_t dev, caddr_t addr, daddr_t blkno, int nblk)
23010 {
23011 	int		instance;
23012 	int		partition;
23013 	int		i;
23014 	int		err;
23015 	struct sd_lun	*un;
23016 	struct scsi_pkt *wr_pktp;
23017 	struct buf	*wr_bp;
23018 	struct buf	wr_buf;
23019 	daddr_t		tgt_byte_offset; /* rmw - byte offset for target */
23020 	daddr_t		tgt_blkno;	/* rmw - blkno for target */
23021 	size_t		tgt_byte_count; /* rmw -  # of bytes to xfer */
23022 	size_t		tgt_nblk; /* rmw -  # of tgt blks to xfer */
23023 	size_t		io_start_offset;
23024 	int		doing_rmw = FALSE;
23025 	int		rval;
23026 	ssize_t		dma_resid;
23027 	daddr_t		oblkno;
23028 	diskaddr_t	nblks = 0;
23029 	diskaddr_t	start_block;
23030 
23031 	instance = SDUNIT(dev);
23032 	if (((un = ddi_get_soft_state(sd_state, instance)) == NULL) ||
23033 	    !SD_IS_VALID_LABEL(un) || ISCD(un)) {
23034 		return (ENXIO);
23035 	}
23036 
23037 	_NOTE(NOW_INVISIBLE_TO_OTHER_THREADS(*un))
23038 
23039 	SD_TRACE(SD_LOG_DUMP, un, "sddump: entry\n");
23040 
23041 	partition = SDPART(dev);
23042 	SD_INFO(SD_LOG_DUMP, un, "sddump: partition = %d\n", partition);
23043 
23044 	/* Validate blocks to dump at against partition size. */
23045 
23046 	(void) cmlb_partinfo(un->un_cmlbhandle, partition,
23047 	    &nblks, &start_block, NULL, NULL, (void *)SD_PATH_DIRECT);
23048 
23049 	if ((blkno + nblk) > nblks) {
23050 		SD_TRACE(SD_LOG_DUMP, un,
23051 		    "sddump: dump range larger than partition: "
23052 		    "blkno = 0x%x, nblk = 0x%x, dkl_nblk = 0x%x\n",
23053 		    blkno, nblk, nblks);
23054 		return (EINVAL);
23055 	}
23056 
23057 	mutex_enter(&un->un_pm_mutex);
23058 	if (SD_DEVICE_IS_IN_LOW_POWER(un)) {
23059 		struct scsi_pkt *start_pktp;
23060 
23061 		mutex_exit(&un->un_pm_mutex);
23062 
23063 		/*
23064 		 * use pm framework to power on HBA 1st
23065 		 */
23066 		(void) pm_raise_power(SD_DEVINFO(un), 0, SD_SPINDLE_ON);
23067 
23068 		/*
23069 		 * Dump no long uses sdpower to power on a device, it's
23070 		 * in-line here so it can be done in polled mode.
23071 		 */
23072 
23073 		SD_INFO(SD_LOG_DUMP, un, "sddump: starting device\n");
23074 
23075 		start_pktp = scsi_init_pkt(SD_ADDRESS(un), NULL, NULL,
23076 		    CDB_GROUP0, un->un_status_len, 0, 0, NULL_FUNC, NULL);
23077 
23078 		if (start_pktp == NULL) {
23079 			/* We were not given a SCSI packet, fail. */
23080 			return (EIO);
23081 		}
23082 		bzero(start_pktp->pkt_cdbp, CDB_GROUP0);
23083 		start_pktp->pkt_cdbp[0] = SCMD_START_STOP;
23084 		start_pktp->pkt_cdbp[4] = SD_TARGET_START;
23085 		start_pktp->pkt_flags = FLAG_NOINTR;
23086 
23087 		mutex_enter(SD_MUTEX(un));
23088 		SD_FILL_SCSI1_LUN(un, start_pktp);
23089 		mutex_exit(SD_MUTEX(un));
23090 		/*
23091 		 * Scsi_poll returns 0 (success) if the command completes and
23092 		 * the status block is STATUS_GOOD.
23093 		 */
23094 		if (sd_scsi_poll(un, start_pktp) != 0) {
23095 			scsi_destroy_pkt(start_pktp);
23096 			return (EIO);
23097 		}
23098 		scsi_destroy_pkt(start_pktp);
23099 		(void) sd_ddi_pm_resume(un);
23100 	} else {
23101 		mutex_exit(&un->un_pm_mutex);
23102 	}
23103 
23104 	mutex_enter(SD_MUTEX(un));
23105 	un->un_throttle = 0;
23106 
23107 	/*
23108 	 * The first time through, reset the specific target device.
23109 	 * However, when cpr calls sddump we know that sd is in a
23110 	 * a good state so no bus reset is required.
23111 	 * Clear sense data via Request Sense cmd.
23112 	 * In sddump we don't care about allow_bus_device_reset anymore
23113 	 */
23114 
23115 	if ((un->un_state != SD_STATE_SUSPENDED) &&
23116 	    (un->un_state != SD_STATE_DUMPING)) {
23117 
23118 		New_state(un, SD_STATE_DUMPING);
23119 
23120 		if (un->un_f_is_fibre == FALSE) {
23121 			mutex_exit(SD_MUTEX(un));
23122 			/*
23123 			 * Attempt a bus reset for parallel scsi.
23124 			 *
23125 			 * Note: A bus reset is required because on some host
23126 			 * systems (i.e. E420R) a bus device reset is
23127 			 * insufficient to reset the state of the target.
23128 			 *
23129 			 * Note: Don't issue the reset for fibre-channel,
23130 			 * because this tends to hang the bus (loop) for
23131 			 * too long while everyone is logging out and in
23132 			 * and the deadman timer for dumping will fire
23133 			 * before the dump is complete.
23134 			 */
23135 			if (scsi_reset(SD_ADDRESS(un), RESET_ALL) == 0) {
23136 				mutex_enter(SD_MUTEX(un));
23137 				Restore_state(un);
23138 				mutex_exit(SD_MUTEX(un));
23139 				return (EIO);
23140 			}
23141 
23142 			/* Delay to give the device some recovery time. */
23143 			drv_usecwait(10000);
23144 
23145 			if (sd_send_polled_RQS(un) == SD_FAILURE) {
23146 				SD_INFO(SD_LOG_DUMP, un,
23147 				    "sddump: sd_send_polled_RQS failed\n");
23148 			}
23149 			mutex_enter(SD_MUTEX(un));
23150 		}
23151 	}
23152 
23153 	/*
23154 	 * Convert the partition-relative block number to a
23155 	 * disk physical block number.
23156 	 */
23157 	blkno += start_block;
23158 
23159 	SD_INFO(SD_LOG_DUMP, un, "sddump: disk blkno = 0x%x\n", blkno);
23160 
23161 
23162 	/*
23163 	 * Check if the device has a non-512 block size.
23164 	 */
23165 	wr_bp = NULL;
23166 	if (NOT_DEVBSIZE(un)) {
23167 		tgt_byte_offset = blkno * un->un_sys_blocksize;
23168 		tgt_byte_count = nblk * un->un_sys_blocksize;
23169 		if ((tgt_byte_offset % un->un_tgt_blocksize) ||
23170 		    (tgt_byte_count % un->un_tgt_blocksize)) {
23171 			doing_rmw = TRUE;
23172 			/*
23173 			 * Calculate the block number and number of block
23174 			 * in terms of the media block size.
23175 			 */
23176 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
23177 			tgt_nblk =
23178 			    ((tgt_byte_offset + tgt_byte_count +
23179 			    (un->un_tgt_blocksize - 1)) /
23180 			    un->un_tgt_blocksize) - tgt_blkno;
23181 
23182 			/*
23183 			 * Invoke the routine which is going to do read part
23184 			 * of read-modify-write.
23185 			 * Note that this routine returns a pointer to
23186 			 * a valid bp in wr_bp.
23187 			 */
23188 			err = sddump_do_read_of_rmw(un, tgt_blkno, tgt_nblk,
23189 			    &wr_bp);
23190 			if (err) {
23191 				mutex_exit(SD_MUTEX(un));
23192 				return (err);
23193 			}
23194 			/*
23195 			 * Offset is being calculated as -
23196 			 * (original block # * system block size) -
23197 			 * (new block # * target block size)
23198 			 */
23199 			io_start_offset =
23200 			    ((uint64_t)(blkno * un->un_sys_blocksize)) -
23201 			    ((uint64_t)(tgt_blkno * un->un_tgt_blocksize));
23202 
23203 			ASSERT((io_start_offset >= 0) &&
23204 			    (io_start_offset < un->un_tgt_blocksize));
23205 			/*
23206 			 * Do the modify portion of read modify write.
23207 			 */
23208 			bcopy(addr, &wr_bp->b_un.b_addr[io_start_offset],
23209 			    (size_t)nblk * un->un_sys_blocksize);
23210 		} else {
23211 			doing_rmw = FALSE;
23212 			tgt_blkno = tgt_byte_offset / un->un_tgt_blocksize;
23213 			tgt_nblk = tgt_byte_count / un->un_tgt_blocksize;
23214 		}
23215 
23216 		/* Convert blkno and nblk to target blocks */
23217 		blkno = tgt_blkno;
23218 		nblk = tgt_nblk;
23219 	} else {
23220 		wr_bp = &wr_buf;
23221 		bzero(wr_bp, sizeof (struct buf));
23222 		wr_bp->b_flags		= B_BUSY;
23223 		wr_bp->b_un.b_addr	= addr;
23224 		wr_bp->b_bcount		= nblk << DEV_BSHIFT;
23225 		wr_bp->b_resid		= 0;
23226 	}
23227 
23228 	mutex_exit(SD_MUTEX(un));
23229 
23230 	/*
23231 	 * Obtain a SCSI packet for the write command.
23232 	 * It should be safe to call the allocator here without
23233 	 * worrying about being locked for DVMA mapping because
23234 	 * the address we're passed is already a DVMA mapping
23235 	 *
23236 	 * We are also not going to worry about semaphore ownership
23237 	 * in the dump buffer. Dumping is single threaded at present.
23238 	 */
23239 
23240 	wr_pktp = NULL;
23241 
23242 	dma_resid = wr_bp->b_bcount;
23243 	oblkno = blkno;
23244 
23245 	while (dma_resid != 0) {
23246 
23247 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
23248 		wr_bp->b_flags &= ~B_ERROR;
23249 
23250 		if (un->un_partial_dma_supported == 1) {
23251 			blkno = oblkno +
23252 			    ((wr_bp->b_bcount - dma_resid) /
23253 			    un->un_tgt_blocksize);
23254 			nblk = dma_resid / un->un_tgt_blocksize;
23255 
23256 			if (wr_pktp) {
23257 				/*
23258 				 * Partial DMA transfers after initial transfer
23259 				 */
23260 				rval = sd_setup_next_rw_pkt(un, wr_pktp, wr_bp,
23261 				    blkno, nblk);
23262 			} else {
23263 				/* Initial transfer */
23264 				rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
23265 				    un->un_pkt_flags, NULL_FUNC, NULL,
23266 				    blkno, nblk);
23267 			}
23268 		} else {
23269 			rval = sd_setup_rw_pkt(un, &wr_pktp, wr_bp,
23270 			    0, NULL_FUNC, NULL, blkno, nblk);
23271 		}
23272 
23273 		if (rval == 0) {
23274 			/* We were given a SCSI packet, continue. */
23275 			break;
23276 		}
23277 
23278 		if (i == 0) {
23279 			if (wr_bp->b_flags & B_ERROR) {
23280 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23281 				    "no resources for dumping; "
23282 				    "error code: 0x%x, retrying",
23283 				    geterror(wr_bp));
23284 			} else {
23285 				scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23286 				    "no resources for dumping; retrying");
23287 			}
23288 		} else if (i != (SD_NDUMP_RETRIES - 1)) {
23289 			if (wr_bp->b_flags & B_ERROR) {
23290 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23291 				    "no resources for dumping; error code: "
23292 				    "0x%x, retrying\n", geterror(wr_bp));
23293 			}
23294 		} else {
23295 			if (wr_bp->b_flags & B_ERROR) {
23296 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23297 				    "no resources for dumping; "
23298 				    "error code: 0x%x, retries failed, "
23299 				    "giving up.\n", geterror(wr_bp));
23300 			} else {
23301 				scsi_log(SD_DEVINFO(un), sd_label, CE_CONT,
23302 				    "no resources for dumping; "
23303 				    "retries failed, giving up.\n");
23304 			}
23305 			mutex_enter(SD_MUTEX(un));
23306 			Restore_state(un);
23307 			if (NOT_DEVBSIZE(un) && (doing_rmw == TRUE)) {
23308 				mutex_exit(SD_MUTEX(un));
23309 				scsi_free_consistent_buf(wr_bp);
23310 			} else {
23311 				mutex_exit(SD_MUTEX(un));
23312 			}
23313 			return (EIO);
23314 		}
23315 		drv_usecwait(10000);
23316 	}
23317 
23318 	if (un->un_partial_dma_supported == 1) {
23319 		/*
23320 		 * save the resid from PARTIAL_DMA
23321 		 */
23322 		dma_resid = wr_pktp->pkt_resid;
23323 		if (dma_resid != 0)
23324 			nblk -= SD_BYTES2TGTBLOCKS(un, dma_resid);
23325 		wr_pktp->pkt_resid = 0;
23326 	} else {
23327 		dma_resid = 0;
23328 	}
23329 
23330 	/* SunBug 1222170 */
23331 	wr_pktp->pkt_flags = FLAG_NOINTR;
23332 
23333 	err = EIO;
23334 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
23335 
23336 		/*
23337 		 * Scsi_poll returns 0 (success) if the command completes and
23338 		 * the status block is STATUS_GOOD.  We should only check
23339 		 * errors if this condition is not true.  Even then we should
23340 		 * send our own request sense packet only if we have a check
23341 		 * condition and auto request sense has not been performed by
23342 		 * the hba.
23343 		 */
23344 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending write\n");
23345 
23346 		if ((sd_scsi_poll(un, wr_pktp) == 0) &&
23347 		    (wr_pktp->pkt_resid == 0)) {
23348 			err = SD_SUCCESS;
23349 			break;
23350 		}
23351 
23352 		/*
23353 		 * Check CMD_DEV_GONE 1st, give up if device is gone.
23354 		 */
23355 		if (wr_pktp->pkt_reason == CMD_DEV_GONE) {
23356 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
23357 			    "Error while dumping state...Device is gone\n");
23358 			break;
23359 		}
23360 
23361 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_CHECK) {
23362 			SD_INFO(SD_LOG_DUMP, un,
23363 			    "sddump: write failed with CHECK, try # %d\n", i);
23364 			if (((wr_pktp->pkt_state & STATE_ARQ_DONE) == 0)) {
23365 				(void) sd_send_polled_RQS(un);
23366 			}
23367 
23368 			continue;
23369 		}
23370 
23371 		if (SD_GET_PKT_STATUS(wr_pktp) == STATUS_BUSY) {
23372 			int reset_retval = 0;
23373 
23374 			SD_INFO(SD_LOG_DUMP, un,
23375 			    "sddump: write failed with BUSY, try # %d\n", i);
23376 
23377 			if (un->un_f_lun_reset_enabled == TRUE) {
23378 				reset_retval = scsi_reset(SD_ADDRESS(un),
23379 				    RESET_LUN);
23380 			}
23381 			if (reset_retval == 0) {
23382 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
23383 			}
23384 			(void) sd_send_polled_RQS(un);
23385 
23386 		} else {
23387 			SD_INFO(SD_LOG_DUMP, un,
23388 			    "sddump: write failed with 0x%x, try # %d\n",
23389 			    SD_GET_PKT_STATUS(wr_pktp), i);
23390 			mutex_enter(SD_MUTEX(un));
23391 			sd_reset_target(un, wr_pktp);
23392 			mutex_exit(SD_MUTEX(un));
23393 		}
23394 
23395 		/*
23396 		 * If we are not getting anywhere with lun/target resets,
23397 		 * let's reset the bus.
23398 		 */
23399 		if (i == SD_NDUMP_RETRIES/2) {
23400 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
23401 			(void) sd_send_polled_RQS(un);
23402 		}
23403 	}
23404 	}
23405 
23406 	scsi_destroy_pkt(wr_pktp);
23407 	mutex_enter(SD_MUTEX(un));
23408 	if ((NOT_DEVBSIZE(un)) && (doing_rmw == TRUE)) {
23409 		mutex_exit(SD_MUTEX(un));
23410 		scsi_free_consistent_buf(wr_bp);
23411 	} else {
23412 		mutex_exit(SD_MUTEX(un));
23413 	}
23414 	SD_TRACE(SD_LOG_DUMP, un, "sddump: exit: err = %d\n", err);
23415 	return (err);
23416 }
23417 
23418 /*
23419  *    Function: sd_scsi_poll()
23420  *
23421  * Description: This is a wrapper for the scsi_poll call.
23422  *
23423  *   Arguments: sd_lun - The unit structure
23424  *              scsi_pkt - The scsi packet being sent to the device.
23425  *
23426  * Return Code: 0 - Command completed successfully with good status
23427  *             -1 - Command failed.  This could indicate a check condition
23428  *                  or other status value requiring recovery action.
23429  *
23430  * NOTE: This code is only called off sddump().
23431  */
23432 
23433 static int
23434 sd_scsi_poll(struct sd_lun *un, struct scsi_pkt *pktp)
23435 {
23436 	int status;
23437 
23438 	ASSERT(un != NULL);
23439 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23440 	ASSERT(pktp != NULL);
23441 
23442 	status = SD_SUCCESS;
23443 
23444 	if (scsi_ifgetcap(&pktp->pkt_address, "tagged-qing", 1) == 1) {
23445 		pktp->pkt_flags |= un->un_tagflags;
23446 		pktp->pkt_flags &= ~FLAG_NODISCON;
23447 	}
23448 
23449 	status = sd_ddi_scsi_poll(pktp);
23450 	/*
23451 	 * Scsi_poll returns 0 (success) if the command completes and the
23452 	 * status block is STATUS_GOOD.  We should only check errors if this
23453 	 * condition is not true.  Even then we should send our own request
23454 	 * sense packet only if we have a check condition and auto
23455 	 * request sense has not been performed by the hba.
23456 	 * Don't get RQS data if pkt_reason is CMD_DEV_GONE.
23457 	 */
23458 	if ((status != SD_SUCCESS) &&
23459 	    (SD_GET_PKT_STATUS(pktp) == STATUS_CHECK) &&
23460 	    (pktp->pkt_state & STATE_ARQ_DONE) == 0 &&
23461 	    (pktp->pkt_reason != CMD_DEV_GONE))
23462 		(void) sd_send_polled_RQS(un);
23463 
23464 	return (status);
23465 }
23466 
23467 /*
23468  *    Function: sd_send_polled_RQS()
23469  *
23470  * Description: This sends the request sense command to a device.
23471  *
23472  *   Arguments: sd_lun - The unit structure
23473  *
23474  * Return Code: 0 - Command completed successfully with good status
23475  *             -1 - Command failed.
23476  *
23477  */
23478 
23479 static int
23480 sd_send_polled_RQS(struct sd_lun *un)
23481 {
23482 	int	ret_val;
23483 	struct	scsi_pkt	*rqs_pktp;
23484 	struct	buf		*rqs_bp;
23485 
23486 	ASSERT(un != NULL);
23487 	ASSERT(!mutex_owned(SD_MUTEX(un)));
23488 
23489 	ret_val = SD_SUCCESS;
23490 
23491 	rqs_pktp = un->un_rqs_pktp;
23492 	rqs_bp	 = un->un_rqs_bp;
23493 
23494 	mutex_enter(SD_MUTEX(un));
23495 
23496 	if (un->un_sense_isbusy) {
23497 		ret_val = SD_FAILURE;
23498 		mutex_exit(SD_MUTEX(un));
23499 		return (ret_val);
23500 	}
23501 
23502 	/*
23503 	 * If the request sense buffer (and packet) is not in use,
23504 	 * let's set the un_sense_isbusy and send our packet
23505 	 */
23506 	un->un_sense_isbusy 	= 1;
23507 	rqs_pktp->pkt_resid  	= 0;
23508 	rqs_pktp->pkt_reason 	= 0;
23509 	rqs_pktp->pkt_flags |= FLAG_NOINTR;
23510 	bzero(rqs_bp->b_un.b_addr, SENSE_LENGTH);
23511 
23512 	mutex_exit(SD_MUTEX(un));
23513 
23514 	SD_INFO(SD_LOG_COMMON, un, "sd_send_polled_RQS: req sense buf at"
23515 	    " 0x%p\n", rqs_bp->b_un.b_addr);
23516 
23517 	/*
23518 	 * Can't send this to sd_scsi_poll, we wrap ourselves around the
23519 	 * axle - it has a call into us!
23520 	 */
23521 	if ((ret_val = sd_ddi_scsi_poll(rqs_pktp)) != 0) {
23522 		SD_INFO(SD_LOG_COMMON, un,
23523 		    "sd_send_polled_RQS: RQS failed\n");
23524 	}
23525 
23526 	SD_DUMP_MEMORY(un, SD_LOG_COMMON, "sd_send_polled_RQS:",
23527 	    (uchar_t *)rqs_bp->b_un.b_addr, SENSE_LENGTH, SD_LOG_HEX);
23528 
23529 	mutex_enter(SD_MUTEX(un));
23530 	un->un_sense_isbusy = 0;
23531 	mutex_exit(SD_MUTEX(un));
23532 
23533 	return (ret_val);
23534 }
23535 
23536 /*
23537  * Defines needed for localized version of the scsi_poll routine.
23538  */
23539 #define	CSEC		10000			/* usecs */
23540 #define	SEC_TO_CSEC	(1000000/CSEC)
23541 
23542 /*
23543  *    Function: sd_ddi_scsi_poll()
23544  *
23545  * Description: Localized version of the scsi_poll routine.  The purpose is to
23546  *		send a scsi_pkt to a device as a polled command.  This version
23547  *		is to ensure more robust handling of transport errors.
23548  *		Specifically this routine cures not ready, coming ready
23549  *		transition for power up and reset of sonoma's.  This can take
23550  *		up to 45 seconds for power-on and 20 seconds for reset of a
23551  * 		sonoma lun.
23552  *
23553  *   Arguments: scsi_pkt - The scsi_pkt being sent to a device
23554  *
23555  * Return Code: 0 - Command completed successfully with good status
23556  *             -1 - Command failed.
23557  *
23558  * NOTE: This code is almost identical to scsi_poll, however before 6668774 can
23559  * be fixed (removing this code), we need to determine how to handle the
23560  * KEY_UNIT_ATTENTION condition below in conditions not as limited as sddump().
23561  *
23562  * NOTE: This code is only called off sddump().
23563  */
23564 static int
23565 sd_ddi_scsi_poll(struct scsi_pkt *pkt)
23566 {
23567 	int			rval = -1;
23568 	int			savef;
23569 	long			savet;
23570 	void			(*savec)();
23571 	int			timeout;
23572 	int			busy_count;
23573 	int			poll_delay;
23574 	int			rc;
23575 	uint8_t			*sensep;
23576 	struct scsi_arq_status	*arqstat;
23577 	extern int		do_polled_io;
23578 
23579 	ASSERT(pkt->pkt_scbp);
23580 
23581 	/*
23582 	 * save old flags..
23583 	 */
23584 	savef = pkt->pkt_flags;
23585 	savec = pkt->pkt_comp;
23586 	savet = pkt->pkt_time;
23587 
23588 	pkt->pkt_flags |= FLAG_NOINTR;
23589 
23590 	/*
23591 	 * XXX there is nothing in the SCSA spec that states that we should not
23592 	 * do a callback for polled cmds; however, removing this will break sd
23593 	 * and probably other target drivers
23594 	 */
23595 	pkt->pkt_comp = NULL;
23596 
23597 	/*
23598 	 * we don't like a polled command without timeout.
23599 	 * 60 seconds seems long enough.
23600 	 */
23601 	if (pkt->pkt_time == 0)
23602 		pkt->pkt_time = SCSI_POLL_TIMEOUT;
23603 
23604 	/*
23605 	 * Send polled cmd.
23606 	 *
23607 	 * We do some error recovery for various errors.  Tran_busy,
23608 	 * queue full, and non-dispatched commands are retried every 10 msec.
23609 	 * as they are typically transient failures.  Busy status and Not
23610 	 * Ready are retried every second as this status takes a while to
23611 	 * change.
23612 	 */
23613 	timeout = pkt->pkt_time * SEC_TO_CSEC;
23614 
23615 	for (busy_count = 0; busy_count < timeout; busy_count++) {
23616 		/*
23617 		 * Initialize pkt status variables.
23618 		 */
23619 		*pkt->pkt_scbp = pkt->pkt_reason = pkt->pkt_state = 0;
23620 
23621 		if ((rc = scsi_transport(pkt)) != TRAN_ACCEPT) {
23622 			if (rc != TRAN_BUSY) {
23623 				/* Transport failed - give up. */
23624 				break;
23625 			} else {
23626 				/* Transport busy - try again. */
23627 				poll_delay = 1 * CSEC;		/* 10 msec. */
23628 			}
23629 		} else {
23630 			/*
23631 			 * Transport accepted - check pkt status.
23632 			 */
23633 			rc = (*pkt->pkt_scbp) & STATUS_MASK;
23634 			if ((pkt->pkt_reason == CMD_CMPLT) &&
23635 			    (rc == STATUS_CHECK) &&
23636 			    (pkt->pkt_state & STATE_ARQ_DONE)) {
23637 				arqstat =
23638 				    (struct scsi_arq_status *)(pkt->pkt_scbp);
23639 				sensep = (uint8_t *)&arqstat->sts_sensedata;
23640 			} else {
23641 				sensep = NULL;
23642 			}
23643 
23644 			if ((pkt->pkt_reason == CMD_CMPLT) &&
23645 			    (rc == STATUS_GOOD)) {
23646 				/* No error - we're done */
23647 				rval = 0;
23648 				break;
23649 
23650 			} else if (pkt->pkt_reason == CMD_DEV_GONE) {
23651 				/* Lost connection - give up */
23652 				break;
23653 
23654 			} else if ((pkt->pkt_reason == CMD_INCOMPLETE) &&
23655 			    (pkt->pkt_state == 0)) {
23656 				/* Pkt not dispatched - try again. */
23657 				poll_delay = 1 * CSEC;		/* 10 msec. */
23658 
23659 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23660 			    (rc == STATUS_QFULL)) {
23661 				/* Queue full - try again. */
23662 				poll_delay = 1 * CSEC;		/* 10 msec. */
23663 
23664 			} else if ((pkt->pkt_reason == CMD_CMPLT) &&
23665 			    (rc == STATUS_BUSY)) {
23666 				/* Busy - try again. */
23667 				poll_delay = 100 * CSEC;	/* 1 sec. */
23668 				busy_count += (SEC_TO_CSEC - 1);
23669 
23670 			} else if ((sensep != NULL) &&
23671 			    (scsi_sense_key(sensep) == KEY_UNIT_ATTENTION)) {
23672 				/*
23673 				 * Unit Attention - try again.
23674 				 * Pretend it took 1 sec.
23675 				 * NOTE: 'continue' avoids poll_delay
23676 				 */
23677 				busy_count += (SEC_TO_CSEC - 1);
23678 				continue;
23679 
23680 			} else if ((sensep != NULL) &&
23681 			    (scsi_sense_key(sensep) == KEY_NOT_READY) &&
23682 			    (scsi_sense_asc(sensep) == 0x04) &&
23683 			    (scsi_sense_ascq(sensep) == 0x01)) {
23684 				/*
23685 				 * Not ready -> ready - try again.
23686 				 * 04h/01h: LUN IS IN PROCESS OF BECOMING READY
23687 				 * ...same as STATUS_BUSY
23688 				 */
23689 				poll_delay = 100 * CSEC;	/* 1 sec. */
23690 				busy_count += (SEC_TO_CSEC - 1);
23691 
23692 			} else {
23693 				/* BAD status - give up. */
23694 				break;
23695 			}
23696 		}
23697 
23698 		if (((curthread->t_flag & T_INTR_THREAD) == 0) &&
23699 		    !do_polled_io) {
23700 			delay(drv_usectohz(poll_delay));
23701 		} else {
23702 			/* we busy wait during cpr_dump or interrupt threads */
23703 			drv_usecwait(poll_delay);
23704 		}
23705 	}
23706 
23707 	pkt->pkt_flags = savef;
23708 	pkt->pkt_comp = savec;
23709 	pkt->pkt_time = savet;
23710 
23711 	/* return on error */
23712 	if (rval)
23713 		return (rval);
23714 
23715 	/*
23716 	 * This is not a performance critical code path.
23717 	 *
23718 	 * As an accommodation for scsi_poll callers, to avoid ddi_dma_sync()
23719 	 * issues associated with looking at DMA memory prior to
23720 	 * scsi_pkt_destroy(), we scsi_sync_pkt() prior to return.
23721 	 */
23722 	scsi_sync_pkt(pkt);
23723 	return (0);
23724 }
23725 
23726 
23727 
23728 /*
23729  *    Function: sd_persistent_reservation_in_read_keys
23730  *
23731  * Description: This routine is the driver entry point for handling CD-ROM
23732  *		multi-host persistent reservation requests (MHIOCGRP_INKEYS)
23733  *		by sending the SCSI-3 PRIN commands to the device.
23734  *		Processes the read keys command response by copying the
23735  *		reservation key information into the user provided buffer.
23736  *		Support for the 32/64 bit _MULTI_DATAMODEL is implemented.
23737  *
23738  *   Arguments: un   -  Pointer to soft state struct for the target.
23739  *		usrp -	user provided pointer to multihost Persistent In Read
23740  *			Keys structure (mhioc_inkeys_t)
23741  *		flag -	this argument is a pass through to ddi_copyxxx()
23742  *			directly from the mode argument of ioctl().
23743  *
23744  * Return Code: 0   - Success
23745  *		EACCES
23746  *		ENOTSUP
23747  *		errno return code from sd_send_scsi_cmd()
23748  *
23749  *     Context: Can sleep. Does not return until command is completed.
23750  */
23751 
23752 static int
23753 sd_persistent_reservation_in_read_keys(struct sd_lun *un,
23754     mhioc_inkeys_t *usrp, int flag)
23755 {
23756 #ifdef _MULTI_DATAMODEL
23757 	struct mhioc_key_list32	li32;
23758 #endif
23759 	sd_prin_readkeys_t	*in;
23760 	mhioc_inkeys_t		*ptr;
23761 	mhioc_key_list_t	li;
23762 	uchar_t			*data_bufp;
23763 	int 			data_len;
23764 	int			rval;
23765 	size_t			copysz;
23766 
23767 	if ((ptr = (mhioc_inkeys_t *)usrp) == NULL) {
23768 		return (EINVAL);
23769 	}
23770 	bzero(&li, sizeof (mhioc_key_list_t));
23771 
23772 	/*
23773 	 * Get the listsize from user
23774 	 */
23775 #ifdef _MULTI_DATAMODEL
23776 
23777 	switch (ddi_model_convert_from(flag & FMODELS)) {
23778 	case DDI_MODEL_ILP32:
23779 		copysz = sizeof (struct mhioc_key_list32);
23780 		if (ddi_copyin(ptr->li, &li32, copysz, flag)) {
23781 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23782 			    "sd_persistent_reservation_in_read_keys: "
23783 			    "failed ddi_copyin: mhioc_key_list32_t\n");
23784 			rval = EFAULT;
23785 			goto done;
23786 		}
23787 		li.listsize = li32.listsize;
23788 		li.list = (mhioc_resv_key_t *)(uintptr_t)li32.list;
23789 		break;
23790 
23791 	case DDI_MODEL_NONE:
23792 		copysz = sizeof (mhioc_key_list_t);
23793 		if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23794 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23795 			    "sd_persistent_reservation_in_read_keys: "
23796 			    "failed ddi_copyin: mhioc_key_list_t\n");
23797 			rval = EFAULT;
23798 			goto done;
23799 		}
23800 		break;
23801 	}
23802 
23803 #else /* ! _MULTI_DATAMODEL */
23804 	copysz = sizeof (mhioc_key_list_t);
23805 	if (ddi_copyin(ptr->li, &li, copysz, flag)) {
23806 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23807 		    "sd_persistent_reservation_in_read_keys: "
23808 		    "failed ddi_copyin: mhioc_key_list_t\n");
23809 		rval = EFAULT;
23810 		goto done;
23811 	}
23812 #endif
23813 
23814 	data_len  = li.listsize * MHIOC_RESV_KEY_SIZE;
23815 	data_len += (sizeof (sd_prin_readkeys_t) - sizeof (caddr_t));
23816 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23817 
23818 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_KEYS,
23819 	    data_len, data_bufp)) != 0) {
23820 		goto done;
23821 	}
23822 	in = (sd_prin_readkeys_t *)data_bufp;
23823 	ptr->generation = BE_32(in->generation);
23824 	li.listlen = BE_32(in->len) / MHIOC_RESV_KEY_SIZE;
23825 
23826 	/*
23827 	 * Return the min(listsize, listlen) keys
23828 	 */
23829 #ifdef _MULTI_DATAMODEL
23830 
23831 	switch (ddi_model_convert_from(flag & FMODELS)) {
23832 	case DDI_MODEL_ILP32:
23833 		li32.listlen = li.listlen;
23834 		if (ddi_copyout(&li32, ptr->li, copysz, flag)) {
23835 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23836 			    "sd_persistent_reservation_in_read_keys: "
23837 			    "failed ddi_copyout: mhioc_key_list32_t\n");
23838 			rval = EFAULT;
23839 			goto done;
23840 		}
23841 		break;
23842 
23843 	case DDI_MODEL_NONE:
23844 		if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23845 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23846 			    "sd_persistent_reservation_in_read_keys: "
23847 			    "failed ddi_copyout: mhioc_key_list_t\n");
23848 			rval = EFAULT;
23849 			goto done;
23850 		}
23851 		break;
23852 	}
23853 
23854 #else /* ! _MULTI_DATAMODEL */
23855 
23856 	if (ddi_copyout(&li, ptr->li, copysz, flag)) {
23857 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23858 		    "sd_persistent_reservation_in_read_keys: "
23859 		    "failed ddi_copyout: mhioc_key_list_t\n");
23860 		rval = EFAULT;
23861 		goto done;
23862 	}
23863 
23864 #endif /* _MULTI_DATAMODEL */
23865 
23866 	copysz = min(li.listlen * MHIOC_RESV_KEY_SIZE,
23867 	    li.listsize * MHIOC_RESV_KEY_SIZE);
23868 	if (ddi_copyout(&in->keylist, li.list, copysz, flag)) {
23869 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23870 		    "sd_persistent_reservation_in_read_keys: "
23871 		    "failed ddi_copyout: keylist\n");
23872 		rval = EFAULT;
23873 	}
23874 done:
23875 	kmem_free(data_bufp, data_len);
23876 	return (rval);
23877 }
23878 
23879 
23880 /*
23881  *    Function: sd_persistent_reservation_in_read_resv
23882  *
23883  * Description: This routine is the driver entry point for handling CD-ROM
23884  *		multi-host persistent reservation requests (MHIOCGRP_INRESV)
23885  *		by sending the SCSI-3 PRIN commands to the device.
23886  *		Process the read persistent reservations command response by
23887  *		copying the reservation information into the user provided
23888  *		buffer. Support for the 32/64 _MULTI_DATAMODEL is implemented.
23889  *
23890  *   Arguments: un   -  Pointer to soft state struct for the target.
23891  *		usrp -	user provided pointer to multihost Persistent In Read
23892  *			Keys structure (mhioc_inkeys_t)
23893  *		flag -	this argument is a pass through to ddi_copyxxx()
23894  *			directly from the mode argument of ioctl().
23895  *
23896  * Return Code: 0   - Success
23897  *		EACCES
23898  *		ENOTSUP
23899  *		errno return code from sd_send_scsi_cmd()
23900  *
23901  *     Context: Can sleep. Does not return until command is completed.
23902  */
23903 
23904 static int
23905 sd_persistent_reservation_in_read_resv(struct sd_lun *un,
23906     mhioc_inresvs_t *usrp, int flag)
23907 {
23908 #ifdef _MULTI_DATAMODEL
23909 	struct mhioc_resv_desc_list32 resvlist32;
23910 #endif
23911 	sd_prin_readresv_t	*in;
23912 	mhioc_inresvs_t		*ptr;
23913 	sd_readresv_desc_t	*readresv_ptr;
23914 	mhioc_resv_desc_list_t	resvlist;
23915 	mhioc_resv_desc_t 	resvdesc;
23916 	uchar_t			*data_bufp;
23917 	int 			data_len;
23918 	int			rval;
23919 	int			i;
23920 	size_t			copysz;
23921 	mhioc_resv_desc_t	*bufp;
23922 
23923 	if ((ptr = usrp) == NULL) {
23924 		return (EINVAL);
23925 	}
23926 
23927 	/*
23928 	 * Get the listsize from user
23929 	 */
23930 #ifdef _MULTI_DATAMODEL
23931 	switch (ddi_model_convert_from(flag & FMODELS)) {
23932 	case DDI_MODEL_ILP32:
23933 		copysz = sizeof (struct mhioc_resv_desc_list32);
23934 		if (ddi_copyin(ptr->li, &resvlist32, copysz, flag)) {
23935 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23936 			    "sd_persistent_reservation_in_read_resv: "
23937 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23938 			rval = EFAULT;
23939 			goto done;
23940 		}
23941 		resvlist.listsize = resvlist32.listsize;
23942 		resvlist.list = (mhioc_resv_desc_t *)(uintptr_t)resvlist32.list;
23943 		break;
23944 
23945 	case DDI_MODEL_NONE:
23946 		copysz = sizeof (mhioc_resv_desc_list_t);
23947 		if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23948 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23949 			    "sd_persistent_reservation_in_read_resv: "
23950 			    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23951 			rval = EFAULT;
23952 			goto done;
23953 		}
23954 		break;
23955 	}
23956 #else /* ! _MULTI_DATAMODEL */
23957 	copysz = sizeof (mhioc_resv_desc_list_t);
23958 	if (ddi_copyin(ptr->li, &resvlist, copysz, flag)) {
23959 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
23960 		    "sd_persistent_reservation_in_read_resv: "
23961 		    "failed ddi_copyin: mhioc_resv_desc_list_t\n");
23962 		rval = EFAULT;
23963 		goto done;
23964 	}
23965 #endif /* ! _MULTI_DATAMODEL */
23966 
23967 	data_len  = resvlist.listsize * SCSI3_RESV_DESC_LEN;
23968 	data_len += (sizeof (sd_prin_readresv_t) - sizeof (caddr_t));
23969 	data_bufp = kmem_zalloc(data_len, KM_SLEEP);
23970 
23971 	if ((rval = sd_send_scsi_PERSISTENT_RESERVE_IN(un, SD_READ_RESV,
23972 	    data_len, data_bufp)) != 0) {
23973 		goto done;
23974 	}
23975 	in = (sd_prin_readresv_t *)data_bufp;
23976 	ptr->generation = BE_32(in->generation);
23977 	resvlist.listlen = BE_32(in->len) / SCSI3_RESV_DESC_LEN;
23978 
23979 	/*
23980 	 * Return the min(listsize, listlen( keys
23981 	 */
23982 #ifdef _MULTI_DATAMODEL
23983 
23984 	switch (ddi_model_convert_from(flag & FMODELS)) {
23985 	case DDI_MODEL_ILP32:
23986 		resvlist32.listlen = resvlist.listlen;
23987 		if (ddi_copyout(&resvlist32, ptr->li, copysz, flag)) {
23988 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23989 			    "sd_persistent_reservation_in_read_resv: "
23990 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
23991 			rval = EFAULT;
23992 			goto done;
23993 		}
23994 		break;
23995 
23996 	case DDI_MODEL_NONE:
23997 		if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
23998 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
23999 			    "sd_persistent_reservation_in_read_resv: "
24000 			    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
24001 			rval = EFAULT;
24002 			goto done;
24003 		}
24004 		break;
24005 	}
24006 
24007 #else /* ! _MULTI_DATAMODEL */
24008 
24009 	if (ddi_copyout(&resvlist, ptr->li, copysz, flag)) {
24010 		SD_ERROR(SD_LOG_IOCTL_MHD, un,
24011 		    "sd_persistent_reservation_in_read_resv: "
24012 		    "failed ddi_copyout: mhioc_resv_desc_list_t\n");
24013 		rval = EFAULT;
24014 		goto done;
24015 	}
24016 
24017 #endif /* ! _MULTI_DATAMODEL */
24018 
24019 	readresv_ptr = (sd_readresv_desc_t *)&in->readresv_desc;
24020 	bufp = resvlist.list;
24021 	copysz = sizeof (mhioc_resv_desc_t);
24022 	for (i = 0; i < min(resvlist.listlen, resvlist.listsize);
24023 	    i++, readresv_ptr++, bufp++) {
24024 
24025 		bcopy(&readresv_ptr->resvkey, &resvdesc.key,
24026 		    MHIOC_RESV_KEY_SIZE);
24027 		resvdesc.type  = readresv_ptr->type;
24028 		resvdesc.scope = readresv_ptr->scope;
24029 		resvdesc.scope_specific_addr =
24030 		    BE_32(readresv_ptr->scope_specific_addr);
24031 
24032 		if (ddi_copyout(&resvdesc, bufp, copysz, flag)) {
24033 			SD_ERROR(SD_LOG_IOCTL_MHD, un,
24034 			    "sd_persistent_reservation_in_read_resv: "
24035 			    "failed ddi_copyout: resvlist\n");
24036 			rval = EFAULT;
24037 			goto done;
24038 		}
24039 	}
24040 done:
24041 	kmem_free(data_bufp, data_len);
24042 	return (rval);
24043 }
24044 
24045 
24046 /*
24047  *    Function: sr_change_blkmode()
24048  *
24049  * Description: This routine is the driver entry point for handling CD-ROM
24050  *		block mode ioctl requests. Support for returning and changing
24051  *		the current block size in use by the device is implemented. The
24052  *		LBA size is changed via a MODE SELECT Block Descriptor.
24053  *
24054  *		This routine issues a mode sense with an allocation length of
24055  *		12 bytes for the mode page header and a single block descriptor.
24056  *
24057  *   Arguments: dev - the device 'dev_t'
24058  *		cmd - the request type; one of CDROMGBLKMODE (get) or
24059  *		      CDROMSBLKMODE (set)
24060  *		data - current block size or requested block size
24061  *		flag - this argument is a pass through to ddi_copyxxx() directly
24062  *		       from the mode argument of ioctl().
24063  *
24064  * Return Code: the code returned by sd_send_scsi_cmd()
24065  *		EINVAL if invalid arguments are provided
24066  *		EFAULT if ddi_copyxxx() fails
24067  *		ENXIO if fail ddi_get_soft_state
24068  *		EIO if invalid mode sense block descriptor length
24069  *
24070  */
24071 
24072 static int
24073 sr_change_blkmode(dev_t dev, int cmd, intptr_t data, int flag)
24074 {
24075 	struct sd_lun			*un = NULL;
24076 	struct mode_header		*sense_mhp, *select_mhp;
24077 	struct block_descriptor		*sense_desc, *select_desc;
24078 	int				current_bsize;
24079 	int				rval = EINVAL;
24080 	uchar_t				*sense = NULL;
24081 	uchar_t				*select = NULL;
24082 
24083 	ASSERT((cmd == CDROMGBLKMODE) || (cmd == CDROMSBLKMODE));
24084 
24085 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24086 		return (ENXIO);
24087 	}
24088 
24089 	/*
24090 	 * The block length is changed via the Mode Select block descriptor, the
24091 	 * "Read/Write Error Recovery" mode page (0x1) contents are not actually
24092 	 * required as part of this routine. Therefore the mode sense allocation
24093 	 * length is specified to be the length of a mode page header and a
24094 	 * block descriptor.
24095 	 */
24096 	sense = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
24097 
24098 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
24099 	    BUFLEN_CHG_BLK_MODE, MODEPAGE_ERR_RECOV, SD_PATH_STANDARD)) != 0) {
24100 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24101 		    "sr_change_blkmode: Mode Sense Failed\n");
24102 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
24103 		return (rval);
24104 	}
24105 
24106 	/* Check the block descriptor len to handle only 1 block descriptor */
24107 	sense_mhp = (struct mode_header *)sense;
24108 	if ((sense_mhp->bdesc_length == 0) ||
24109 	    (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH)) {
24110 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24111 		    "sr_change_blkmode: Mode Sense returned invalid block"
24112 		    " descriptor length\n");
24113 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
24114 		return (EIO);
24115 	}
24116 	sense_desc = (struct block_descriptor *)(sense + MODE_HEADER_LENGTH);
24117 	current_bsize = ((sense_desc->blksize_hi << 16) |
24118 	    (sense_desc->blksize_mid << 8) | sense_desc->blksize_lo);
24119 
24120 	/* Process command */
24121 	switch (cmd) {
24122 	case CDROMGBLKMODE:
24123 		/* Return the block size obtained during the mode sense */
24124 		if (ddi_copyout(&current_bsize, (void *)data,
24125 		    sizeof (int), flag) != 0)
24126 			rval = EFAULT;
24127 		break;
24128 	case CDROMSBLKMODE:
24129 		/* Validate the requested block size */
24130 		switch (data) {
24131 		case CDROM_BLK_512:
24132 		case CDROM_BLK_1024:
24133 		case CDROM_BLK_2048:
24134 		case CDROM_BLK_2056:
24135 		case CDROM_BLK_2336:
24136 		case CDROM_BLK_2340:
24137 		case CDROM_BLK_2352:
24138 		case CDROM_BLK_2368:
24139 		case CDROM_BLK_2448:
24140 		case CDROM_BLK_2646:
24141 		case CDROM_BLK_2647:
24142 			break;
24143 		default:
24144 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24145 			    "sr_change_blkmode: "
24146 			    "Block Size '%ld' Not Supported\n", data);
24147 			kmem_free(sense, BUFLEN_CHG_BLK_MODE);
24148 			return (EINVAL);
24149 		}
24150 
24151 		/*
24152 		 * The current block size matches the requested block size so
24153 		 * there is no need to send the mode select to change the size
24154 		 */
24155 		if (current_bsize == data) {
24156 			break;
24157 		}
24158 
24159 		/* Build the select data for the requested block size */
24160 		select = kmem_zalloc(BUFLEN_CHG_BLK_MODE, KM_SLEEP);
24161 		select_mhp = (struct mode_header *)select;
24162 		select_desc =
24163 		    (struct block_descriptor *)(select + MODE_HEADER_LENGTH);
24164 		/*
24165 		 * The LBA size is changed via the block descriptor, so the
24166 		 * descriptor is built according to the user data
24167 		 */
24168 		select_mhp->bdesc_length = MODE_BLK_DESC_LENGTH;
24169 		select_desc->blksize_hi  = (char)(((data) & 0x00ff0000) >> 16);
24170 		select_desc->blksize_mid = (char)(((data) & 0x0000ff00) >> 8);
24171 		select_desc->blksize_lo  = (char)((data) & 0x000000ff);
24172 
24173 		/* Send the mode select for the requested block size */
24174 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
24175 		    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
24176 		    SD_PATH_STANDARD)) != 0) {
24177 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24178 			    "sr_change_blkmode: Mode Select Failed\n");
24179 			/*
24180 			 * The mode select failed for the requested block size,
24181 			 * so reset the data for the original block size and
24182 			 * send it to the target. The error is indicated by the
24183 			 * return value for the failed mode select.
24184 			 */
24185 			select_desc->blksize_hi  = sense_desc->blksize_hi;
24186 			select_desc->blksize_mid = sense_desc->blksize_mid;
24187 			select_desc->blksize_lo  = sense_desc->blksize_lo;
24188 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0,
24189 			    select, BUFLEN_CHG_BLK_MODE, SD_DONTSAVE_PAGE,
24190 			    SD_PATH_STANDARD);
24191 		} else {
24192 			ASSERT(!mutex_owned(SD_MUTEX(un)));
24193 			mutex_enter(SD_MUTEX(un));
24194 			sd_update_block_info(un, (uint32_t)data, 0);
24195 			mutex_exit(SD_MUTEX(un));
24196 		}
24197 		break;
24198 	default:
24199 		/* should not reach here, but check anyway */
24200 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24201 		    "sr_change_blkmode: Command '%x' Not Supported\n", cmd);
24202 		rval = EINVAL;
24203 		break;
24204 	}
24205 
24206 	if (select) {
24207 		kmem_free(select, BUFLEN_CHG_BLK_MODE);
24208 	}
24209 	if (sense) {
24210 		kmem_free(sense, BUFLEN_CHG_BLK_MODE);
24211 	}
24212 	return (rval);
24213 }
24214 
24215 
24216 /*
24217  * Note: The following sr_change_speed() and sr_atapi_change_speed() routines
24218  * implement driver support for getting and setting the CD speed. The command
24219  * set used will be based on the device type. If the device has not been
24220  * identified as MMC the Toshiba vendor specific mode page will be used. If
24221  * the device is MMC but does not support the Real Time Streaming feature
24222  * the SET CD SPEED command will be used to set speed and mode page 0x2A will
24223  * be used to read the speed.
24224  */
24225 
24226 /*
24227  *    Function: sr_change_speed()
24228  *
24229  * Description: This routine is the driver entry point for handling CD-ROM
24230  *		drive speed ioctl requests for devices supporting the Toshiba
24231  *		vendor specific drive speed mode page. Support for returning
24232  *		and changing the current drive speed in use by the device is
24233  *		implemented.
24234  *
24235  *   Arguments: dev - the device 'dev_t'
24236  *		cmd - the request type; one of CDROMGDRVSPEED (get) or
24237  *		      CDROMSDRVSPEED (set)
24238  *		data - current drive speed or requested drive speed
24239  *		flag - this argument is a pass through to ddi_copyxxx() directly
24240  *		       from the mode argument of ioctl().
24241  *
24242  * Return Code: the code returned by sd_send_scsi_cmd()
24243  *		EINVAL if invalid arguments are provided
24244  *		EFAULT if ddi_copyxxx() fails
24245  *		ENXIO if fail ddi_get_soft_state
24246  *		EIO if invalid mode sense block descriptor length
24247  */
24248 
24249 static int
24250 sr_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
24251 {
24252 	struct sd_lun			*un = NULL;
24253 	struct mode_header		*sense_mhp, *select_mhp;
24254 	struct mode_speed		*sense_page, *select_page;
24255 	int				current_speed;
24256 	int				rval = EINVAL;
24257 	int				bd_len;
24258 	uchar_t				*sense = NULL;
24259 	uchar_t				*select = NULL;
24260 
24261 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
24262 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24263 		return (ENXIO);
24264 	}
24265 
24266 	/*
24267 	 * Note: The drive speed is being modified here according to a Toshiba
24268 	 * vendor specific mode page (0x31).
24269 	 */
24270 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
24271 
24272 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
24273 	    BUFLEN_MODE_CDROM_SPEED, CDROM_MODE_SPEED,
24274 	    SD_PATH_STANDARD)) != 0) {
24275 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24276 		    "sr_change_speed: Mode Sense Failed\n");
24277 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24278 		return (rval);
24279 	}
24280 	sense_mhp  = (struct mode_header *)sense;
24281 
24282 	/* Check the block descriptor len to handle only 1 block descriptor */
24283 	bd_len = sense_mhp->bdesc_length;
24284 	if (bd_len > MODE_BLK_DESC_LENGTH) {
24285 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24286 		    "sr_change_speed: Mode Sense returned invalid block "
24287 		    "descriptor length\n");
24288 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24289 		return (EIO);
24290 	}
24291 
24292 	sense_page = (struct mode_speed *)
24293 	    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
24294 	current_speed = sense_page->speed;
24295 
24296 	/* Process command */
24297 	switch (cmd) {
24298 	case CDROMGDRVSPEED:
24299 		/* Return the drive speed obtained during the mode sense */
24300 		if (current_speed == 0x2) {
24301 			current_speed = CDROM_TWELVE_SPEED;
24302 		}
24303 		if (ddi_copyout(&current_speed, (void *)data,
24304 		    sizeof (int), flag) != 0) {
24305 			rval = EFAULT;
24306 		}
24307 		break;
24308 	case CDROMSDRVSPEED:
24309 		/* Validate the requested drive speed */
24310 		switch ((uchar_t)data) {
24311 		case CDROM_TWELVE_SPEED:
24312 			data = 0x2;
24313 			/*FALLTHROUGH*/
24314 		case CDROM_NORMAL_SPEED:
24315 		case CDROM_DOUBLE_SPEED:
24316 		case CDROM_QUAD_SPEED:
24317 		case CDROM_MAXIMUM_SPEED:
24318 			break;
24319 		default:
24320 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24321 			    "sr_change_speed: "
24322 			    "Drive Speed '%d' Not Supported\n", (uchar_t)data);
24323 			kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24324 			return (EINVAL);
24325 		}
24326 
24327 		/*
24328 		 * The current drive speed matches the requested drive speed so
24329 		 * there is no need to send the mode select to change the speed
24330 		 */
24331 		if (current_speed == data) {
24332 			break;
24333 		}
24334 
24335 		/* Build the select data for the requested drive speed */
24336 		select = kmem_zalloc(BUFLEN_MODE_CDROM_SPEED, KM_SLEEP);
24337 		select_mhp = (struct mode_header *)select;
24338 		select_mhp->bdesc_length = 0;
24339 		select_page =
24340 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
24341 		select_page =
24342 		    (struct mode_speed *)(select + MODE_HEADER_LENGTH);
24343 		select_page->mode_page.code = CDROM_MODE_SPEED;
24344 		select_page->mode_page.length = 2;
24345 		select_page->speed = (uchar_t)data;
24346 
24347 		/* Send the mode select for the requested block size */
24348 		if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
24349 		    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
24350 		    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
24351 			/*
24352 			 * The mode select failed for the requested drive speed,
24353 			 * so reset the data for the original drive speed and
24354 			 * send it to the target. The error is indicated by the
24355 			 * return value for the failed mode select.
24356 			 */
24357 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24358 			    "sr_drive_speed: Mode Select Failed\n");
24359 			select_page->speed = sense_page->speed;
24360 			(void) sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
24361 			    MODEPAGE_CDROM_SPEED_LEN + MODE_HEADER_LENGTH,
24362 			    SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
24363 		}
24364 		break;
24365 	default:
24366 		/* should not reach here, but check anyway */
24367 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24368 		    "sr_change_speed: Command '%x' Not Supported\n", cmd);
24369 		rval = EINVAL;
24370 		break;
24371 	}
24372 
24373 	if (select) {
24374 		kmem_free(select, BUFLEN_MODE_CDROM_SPEED);
24375 	}
24376 	if (sense) {
24377 		kmem_free(sense, BUFLEN_MODE_CDROM_SPEED);
24378 	}
24379 
24380 	return (rval);
24381 }
24382 
24383 
24384 /*
24385  *    Function: sr_atapi_change_speed()
24386  *
24387  * Description: This routine is the driver entry point for handling CD-ROM
24388  *		drive speed ioctl requests for MMC devices that do not support
24389  *		the Real Time Streaming feature (0x107).
24390  *
24391  *		Note: This routine will use the SET SPEED command which may not
24392  *		be supported by all devices.
24393  *
24394  *   Arguments: dev- the device 'dev_t'
24395  *		cmd- the request type; one of CDROMGDRVSPEED (get) or
24396  *		     CDROMSDRVSPEED (set)
24397  *		data- current drive speed or requested drive speed
24398  *		flag- this argument is a pass through to ddi_copyxxx() directly
24399  *		      from the mode argument of ioctl().
24400  *
24401  * Return Code: the code returned by sd_send_scsi_cmd()
24402  *		EINVAL if invalid arguments are provided
24403  *		EFAULT if ddi_copyxxx() fails
24404  *		ENXIO if fail ddi_get_soft_state
24405  *		EIO if invalid mode sense block descriptor length
24406  */
24407 
24408 static int
24409 sr_atapi_change_speed(dev_t dev, int cmd, intptr_t data, int flag)
24410 {
24411 	struct sd_lun			*un;
24412 	struct uscsi_cmd		*com = NULL;
24413 	struct mode_header_grp2		*sense_mhp;
24414 	uchar_t				*sense_page;
24415 	uchar_t				*sense = NULL;
24416 	char				cdb[CDB_GROUP5];
24417 	int				bd_len;
24418 	int				current_speed = 0;
24419 	int				max_speed = 0;
24420 	int				rval;
24421 
24422 	ASSERT((cmd == CDROMGDRVSPEED) || (cmd == CDROMSDRVSPEED));
24423 
24424 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24425 		return (ENXIO);
24426 	}
24427 
24428 	sense = kmem_zalloc(BUFLEN_MODE_CDROM_CAP, KM_SLEEP);
24429 
24430 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
24431 	    BUFLEN_MODE_CDROM_CAP, MODEPAGE_CDROM_CAP,
24432 	    SD_PATH_STANDARD)) != 0) {
24433 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24434 		    "sr_atapi_change_speed: Mode Sense Failed\n");
24435 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24436 		return (rval);
24437 	}
24438 
24439 	/* Check the block descriptor len to handle only 1 block descriptor */
24440 	sense_mhp = (struct mode_header_grp2 *)sense;
24441 	bd_len = (sense_mhp->bdesc_length_hi << 8) | sense_mhp->bdesc_length_lo;
24442 	if (bd_len > MODE_BLK_DESC_LENGTH) {
24443 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24444 		    "sr_atapi_change_speed: Mode Sense returned invalid "
24445 		    "block descriptor length\n");
24446 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24447 		return (EIO);
24448 	}
24449 
24450 	/* Calculate the current and maximum drive speeds */
24451 	sense_page = (uchar_t *)(sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
24452 	current_speed = (sense_page[14] << 8) | sense_page[15];
24453 	max_speed = (sense_page[8] << 8) | sense_page[9];
24454 
24455 	/* Process the command */
24456 	switch (cmd) {
24457 	case CDROMGDRVSPEED:
24458 		current_speed /= SD_SPEED_1X;
24459 		if (ddi_copyout(&current_speed, (void *)data,
24460 		    sizeof (int), flag) != 0)
24461 			rval = EFAULT;
24462 		break;
24463 	case CDROMSDRVSPEED:
24464 		/* Convert the speed code to KB/sec */
24465 		switch ((uchar_t)data) {
24466 		case CDROM_NORMAL_SPEED:
24467 			current_speed = SD_SPEED_1X;
24468 			break;
24469 		case CDROM_DOUBLE_SPEED:
24470 			current_speed = 2 * SD_SPEED_1X;
24471 			break;
24472 		case CDROM_QUAD_SPEED:
24473 			current_speed = 4 * SD_SPEED_1X;
24474 			break;
24475 		case CDROM_TWELVE_SPEED:
24476 			current_speed = 12 * SD_SPEED_1X;
24477 			break;
24478 		case CDROM_MAXIMUM_SPEED:
24479 			current_speed = 0xffff;
24480 			break;
24481 		default:
24482 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24483 			    "sr_atapi_change_speed: invalid drive speed %d\n",
24484 			    (uchar_t)data);
24485 			kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24486 			return (EINVAL);
24487 		}
24488 
24489 		/* Check the request against the drive's max speed. */
24490 		if (current_speed != 0xffff) {
24491 			if (current_speed > max_speed) {
24492 				kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24493 				return (EINVAL);
24494 			}
24495 		}
24496 
24497 		/*
24498 		 * Build and send the SET SPEED command
24499 		 *
24500 		 * Note: The SET SPEED (0xBB) command used in this routine is
24501 		 * obsolete per the SCSI MMC spec but still supported in the
24502 		 * MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
24503 		 * therefore the command is still implemented in this routine.
24504 		 */
24505 		bzero(cdb, sizeof (cdb));
24506 		cdb[0] = (char)SCMD_SET_CDROM_SPEED;
24507 		cdb[2] = (uchar_t)(current_speed >> 8);
24508 		cdb[3] = (uchar_t)current_speed;
24509 		com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24510 		com->uscsi_cdb	   = (caddr_t)cdb;
24511 		com->uscsi_cdblen  = CDB_GROUP5;
24512 		com->uscsi_bufaddr = NULL;
24513 		com->uscsi_buflen  = 0;
24514 		com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT;
24515 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, 0, SD_PATH_STANDARD);
24516 		break;
24517 	default:
24518 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24519 		    "sr_atapi_change_speed: Command '%x' Not Supported\n", cmd);
24520 		rval = EINVAL;
24521 	}
24522 
24523 	if (sense) {
24524 		kmem_free(sense, BUFLEN_MODE_CDROM_CAP);
24525 	}
24526 	if (com) {
24527 		kmem_free(com, sizeof (*com));
24528 	}
24529 	return (rval);
24530 }
24531 
24532 
24533 /*
24534  *    Function: sr_pause_resume()
24535  *
24536  * Description: This routine is the driver entry point for handling CD-ROM
24537  *		pause/resume ioctl requests. This only affects the audio play
24538  *		operation.
24539  *
24540  *   Arguments: dev - the device 'dev_t'
24541  *		cmd - the request type; one of CDROMPAUSE or CDROMRESUME, used
24542  *		      for setting the resume bit of the cdb.
24543  *
24544  * Return Code: the code returned by sd_send_scsi_cmd()
24545  *		EINVAL if invalid mode specified
24546  *
24547  */
24548 
24549 static int
24550 sr_pause_resume(dev_t dev, int cmd)
24551 {
24552 	struct sd_lun		*un;
24553 	struct uscsi_cmd	*com;
24554 	char			cdb[CDB_GROUP1];
24555 	int			rval;
24556 
24557 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24558 		return (ENXIO);
24559 	}
24560 
24561 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24562 	bzero(cdb, CDB_GROUP1);
24563 	cdb[0] = SCMD_PAUSE_RESUME;
24564 	switch (cmd) {
24565 	case CDROMRESUME:
24566 		cdb[8] = 1;
24567 		break;
24568 	case CDROMPAUSE:
24569 		cdb[8] = 0;
24570 		break;
24571 	default:
24572 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_pause_resume:"
24573 		    " Command '%x' Not Supported\n", cmd);
24574 		rval = EINVAL;
24575 		goto done;
24576 	}
24577 
24578 	com->uscsi_cdb    = cdb;
24579 	com->uscsi_cdblen = CDB_GROUP1;
24580 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24581 
24582 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24583 	    SD_PATH_STANDARD);
24584 
24585 done:
24586 	kmem_free(com, sizeof (*com));
24587 	return (rval);
24588 }
24589 
24590 
24591 /*
24592  *    Function: sr_play_msf()
24593  *
24594  * Description: This routine is the driver entry point for handling CD-ROM
24595  *		ioctl requests to output the audio signals at the specified
24596  *		starting address and continue the audio play until the specified
24597  *		ending address (CDROMPLAYMSF) The address is in Minute Second
24598  *		Frame (MSF) format.
24599  *
24600  *   Arguments: dev	- the device 'dev_t'
24601  *		data	- pointer to user provided audio msf structure,
24602  *		          specifying start/end addresses.
24603  *		flag	- this argument is a pass through to ddi_copyxxx()
24604  *		          directly from the mode argument of ioctl().
24605  *
24606  * Return Code: the code returned by sd_send_scsi_cmd()
24607  *		EFAULT if ddi_copyxxx() fails
24608  *		ENXIO if fail ddi_get_soft_state
24609  *		EINVAL if data pointer is NULL
24610  */
24611 
24612 static int
24613 sr_play_msf(dev_t dev, caddr_t data, int flag)
24614 {
24615 	struct sd_lun		*un;
24616 	struct uscsi_cmd	*com;
24617 	struct cdrom_msf	msf_struct;
24618 	struct cdrom_msf	*msf = &msf_struct;
24619 	char			cdb[CDB_GROUP1];
24620 	int			rval;
24621 
24622 	if (data == NULL) {
24623 		return (EINVAL);
24624 	}
24625 
24626 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24627 		return (ENXIO);
24628 	}
24629 
24630 	if (ddi_copyin(data, msf, sizeof (struct cdrom_msf), flag)) {
24631 		return (EFAULT);
24632 	}
24633 
24634 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24635 	bzero(cdb, CDB_GROUP1);
24636 	cdb[0] = SCMD_PLAYAUDIO_MSF;
24637 	if (un->un_f_cfg_playmsf_bcd == TRUE) {
24638 		cdb[3] = BYTE_TO_BCD(msf->cdmsf_min0);
24639 		cdb[4] = BYTE_TO_BCD(msf->cdmsf_sec0);
24640 		cdb[5] = BYTE_TO_BCD(msf->cdmsf_frame0);
24641 		cdb[6] = BYTE_TO_BCD(msf->cdmsf_min1);
24642 		cdb[7] = BYTE_TO_BCD(msf->cdmsf_sec1);
24643 		cdb[8] = BYTE_TO_BCD(msf->cdmsf_frame1);
24644 	} else {
24645 		cdb[3] = msf->cdmsf_min0;
24646 		cdb[4] = msf->cdmsf_sec0;
24647 		cdb[5] = msf->cdmsf_frame0;
24648 		cdb[6] = msf->cdmsf_min1;
24649 		cdb[7] = msf->cdmsf_sec1;
24650 		cdb[8] = msf->cdmsf_frame1;
24651 	}
24652 	com->uscsi_cdb    = cdb;
24653 	com->uscsi_cdblen = CDB_GROUP1;
24654 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24655 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24656 	    SD_PATH_STANDARD);
24657 	kmem_free(com, sizeof (*com));
24658 	return (rval);
24659 }
24660 
24661 
24662 /*
24663  *    Function: sr_play_trkind()
24664  *
24665  * Description: This routine is the driver entry point for handling CD-ROM
24666  *		ioctl requests to output the audio signals at the specified
24667  *		starting address and continue the audio play until the specified
24668  *		ending address (CDROMPLAYTRKIND). The address is in Track Index
24669  *		format.
24670  *
24671  *   Arguments: dev	- the device 'dev_t'
24672  *		data	- pointer to user provided audio track/index structure,
24673  *		          specifying start/end addresses.
24674  *		flag	- this argument is a pass through to ddi_copyxxx()
24675  *		          directly from the mode argument of ioctl().
24676  *
24677  * Return Code: the code returned by sd_send_scsi_cmd()
24678  *		EFAULT if ddi_copyxxx() fails
24679  *		ENXIO if fail ddi_get_soft_state
24680  *		EINVAL if data pointer is NULL
24681  */
24682 
24683 static int
24684 sr_play_trkind(dev_t dev, caddr_t data, int flag)
24685 {
24686 	struct cdrom_ti		ti_struct;
24687 	struct cdrom_ti		*ti = &ti_struct;
24688 	struct uscsi_cmd	*com = NULL;
24689 	char			cdb[CDB_GROUP1];
24690 	int			rval;
24691 
24692 	if (data == NULL) {
24693 		return (EINVAL);
24694 	}
24695 
24696 	if (ddi_copyin(data, ti, sizeof (struct cdrom_ti), flag)) {
24697 		return (EFAULT);
24698 	}
24699 
24700 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24701 	bzero(cdb, CDB_GROUP1);
24702 	cdb[0] = SCMD_PLAYAUDIO_TI;
24703 	cdb[4] = ti->cdti_trk0;
24704 	cdb[5] = ti->cdti_ind0;
24705 	cdb[7] = ti->cdti_trk1;
24706 	cdb[8] = ti->cdti_ind1;
24707 	com->uscsi_cdb    = cdb;
24708 	com->uscsi_cdblen = CDB_GROUP1;
24709 	com->uscsi_flags  = USCSI_DIAGNOSE|USCSI_SILENT;
24710 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24711 	    SD_PATH_STANDARD);
24712 	kmem_free(com, sizeof (*com));
24713 	return (rval);
24714 }
24715 
24716 
24717 /*
24718  *    Function: sr_read_all_subcodes()
24719  *
24720  * Description: This routine is the driver entry point for handling CD-ROM
24721  *		ioctl requests to return raw subcode data while the target is
24722  *		playing audio (CDROMSUBCODE).
24723  *
24724  *   Arguments: dev	- the device 'dev_t'
24725  *		data	- pointer to user provided cdrom subcode structure,
24726  *		          specifying the transfer length and address.
24727  *		flag	- this argument is a pass through to ddi_copyxxx()
24728  *		          directly from the mode argument of ioctl().
24729  *
24730  * Return Code: the code returned by sd_send_scsi_cmd()
24731  *		EFAULT if ddi_copyxxx() fails
24732  *		ENXIO if fail ddi_get_soft_state
24733  *		EINVAL if data pointer is NULL
24734  */
24735 
24736 static int
24737 sr_read_all_subcodes(dev_t dev, caddr_t data, int flag)
24738 {
24739 	struct sd_lun		*un = NULL;
24740 	struct uscsi_cmd	*com = NULL;
24741 	struct cdrom_subcode	*subcode = NULL;
24742 	int			rval;
24743 	size_t			buflen;
24744 	char			cdb[CDB_GROUP5];
24745 
24746 #ifdef _MULTI_DATAMODEL
24747 	/* To support ILP32 applications in an LP64 world */
24748 	struct cdrom_subcode32		cdrom_subcode32;
24749 	struct cdrom_subcode32		*cdsc32 = &cdrom_subcode32;
24750 #endif
24751 	if (data == NULL) {
24752 		return (EINVAL);
24753 	}
24754 
24755 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
24756 		return (ENXIO);
24757 	}
24758 
24759 	subcode = kmem_zalloc(sizeof (struct cdrom_subcode), KM_SLEEP);
24760 
24761 #ifdef _MULTI_DATAMODEL
24762 	switch (ddi_model_convert_from(flag & FMODELS)) {
24763 	case DDI_MODEL_ILP32:
24764 		if (ddi_copyin(data, cdsc32, sizeof (*cdsc32), flag)) {
24765 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24766 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24767 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24768 			return (EFAULT);
24769 		}
24770 		/* Convert the ILP32 uscsi data from the application to LP64 */
24771 		cdrom_subcode32tocdrom_subcode(cdsc32, subcode);
24772 		break;
24773 	case DDI_MODEL_NONE:
24774 		if (ddi_copyin(data, subcode,
24775 		    sizeof (struct cdrom_subcode), flag)) {
24776 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24777 			    "sr_read_all_subcodes: ddi_copyin Failed\n");
24778 			kmem_free(subcode, sizeof (struct cdrom_subcode));
24779 			return (EFAULT);
24780 		}
24781 		break;
24782 	}
24783 #else /* ! _MULTI_DATAMODEL */
24784 	if (ddi_copyin(data, subcode, sizeof (struct cdrom_subcode), flag)) {
24785 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24786 		    "sr_read_all_subcodes: ddi_copyin Failed\n");
24787 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24788 		return (EFAULT);
24789 	}
24790 #endif /* _MULTI_DATAMODEL */
24791 
24792 	/*
24793 	 * Since MMC-2 expects max 3 bytes for length, check if the
24794 	 * length input is greater than 3 bytes
24795 	 */
24796 	if ((subcode->cdsc_length & 0xFF000000) != 0) {
24797 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
24798 		    "sr_read_all_subcodes: "
24799 		    "cdrom transfer length too large: %d (limit %d)\n",
24800 		    subcode->cdsc_length, 0xFFFFFF);
24801 		kmem_free(subcode, sizeof (struct cdrom_subcode));
24802 		return (EINVAL);
24803 	}
24804 
24805 	buflen = CDROM_BLK_SUBCODE * subcode->cdsc_length;
24806 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24807 	bzero(cdb, CDB_GROUP5);
24808 
24809 	if (un->un_f_mmc_cap == TRUE) {
24810 		cdb[0] = (char)SCMD_READ_CD;
24811 		cdb[2] = (char)0xff;
24812 		cdb[3] = (char)0xff;
24813 		cdb[4] = (char)0xff;
24814 		cdb[5] = (char)0xff;
24815 		cdb[6] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24816 		cdb[7] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24817 		cdb[8] = ((subcode->cdsc_length) & 0x000000ff);
24818 		cdb[10] = 1;
24819 	} else {
24820 		/*
24821 		 * Note: A vendor specific command (0xDF) is being used her to
24822 		 * request a read of all subcodes.
24823 		 */
24824 		cdb[0] = (char)SCMD_READ_ALL_SUBCODES;
24825 		cdb[6] = (((subcode->cdsc_length) & 0xff000000) >> 24);
24826 		cdb[7] = (((subcode->cdsc_length) & 0x00ff0000) >> 16);
24827 		cdb[8] = (((subcode->cdsc_length) & 0x0000ff00) >> 8);
24828 		cdb[9] = ((subcode->cdsc_length) & 0x000000ff);
24829 	}
24830 	com->uscsi_cdb	   = cdb;
24831 	com->uscsi_cdblen  = CDB_GROUP5;
24832 	com->uscsi_bufaddr = (caddr_t)subcode->cdsc_addr;
24833 	com->uscsi_buflen  = buflen;
24834 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24835 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
24836 	    SD_PATH_STANDARD);
24837 	kmem_free(subcode, sizeof (struct cdrom_subcode));
24838 	kmem_free(com, sizeof (*com));
24839 	return (rval);
24840 }
24841 
24842 
24843 /*
24844  *    Function: sr_read_subchannel()
24845  *
24846  * Description: This routine is the driver entry point for handling CD-ROM
24847  *		ioctl requests to return the Q sub-channel data of the CD
24848  *		current position block. (CDROMSUBCHNL) The data includes the
24849  *		track number, index number, absolute CD-ROM address (LBA or MSF
24850  *		format per the user) , track relative CD-ROM address (LBA or MSF
24851  *		format per the user), control data and audio status.
24852  *
24853  *   Arguments: dev	- the device 'dev_t'
24854  *		data	- pointer to user provided cdrom sub-channel structure
24855  *		flag	- this argument is a pass through to ddi_copyxxx()
24856  *		          directly from the mode argument of ioctl().
24857  *
24858  * Return Code: the code returned by sd_send_scsi_cmd()
24859  *		EFAULT if ddi_copyxxx() fails
24860  *		ENXIO if fail ddi_get_soft_state
24861  *		EINVAL if data pointer is NULL
24862  */
24863 
24864 static int
24865 sr_read_subchannel(dev_t dev, caddr_t data, int flag)
24866 {
24867 	struct sd_lun		*un;
24868 	struct uscsi_cmd	*com;
24869 	struct cdrom_subchnl	subchanel;
24870 	struct cdrom_subchnl	*subchnl = &subchanel;
24871 	char			cdb[CDB_GROUP1];
24872 	caddr_t			buffer;
24873 	int			rval;
24874 
24875 	if (data == NULL) {
24876 		return (EINVAL);
24877 	}
24878 
24879 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24880 	    (un->un_state == SD_STATE_OFFLINE)) {
24881 		return (ENXIO);
24882 	}
24883 
24884 	if (ddi_copyin(data, subchnl, sizeof (struct cdrom_subchnl), flag)) {
24885 		return (EFAULT);
24886 	}
24887 
24888 	buffer = kmem_zalloc((size_t)16, KM_SLEEP);
24889 	bzero(cdb, CDB_GROUP1);
24890 	cdb[0] = SCMD_READ_SUBCHANNEL;
24891 	/* Set the MSF bit based on the user requested address format */
24892 	cdb[1] = (subchnl->cdsc_format & CDROM_LBA) ? 0 : 0x02;
24893 	/*
24894 	 * Set the Q bit in byte 2 to indicate that Q sub-channel data be
24895 	 * returned
24896 	 */
24897 	cdb[2] = 0x40;
24898 	/*
24899 	 * Set byte 3 to specify the return data format. A value of 0x01
24900 	 * indicates that the CD-ROM current position should be returned.
24901 	 */
24902 	cdb[3] = 0x01;
24903 	cdb[8] = 0x10;
24904 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
24905 	com->uscsi_cdb	   = cdb;
24906 	com->uscsi_cdblen  = CDB_GROUP1;
24907 	com->uscsi_bufaddr = buffer;
24908 	com->uscsi_buflen  = 16;
24909 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
24910 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
24911 	    SD_PATH_STANDARD);
24912 	if (rval != 0) {
24913 		kmem_free(buffer, 16);
24914 		kmem_free(com, sizeof (*com));
24915 		return (rval);
24916 	}
24917 
24918 	/* Process the returned Q sub-channel data */
24919 	subchnl->cdsc_audiostatus = buffer[1];
24920 	subchnl->cdsc_adr	= (buffer[5] & 0xF0);
24921 	subchnl->cdsc_ctrl	= (buffer[5] & 0x0F);
24922 	subchnl->cdsc_trk	= buffer[6];
24923 	subchnl->cdsc_ind	= buffer[7];
24924 	if (subchnl->cdsc_format & CDROM_LBA) {
24925 		subchnl->cdsc_absaddr.lba =
24926 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
24927 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
24928 		subchnl->cdsc_reladdr.lba =
24929 		    ((uchar_t)buffer[12] << 24) + ((uchar_t)buffer[13] << 16) +
24930 		    ((uchar_t)buffer[14] << 8) + ((uchar_t)buffer[15]);
24931 	} else if (un->un_f_cfg_readsub_bcd == TRUE) {
24932 		subchnl->cdsc_absaddr.msf.minute = BCD_TO_BYTE(buffer[9]);
24933 		subchnl->cdsc_absaddr.msf.second = BCD_TO_BYTE(buffer[10]);
24934 		subchnl->cdsc_absaddr.msf.frame  = BCD_TO_BYTE(buffer[11]);
24935 		subchnl->cdsc_reladdr.msf.minute = BCD_TO_BYTE(buffer[13]);
24936 		subchnl->cdsc_reladdr.msf.second = BCD_TO_BYTE(buffer[14]);
24937 		subchnl->cdsc_reladdr.msf.frame  = BCD_TO_BYTE(buffer[15]);
24938 	} else {
24939 		subchnl->cdsc_absaddr.msf.minute = buffer[9];
24940 		subchnl->cdsc_absaddr.msf.second = buffer[10];
24941 		subchnl->cdsc_absaddr.msf.frame  = buffer[11];
24942 		subchnl->cdsc_reladdr.msf.minute = buffer[13];
24943 		subchnl->cdsc_reladdr.msf.second = buffer[14];
24944 		subchnl->cdsc_reladdr.msf.frame  = buffer[15];
24945 	}
24946 	kmem_free(buffer, 16);
24947 	kmem_free(com, sizeof (*com));
24948 	if (ddi_copyout(subchnl, data, sizeof (struct cdrom_subchnl), flag)
24949 	    != 0) {
24950 		return (EFAULT);
24951 	}
24952 	return (rval);
24953 }
24954 
24955 
24956 /*
24957  *    Function: sr_read_tocentry()
24958  *
24959  * Description: This routine is the driver entry point for handling CD-ROM
24960  *		ioctl requests to read from the Table of Contents (TOC)
24961  *		(CDROMREADTOCENTRY). This routine provides the ADR and CTRL
24962  *		fields, the starting address (LBA or MSF format per the user)
24963  *		and the data mode if the user specified track is a data track.
24964  *
24965  *		Note: The READ HEADER (0x44) command used in this routine is
24966  *		obsolete per the SCSI MMC spec but still supported in the
24967  *		MT FUJI vendor spec. Most equipment is adhereing to MT FUJI
24968  *		therefore the command is still implemented in this routine.
24969  *
24970  *   Arguments: dev	- the device 'dev_t'
24971  *		data	- pointer to user provided toc entry structure,
24972  *			  specifying the track # and the address format
24973  *			  (LBA or MSF).
24974  *		flag	- this argument is a pass through to ddi_copyxxx()
24975  *		          directly from the mode argument of ioctl().
24976  *
24977  * Return Code: the code returned by sd_send_scsi_cmd()
24978  *		EFAULT if ddi_copyxxx() fails
24979  *		ENXIO if fail ddi_get_soft_state
24980  *		EINVAL if data pointer is NULL
24981  */
24982 
24983 static int
24984 sr_read_tocentry(dev_t dev, caddr_t data, int flag)
24985 {
24986 	struct sd_lun		*un = NULL;
24987 	struct uscsi_cmd	*com;
24988 	struct cdrom_tocentry	toc_entry;
24989 	struct cdrom_tocentry	*entry = &toc_entry;
24990 	caddr_t			buffer;
24991 	int			rval;
24992 	char			cdb[CDB_GROUP1];
24993 
24994 	if (data == NULL) {
24995 		return (EINVAL);
24996 	}
24997 
24998 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
24999 	    (un->un_state == SD_STATE_OFFLINE)) {
25000 		return (ENXIO);
25001 	}
25002 
25003 	if (ddi_copyin(data, entry, sizeof (struct cdrom_tocentry), flag)) {
25004 		return (EFAULT);
25005 	}
25006 
25007 	/* Validate the requested track and address format */
25008 	if (!(entry->cdte_format & (CDROM_LBA | CDROM_MSF))) {
25009 		return (EINVAL);
25010 	}
25011 
25012 	if (entry->cdte_track == 0) {
25013 		return (EINVAL);
25014 	}
25015 
25016 	buffer = kmem_zalloc((size_t)12, KM_SLEEP);
25017 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25018 	bzero(cdb, CDB_GROUP1);
25019 
25020 	cdb[0] = SCMD_READ_TOC;
25021 	/* Set the MSF bit based on the user requested address format  */
25022 	cdb[1] = ((entry->cdte_format & CDROM_LBA) ? 0 : 2);
25023 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
25024 		cdb[6] = BYTE_TO_BCD(entry->cdte_track);
25025 	} else {
25026 		cdb[6] = entry->cdte_track;
25027 	}
25028 
25029 	/*
25030 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
25031 	 * (4 byte TOC response header + 8 byte track descriptor)
25032 	 */
25033 	cdb[8] = 12;
25034 	com->uscsi_cdb	   = cdb;
25035 	com->uscsi_cdblen  = CDB_GROUP1;
25036 	com->uscsi_bufaddr = buffer;
25037 	com->uscsi_buflen  = 0x0C;
25038 	com->uscsi_flags   = (USCSI_DIAGNOSE | USCSI_SILENT | USCSI_READ);
25039 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25040 	    SD_PATH_STANDARD);
25041 	if (rval != 0) {
25042 		kmem_free(buffer, 12);
25043 		kmem_free(com, sizeof (*com));
25044 		return (rval);
25045 	}
25046 
25047 	/* Process the toc entry */
25048 	entry->cdte_adr		= (buffer[5] & 0xF0) >> 4;
25049 	entry->cdte_ctrl	= (buffer[5] & 0x0F);
25050 	if (entry->cdte_format & CDROM_LBA) {
25051 		entry->cdte_addr.lba =
25052 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
25053 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
25054 	} else if (un->un_f_cfg_read_toc_addr_bcd == TRUE) {
25055 		entry->cdte_addr.msf.minute	= BCD_TO_BYTE(buffer[9]);
25056 		entry->cdte_addr.msf.second	= BCD_TO_BYTE(buffer[10]);
25057 		entry->cdte_addr.msf.frame	= BCD_TO_BYTE(buffer[11]);
25058 		/*
25059 		 * Send a READ TOC command using the LBA address format to get
25060 		 * the LBA for the track requested so it can be used in the
25061 		 * READ HEADER request
25062 		 *
25063 		 * Note: The MSF bit of the READ HEADER command specifies the
25064 		 * output format. The block address specified in that command
25065 		 * must be in LBA format.
25066 		 */
25067 		cdb[1] = 0;
25068 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25069 		    SD_PATH_STANDARD);
25070 		if (rval != 0) {
25071 			kmem_free(buffer, 12);
25072 			kmem_free(com, sizeof (*com));
25073 			return (rval);
25074 		}
25075 	} else {
25076 		entry->cdte_addr.msf.minute	= buffer[9];
25077 		entry->cdte_addr.msf.second	= buffer[10];
25078 		entry->cdte_addr.msf.frame	= buffer[11];
25079 		/*
25080 		 * Send a READ TOC command using the LBA address format to get
25081 		 * the LBA for the track requested so it can be used in the
25082 		 * READ HEADER request
25083 		 *
25084 		 * Note: The MSF bit of the READ HEADER command specifies the
25085 		 * output format. The block address specified in that command
25086 		 * must be in LBA format.
25087 		 */
25088 		cdb[1] = 0;
25089 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25090 		    SD_PATH_STANDARD);
25091 		if (rval != 0) {
25092 			kmem_free(buffer, 12);
25093 			kmem_free(com, sizeof (*com));
25094 			return (rval);
25095 		}
25096 	}
25097 
25098 	/*
25099 	 * Build and send the READ HEADER command to determine the data mode of
25100 	 * the user specified track.
25101 	 */
25102 	if ((entry->cdte_ctrl & CDROM_DATA_TRACK) &&
25103 	    (entry->cdte_track != CDROM_LEADOUT)) {
25104 		bzero(cdb, CDB_GROUP1);
25105 		cdb[0] = SCMD_READ_HEADER;
25106 		cdb[2] = buffer[8];
25107 		cdb[3] = buffer[9];
25108 		cdb[4] = buffer[10];
25109 		cdb[5] = buffer[11];
25110 		cdb[8] = 0x08;
25111 		com->uscsi_buflen = 0x08;
25112 		rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25113 		    SD_PATH_STANDARD);
25114 		if (rval == 0) {
25115 			entry->cdte_datamode = buffer[0];
25116 		} else {
25117 			/*
25118 			 * READ HEADER command failed, since this is
25119 			 * obsoleted in one spec, its better to return
25120 			 * -1 for an invlid track so that we can still
25121 			 * receive the rest of the TOC data.
25122 			 */
25123 			entry->cdte_datamode = (uchar_t)-1;
25124 		}
25125 	} else {
25126 		entry->cdte_datamode = (uchar_t)-1;
25127 	}
25128 
25129 	kmem_free(buffer, 12);
25130 	kmem_free(com, sizeof (*com));
25131 	if (ddi_copyout(entry, data, sizeof (struct cdrom_tocentry), flag) != 0)
25132 		return (EFAULT);
25133 
25134 	return (rval);
25135 }
25136 
25137 
25138 /*
25139  *    Function: sr_read_tochdr()
25140  *
25141  * Description: This routine is the driver entry point for handling CD-ROM
25142  * 		ioctl requests to read the Table of Contents (TOC) header
25143  *		(CDROMREADTOHDR). The TOC header consists of the disk starting
25144  *		and ending track numbers
25145  *
25146  *   Arguments: dev	- the device 'dev_t'
25147  *		data	- pointer to user provided toc header structure,
25148  *			  specifying the starting and ending track numbers.
25149  *		flag	- this argument is a pass through to ddi_copyxxx()
25150  *			  directly from the mode argument of ioctl().
25151  *
25152  * Return Code: the code returned by sd_send_scsi_cmd()
25153  *		EFAULT if ddi_copyxxx() fails
25154  *		ENXIO if fail ddi_get_soft_state
25155  *		EINVAL if data pointer is NULL
25156  */
25157 
25158 static int
25159 sr_read_tochdr(dev_t dev, caddr_t data, int flag)
25160 {
25161 	struct sd_lun		*un;
25162 	struct uscsi_cmd	*com;
25163 	struct cdrom_tochdr	toc_header;
25164 	struct cdrom_tochdr	*hdr = &toc_header;
25165 	char			cdb[CDB_GROUP1];
25166 	int			rval;
25167 	caddr_t			buffer;
25168 
25169 	if (data == NULL) {
25170 		return (EINVAL);
25171 	}
25172 
25173 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25174 	    (un->un_state == SD_STATE_OFFLINE)) {
25175 		return (ENXIO);
25176 	}
25177 
25178 	buffer = kmem_zalloc(4, KM_SLEEP);
25179 	bzero(cdb, CDB_GROUP1);
25180 	cdb[0] = SCMD_READ_TOC;
25181 	/*
25182 	 * Specifying a track number of 0x00 in the READ TOC command indicates
25183 	 * that the TOC header should be returned
25184 	 */
25185 	cdb[6] = 0x00;
25186 	/*
25187 	 * Bytes 7 & 8 are the 4 byte allocation length for TOC header.
25188 	 * (2 byte data len + 1 byte starting track # + 1 byte ending track #)
25189 	 */
25190 	cdb[8] = 0x04;
25191 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25192 	com->uscsi_cdb	   = cdb;
25193 	com->uscsi_cdblen  = CDB_GROUP1;
25194 	com->uscsi_bufaddr = buffer;
25195 	com->uscsi_buflen  = 0x04;
25196 	com->uscsi_timeout = 300;
25197 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25198 
25199 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
25200 	    SD_PATH_STANDARD);
25201 	if (un->un_f_cfg_read_toc_trk_bcd == TRUE) {
25202 		hdr->cdth_trk0 = BCD_TO_BYTE(buffer[2]);
25203 		hdr->cdth_trk1 = BCD_TO_BYTE(buffer[3]);
25204 	} else {
25205 		hdr->cdth_trk0 = buffer[2];
25206 		hdr->cdth_trk1 = buffer[3];
25207 	}
25208 	kmem_free(buffer, 4);
25209 	kmem_free(com, sizeof (*com));
25210 	if (ddi_copyout(hdr, data, sizeof (struct cdrom_tochdr), flag) != 0) {
25211 		return (EFAULT);
25212 	}
25213 	return (rval);
25214 }
25215 
25216 
25217 /*
25218  * Note: The following sr_read_mode1(), sr_read_cd_mode2(), sr_read_mode2(),
25219  * sr_read_cdda(), sr_read_cdxa(), routines implement driver support for
25220  * handling CDROMREAD ioctl requests for mode 1 user data, mode 2 user data,
25221  * digital audio and extended architecture digital audio. These modes are
25222  * defined in the IEC908 (Red Book), ISO10149 (Yellow Book), and the SCSI3
25223  * MMC specs.
25224  *
25225  * In addition to support for the various data formats these routines also
25226  * include support for devices that implement only the direct access READ
25227  * commands (0x08, 0x28), devices that implement the READ_CD commands
25228  * (0xBE, 0xD4), and devices that implement the vendor unique READ CDDA and
25229  * READ CDXA commands (0xD8, 0xDB)
25230  */
25231 
25232 /*
25233  *    Function: sr_read_mode1()
25234  *
25235  * Description: This routine is the driver entry point for handling CD-ROM
25236  *		ioctl read mode1 requests (CDROMREADMODE1).
25237  *
25238  *   Arguments: dev	- the device 'dev_t'
25239  *		data	- pointer to user provided cd read structure specifying
25240  *			  the lba buffer address and length.
25241  *		flag	- this argument is a pass through to ddi_copyxxx()
25242  *			  directly from the mode argument of ioctl().
25243  *
25244  * Return Code: the code returned by sd_send_scsi_cmd()
25245  *		EFAULT if ddi_copyxxx() fails
25246  *		ENXIO if fail ddi_get_soft_state
25247  *		EINVAL if data pointer is NULL
25248  */
25249 
25250 static int
25251 sr_read_mode1(dev_t dev, caddr_t data, int flag)
25252 {
25253 	struct sd_lun		*un;
25254 	struct cdrom_read	mode1_struct;
25255 	struct cdrom_read	*mode1 = &mode1_struct;
25256 	int			rval;
25257 #ifdef _MULTI_DATAMODEL
25258 	/* To support ILP32 applications in an LP64 world */
25259 	struct cdrom_read32	cdrom_read32;
25260 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25261 #endif /* _MULTI_DATAMODEL */
25262 
25263 	if (data == NULL) {
25264 		return (EINVAL);
25265 	}
25266 
25267 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25268 	    (un->un_state == SD_STATE_OFFLINE)) {
25269 		return (ENXIO);
25270 	}
25271 
25272 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25273 	    "sd_read_mode1: entry: un:0x%p\n", un);
25274 
25275 #ifdef _MULTI_DATAMODEL
25276 	switch (ddi_model_convert_from(flag & FMODELS)) {
25277 	case DDI_MODEL_ILP32:
25278 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25279 			return (EFAULT);
25280 		}
25281 		/* Convert the ILP32 uscsi data from the application to LP64 */
25282 		cdrom_read32tocdrom_read(cdrd32, mode1);
25283 		break;
25284 	case DDI_MODEL_NONE:
25285 		if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
25286 			return (EFAULT);
25287 		}
25288 	}
25289 #else /* ! _MULTI_DATAMODEL */
25290 	if (ddi_copyin(data, mode1, sizeof (struct cdrom_read), flag)) {
25291 		return (EFAULT);
25292 	}
25293 #endif /* _MULTI_DATAMODEL */
25294 
25295 	rval = sd_send_scsi_READ(un, mode1->cdread_bufaddr,
25296 	    mode1->cdread_buflen, mode1->cdread_lba, SD_PATH_STANDARD);
25297 
25298 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25299 	    "sd_read_mode1: exit: un:0x%p\n", un);
25300 
25301 	return (rval);
25302 }
25303 
25304 
25305 /*
25306  *    Function: sr_read_cd_mode2()
25307  *
25308  * Description: This routine is the driver entry point for handling CD-ROM
25309  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
25310  *		support the READ CD (0xBE) command or the 1st generation
25311  *		READ CD (0xD4) command.
25312  *
25313  *   Arguments: dev	- the device 'dev_t'
25314  *		data	- pointer to user provided cd read structure specifying
25315  *			  the lba buffer address and length.
25316  *		flag	- this argument is a pass through to ddi_copyxxx()
25317  *			  directly from the mode argument of ioctl().
25318  *
25319  * Return Code: the code returned by sd_send_scsi_cmd()
25320  *		EFAULT if ddi_copyxxx() fails
25321  *		ENXIO if fail ddi_get_soft_state
25322  *		EINVAL if data pointer is NULL
25323  */
25324 
25325 static int
25326 sr_read_cd_mode2(dev_t dev, caddr_t data, int flag)
25327 {
25328 	struct sd_lun		*un;
25329 	struct uscsi_cmd	*com;
25330 	struct cdrom_read	mode2_struct;
25331 	struct cdrom_read	*mode2 = &mode2_struct;
25332 	uchar_t			cdb[CDB_GROUP5];
25333 	int			nblocks;
25334 	int			rval;
25335 #ifdef _MULTI_DATAMODEL
25336 	/*  To support ILP32 applications in an LP64 world */
25337 	struct cdrom_read32	cdrom_read32;
25338 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25339 #endif /* _MULTI_DATAMODEL */
25340 
25341 	if (data == NULL) {
25342 		return (EINVAL);
25343 	}
25344 
25345 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25346 	    (un->un_state == SD_STATE_OFFLINE)) {
25347 		return (ENXIO);
25348 	}
25349 
25350 #ifdef _MULTI_DATAMODEL
25351 	switch (ddi_model_convert_from(flag & FMODELS)) {
25352 	case DDI_MODEL_ILP32:
25353 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25354 			return (EFAULT);
25355 		}
25356 		/* Convert the ILP32 uscsi data from the application to LP64 */
25357 		cdrom_read32tocdrom_read(cdrd32, mode2);
25358 		break;
25359 	case DDI_MODEL_NONE:
25360 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25361 			return (EFAULT);
25362 		}
25363 		break;
25364 	}
25365 
25366 #else /* ! _MULTI_DATAMODEL */
25367 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25368 		return (EFAULT);
25369 	}
25370 #endif /* _MULTI_DATAMODEL */
25371 
25372 	bzero(cdb, sizeof (cdb));
25373 	if (un->un_f_cfg_read_cd_xd4 == TRUE) {
25374 		/* Read command supported by 1st generation atapi drives */
25375 		cdb[0] = SCMD_READ_CDD4;
25376 	} else {
25377 		/* Universal CD Access Command */
25378 		cdb[0] = SCMD_READ_CD;
25379 	}
25380 
25381 	/*
25382 	 * Set expected sector type to: 2336s byte, Mode 2 Yellow Book
25383 	 */
25384 	cdb[1] = CDROM_SECTOR_TYPE_MODE2;
25385 
25386 	/* set the start address */
25387 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 24) & 0XFF);
25388 	cdb[3] = (uchar_t)((mode2->cdread_lba >> 16) & 0XFF);
25389 	cdb[4] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
25390 	cdb[5] = (uchar_t)(mode2->cdread_lba & 0xFF);
25391 
25392 	/* set the transfer length */
25393 	nblocks = mode2->cdread_buflen / 2336;
25394 	cdb[6] = (uchar_t)(nblocks >> 16);
25395 	cdb[7] = (uchar_t)(nblocks >> 8);
25396 	cdb[8] = (uchar_t)nblocks;
25397 
25398 	/* set the filter bits */
25399 	cdb[9] = CDROM_READ_CD_USERDATA;
25400 
25401 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25402 	com->uscsi_cdb = (caddr_t)cdb;
25403 	com->uscsi_cdblen = sizeof (cdb);
25404 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
25405 	com->uscsi_buflen = mode2->cdread_buflen;
25406 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25407 
25408 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25409 	    SD_PATH_STANDARD);
25410 	kmem_free(com, sizeof (*com));
25411 	return (rval);
25412 }
25413 
25414 
25415 /*
25416  *    Function: sr_read_mode2()
25417  *
25418  * Description: This routine is the driver entry point for handling CD-ROM
25419  *		ioctl read mode2 requests (CDROMREADMODE2) for devices that
25420  *		do not support the READ CD (0xBE) command.
25421  *
25422  *   Arguments: dev	- the device 'dev_t'
25423  *		data	- pointer to user provided cd read structure specifying
25424  *			  the lba buffer address and length.
25425  *		flag	- this argument is a pass through to ddi_copyxxx()
25426  *			  directly from the mode argument of ioctl().
25427  *
25428  * Return Code: the code returned by sd_send_scsi_cmd()
25429  *		EFAULT if ddi_copyxxx() fails
25430  *		ENXIO if fail ddi_get_soft_state
25431  *		EINVAL if data pointer is NULL
25432  *		EIO if fail to reset block size
25433  *		EAGAIN if commands are in progress in the driver
25434  */
25435 
25436 static int
25437 sr_read_mode2(dev_t dev, caddr_t data, int flag)
25438 {
25439 	struct sd_lun		*un;
25440 	struct cdrom_read	mode2_struct;
25441 	struct cdrom_read	*mode2 = &mode2_struct;
25442 	int			rval;
25443 	uint32_t		restore_blksize;
25444 	struct uscsi_cmd	*com;
25445 	uchar_t			cdb[CDB_GROUP0];
25446 	int			nblocks;
25447 
25448 #ifdef _MULTI_DATAMODEL
25449 	/* To support ILP32 applications in an LP64 world */
25450 	struct cdrom_read32	cdrom_read32;
25451 	struct cdrom_read32	*cdrd32 = &cdrom_read32;
25452 #endif /* _MULTI_DATAMODEL */
25453 
25454 	if (data == NULL) {
25455 		return (EINVAL);
25456 	}
25457 
25458 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25459 	    (un->un_state == SD_STATE_OFFLINE)) {
25460 		return (ENXIO);
25461 	}
25462 
25463 	/*
25464 	 * Because this routine will update the device and driver block size
25465 	 * being used we want to make sure there are no commands in progress.
25466 	 * If commands are in progress the user will have to try again.
25467 	 *
25468 	 * We check for 1 instead of 0 because we increment un_ncmds_in_driver
25469 	 * in sdioctl to protect commands from sdioctl through to the top of
25470 	 * sd_uscsi_strategy. See sdioctl for details.
25471 	 */
25472 	mutex_enter(SD_MUTEX(un));
25473 	if (un->un_ncmds_in_driver != 1) {
25474 		mutex_exit(SD_MUTEX(un));
25475 		return (EAGAIN);
25476 	}
25477 	mutex_exit(SD_MUTEX(un));
25478 
25479 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25480 	    "sd_read_mode2: entry: un:0x%p\n", un);
25481 
25482 #ifdef _MULTI_DATAMODEL
25483 	switch (ddi_model_convert_from(flag & FMODELS)) {
25484 	case DDI_MODEL_ILP32:
25485 		if (ddi_copyin(data, cdrd32, sizeof (*cdrd32), flag) != 0) {
25486 			return (EFAULT);
25487 		}
25488 		/* Convert the ILP32 uscsi data from the application to LP64 */
25489 		cdrom_read32tocdrom_read(cdrd32, mode2);
25490 		break;
25491 	case DDI_MODEL_NONE:
25492 		if (ddi_copyin(data, mode2, sizeof (*mode2), flag) != 0) {
25493 			return (EFAULT);
25494 		}
25495 		break;
25496 	}
25497 #else /* ! _MULTI_DATAMODEL */
25498 	if (ddi_copyin(data, mode2, sizeof (*mode2), flag)) {
25499 		return (EFAULT);
25500 	}
25501 #endif /* _MULTI_DATAMODEL */
25502 
25503 	/* Store the current target block size for restoration later */
25504 	restore_blksize = un->un_tgt_blocksize;
25505 
25506 	/* Change the device and soft state target block size to 2336 */
25507 	if (sr_sector_mode(dev, SD_MODE2_BLKSIZE) != 0) {
25508 		rval = EIO;
25509 		goto done;
25510 	}
25511 
25512 
25513 	bzero(cdb, sizeof (cdb));
25514 
25515 	/* set READ operation */
25516 	cdb[0] = SCMD_READ;
25517 
25518 	/* adjust lba for 2kbyte blocks from 512 byte blocks */
25519 	mode2->cdread_lba >>= 2;
25520 
25521 	/* set the start address */
25522 	cdb[1] = (uchar_t)((mode2->cdread_lba >> 16) & 0X1F);
25523 	cdb[2] = (uchar_t)((mode2->cdread_lba >> 8) & 0xFF);
25524 	cdb[3] = (uchar_t)(mode2->cdread_lba & 0xFF);
25525 
25526 	/* set the transfer length */
25527 	nblocks = mode2->cdread_buflen / 2336;
25528 	cdb[4] = (uchar_t)nblocks & 0xFF;
25529 
25530 	/* build command */
25531 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25532 	com->uscsi_cdb = (caddr_t)cdb;
25533 	com->uscsi_cdblen = sizeof (cdb);
25534 	com->uscsi_bufaddr = mode2->cdread_bufaddr;
25535 	com->uscsi_buflen = mode2->cdread_buflen;
25536 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25537 
25538 	/*
25539 	 * Issue SCSI command with user space address for read buffer.
25540 	 *
25541 	 * This sends the command through main channel in the driver.
25542 	 *
25543 	 * Since this is accessed via an IOCTL call, we go through the
25544 	 * standard path, so that if the device was powered down, then
25545 	 * it would be 'awakened' to handle the command.
25546 	 */
25547 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25548 	    SD_PATH_STANDARD);
25549 
25550 	kmem_free(com, sizeof (*com));
25551 
25552 	/* Restore the device and soft state target block size */
25553 	if (sr_sector_mode(dev, restore_blksize) != 0) {
25554 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25555 		    "can't do switch back to mode 1\n");
25556 		/*
25557 		 * If sd_send_scsi_READ succeeded we still need to report
25558 		 * an error because we failed to reset the block size
25559 		 */
25560 		if (rval == 0) {
25561 			rval = EIO;
25562 		}
25563 	}
25564 
25565 done:
25566 	SD_TRACE(SD_LOG_ATTACH_DETACH, un,
25567 	    "sd_read_mode2: exit: un:0x%p\n", un);
25568 
25569 	return (rval);
25570 }
25571 
25572 
25573 /*
25574  *    Function: sr_sector_mode()
25575  *
25576  * Description: This utility function is used by sr_read_mode2 to set the target
25577  *		block size based on the user specified size. This is a legacy
25578  *		implementation based upon a vendor specific mode page
25579  *
25580  *   Arguments: dev	- the device 'dev_t'
25581  *		data	- flag indicating if block size is being set to 2336 or
25582  *			  512.
25583  *
25584  * Return Code: the code returned by sd_send_scsi_cmd()
25585  *		EFAULT if ddi_copyxxx() fails
25586  *		ENXIO if fail ddi_get_soft_state
25587  *		EINVAL if data pointer is NULL
25588  */
25589 
25590 static int
25591 sr_sector_mode(dev_t dev, uint32_t blksize)
25592 {
25593 	struct sd_lun	*un;
25594 	uchar_t		*sense;
25595 	uchar_t		*select;
25596 	int		rval;
25597 
25598 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25599 	    (un->un_state == SD_STATE_OFFLINE)) {
25600 		return (ENXIO);
25601 	}
25602 
25603 	sense = kmem_zalloc(20, KM_SLEEP);
25604 
25605 	/* Note: This is a vendor specific mode page (0x81) */
25606 	if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, 20, 0x81,
25607 	    SD_PATH_STANDARD)) != 0) {
25608 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25609 		    "sr_sector_mode: Mode Sense failed\n");
25610 		kmem_free(sense, 20);
25611 		return (rval);
25612 	}
25613 	select = kmem_zalloc(20, KM_SLEEP);
25614 	select[3] = 0x08;
25615 	select[10] = ((blksize >> 8) & 0xff);
25616 	select[11] = (blksize & 0xff);
25617 	select[12] = 0x01;
25618 	select[13] = 0x06;
25619 	select[14] = sense[14];
25620 	select[15] = sense[15];
25621 	if (blksize == SD_MODE2_BLKSIZE) {
25622 		select[14] |= 0x01;
25623 	}
25624 
25625 	if ((rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select, 20,
25626 	    SD_DONTSAVE_PAGE, SD_PATH_STANDARD)) != 0) {
25627 		SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
25628 		    "sr_sector_mode: Mode Select failed\n");
25629 	} else {
25630 		/*
25631 		 * Only update the softstate block size if we successfully
25632 		 * changed the device block mode.
25633 		 */
25634 		mutex_enter(SD_MUTEX(un));
25635 		sd_update_block_info(un, blksize, 0);
25636 		mutex_exit(SD_MUTEX(un));
25637 	}
25638 	kmem_free(sense, 20);
25639 	kmem_free(select, 20);
25640 	return (rval);
25641 }
25642 
25643 
25644 /*
25645  *    Function: sr_read_cdda()
25646  *
25647  * Description: This routine is the driver entry point for handling CD-ROM
25648  *		ioctl requests to return CD-DA or subcode data. (CDROMCDDA) If
25649  *		the target supports CDDA these requests are handled via a vendor
25650  *		specific command (0xD8) If the target does not support CDDA
25651  *		these requests are handled via the READ CD command (0xBE).
25652  *
25653  *   Arguments: dev	- the device 'dev_t'
25654  *		data	- pointer to user provided CD-DA structure specifying
25655  *			  the track starting address, transfer length, and
25656  *			  subcode options.
25657  *		flag	- this argument is a pass through to ddi_copyxxx()
25658  *			  directly from the mode argument of ioctl().
25659  *
25660  * Return Code: the code returned by sd_send_scsi_cmd()
25661  *		EFAULT if ddi_copyxxx() fails
25662  *		ENXIO if fail ddi_get_soft_state
25663  *		EINVAL if invalid arguments are provided
25664  *		ENOTTY
25665  */
25666 
25667 static int
25668 sr_read_cdda(dev_t dev, caddr_t data, int flag)
25669 {
25670 	struct sd_lun			*un;
25671 	struct uscsi_cmd		*com;
25672 	struct cdrom_cdda		*cdda;
25673 	int				rval;
25674 	size_t				buflen;
25675 	char				cdb[CDB_GROUP5];
25676 
25677 #ifdef _MULTI_DATAMODEL
25678 	/* To support ILP32 applications in an LP64 world */
25679 	struct cdrom_cdda32	cdrom_cdda32;
25680 	struct cdrom_cdda32	*cdda32 = &cdrom_cdda32;
25681 #endif /* _MULTI_DATAMODEL */
25682 
25683 	if (data == NULL) {
25684 		return (EINVAL);
25685 	}
25686 
25687 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25688 		return (ENXIO);
25689 	}
25690 
25691 	cdda = kmem_zalloc(sizeof (struct cdrom_cdda), KM_SLEEP);
25692 
25693 #ifdef _MULTI_DATAMODEL
25694 	switch (ddi_model_convert_from(flag & FMODELS)) {
25695 	case DDI_MODEL_ILP32:
25696 		if (ddi_copyin(data, cdda32, sizeof (*cdda32), flag)) {
25697 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25698 			    "sr_read_cdda: ddi_copyin Failed\n");
25699 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25700 			return (EFAULT);
25701 		}
25702 		/* Convert the ILP32 uscsi data from the application to LP64 */
25703 		cdrom_cdda32tocdrom_cdda(cdda32, cdda);
25704 		break;
25705 	case DDI_MODEL_NONE:
25706 		if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25707 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25708 			    "sr_read_cdda: ddi_copyin Failed\n");
25709 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25710 			return (EFAULT);
25711 		}
25712 		break;
25713 	}
25714 #else /* ! _MULTI_DATAMODEL */
25715 	if (ddi_copyin(data, cdda, sizeof (struct cdrom_cdda), flag)) {
25716 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25717 		    "sr_read_cdda: ddi_copyin Failed\n");
25718 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25719 		return (EFAULT);
25720 	}
25721 #endif /* _MULTI_DATAMODEL */
25722 
25723 	/*
25724 	 * Since MMC-2 expects max 3 bytes for length, check if the
25725 	 * length input is greater than 3 bytes
25726 	 */
25727 	if ((cdda->cdda_length & 0xFF000000) != 0) {
25728 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdda: "
25729 		    "cdrom transfer length too large: %d (limit %d)\n",
25730 		    cdda->cdda_length, 0xFFFFFF);
25731 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25732 		return (EINVAL);
25733 	}
25734 
25735 	switch (cdda->cdda_subcode) {
25736 	case CDROM_DA_NO_SUBCODE:
25737 		buflen = CDROM_BLK_2352 * cdda->cdda_length;
25738 		break;
25739 	case CDROM_DA_SUBQ:
25740 		buflen = CDROM_BLK_2368 * cdda->cdda_length;
25741 		break;
25742 	case CDROM_DA_ALL_SUBCODE:
25743 		buflen = CDROM_BLK_2448 * cdda->cdda_length;
25744 		break;
25745 	case CDROM_DA_SUBCODE_ONLY:
25746 		buflen = CDROM_BLK_SUBCODE * cdda->cdda_length;
25747 		break;
25748 	default:
25749 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25750 		    "sr_read_cdda: Subcode '0x%x' Not Supported\n",
25751 		    cdda->cdda_subcode);
25752 		kmem_free(cdda, sizeof (struct cdrom_cdda));
25753 		return (EINVAL);
25754 	}
25755 
25756 	/* Build and send the command */
25757 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25758 	bzero(cdb, CDB_GROUP5);
25759 
25760 	if (un->un_f_cfg_cdda == TRUE) {
25761 		cdb[0] = (char)SCMD_READ_CD;
25762 		cdb[1] = 0x04;
25763 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25764 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25765 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25766 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25767 		cdb[6] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25768 		cdb[7] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25769 		cdb[8] = ((cdda->cdda_length) & 0x000000ff);
25770 		cdb[9] = 0x10;
25771 		switch (cdda->cdda_subcode) {
25772 		case CDROM_DA_NO_SUBCODE :
25773 			cdb[10] = 0x0;
25774 			break;
25775 		case CDROM_DA_SUBQ :
25776 			cdb[10] = 0x2;
25777 			break;
25778 		case CDROM_DA_ALL_SUBCODE :
25779 			cdb[10] = 0x1;
25780 			break;
25781 		case CDROM_DA_SUBCODE_ONLY :
25782 			/* FALLTHROUGH */
25783 		default :
25784 			kmem_free(cdda, sizeof (struct cdrom_cdda));
25785 			kmem_free(com, sizeof (*com));
25786 			return (ENOTTY);
25787 		}
25788 	} else {
25789 		cdb[0] = (char)SCMD_READ_CDDA;
25790 		cdb[2] = (((cdda->cdda_addr) & 0xff000000) >> 24);
25791 		cdb[3] = (((cdda->cdda_addr) & 0x00ff0000) >> 16);
25792 		cdb[4] = (((cdda->cdda_addr) & 0x0000ff00) >> 8);
25793 		cdb[5] = ((cdda->cdda_addr) & 0x000000ff);
25794 		cdb[6] = (((cdda->cdda_length) & 0xff000000) >> 24);
25795 		cdb[7] = (((cdda->cdda_length) & 0x00ff0000) >> 16);
25796 		cdb[8] = (((cdda->cdda_length) & 0x0000ff00) >> 8);
25797 		cdb[9] = ((cdda->cdda_length) & 0x000000ff);
25798 		cdb[10] = cdda->cdda_subcode;
25799 	}
25800 
25801 	com->uscsi_cdb = cdb;
25802 	com->uscsi_cdblen = CDB_GROUP5;
25803 	com->uscsi_bufaddr = (caddr_t)cdda->cdda_data;
25804 	com->uscsi_buflen = buflen;
25805 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25806 
25807 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25808 	    SD_PATH_STANDARD);
25809 
25810 	kmem_free(cdda, sizeof (struct cdrom_cdda));
25811 	kmem_free(com, sizeof (*com));
25812 	return (rval);
25813 }
25814 
25815 
25816 /*
25817  *    Function: sr_read_cdxa()
25818  *
25819  * Description: This routine is the driver entry point for handling CD-ROM
25820  *		ioctl requests to return CD-XA (Extended Architecture) data.
25821  *		(CDROMCDXA).
25822  *
25823  *   Arguments: dev	- the device 'dev_t'
25824  *		data	- pointer to user provided CD-XA structure specifying
25825  *			  the data starting address, transfer length, and format
25826  *		flag	- this argument is a pass through to ddi_copyxxx()
25827  *			  directly from the mode argument of ioctl().
25828  *
25829  * Return Code: the code returned by sd_send_scsi_cmd()
25830  *		EFAULT if ddi_copyxxx() fails
25831  *		ENXIO if fail ddi_get_soft_state
25832  *		EINVAL if data pointer is NULL
25833  */
25834 
25835 static int
25836 sr_read_cdxa(dev_t dev, caddr_t data, int flag)
25837 {
25838 	struct sd_lun		*un;
25839 	struct uscsi_cmd	*com;
25840 	struct cdrom_cdxa	*cdxa;
25841 	int			rval;
25842 	size_t			buflen;
25843 	char			cdb[CDB_GROUP5];
25844 	uchar_t			read_flags;
25845 
25846 #ifdef _MULTI_DATAMODEL
25847 	/* To support ILP32 applications in an LP64 world */
25848 	struct cdrom_cdxa32		cdrom_cdxa32;
25849 	struct cdrom_cdxa32		*cdxa32 = &cdrom_cdxa32;
25850 #endif /* _MULTI_DATAMODEL */
25851 
25852 	if (data == NULL) {
25853 		return (EINVAL);
25854 	}
25855 
25856 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
25857 		return (ENXIO);
25858 	}
25859 
25860 	cdxa = kmem_zalloc(sizeof (struct cdrom_cdxa), KM_SLEEP);
25861 
25862 #ifdef _MULTI_DATAMODEL
25863 	switch (ddi_model_convert_from(flag & FMODELS)) {
25864 	case DDI_MODEL_ILP32:
25865 		if (ddi_copyin(data, cdxa32, sizeof (*cdxa32), flag)) {
25866 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25867 			return (EFAULT);
25868 		}
25869 		/*
25870 		 * Convert the ILP32 uscsi data from the
25871 		 * application to LP64 for internal use.
25872 		 */
25873 		cdrom_cdxa32tocdrom_cdxa(cdxa32, cdxa);
25874 		break;
25875 	case DDI_MODEL_NONE:
25876 		if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25877 			kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25878 			return (EFAULT);
25879 		}
25880 		break;
25881 	}
25882 #else /* ! _MULTI_DATAMODEL */
25883 	if (ddi_copyin(data, cdxa, sizeof (struct cdrom_cdxa), flag)) {
25884 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25885 		return (EFAULT);
25886 	}
25887 #endif /* _MULTI_DATAMODEL */
25888 
25889 	/*
25890 	 * Since MMC-2 expects max 3 bytes for length, check if the
25891 	 * length input is greater than 3 bytes
25892 	 */
25893 	if ((cdxa->cdxa_length & 0xFF000000) != 0) {
25894 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN, "sr_read_cdxa: "
25895 		    "cdrom transfer length too large: %d (limit %d)\n",
25896 		    cdxa->cdxa_length, 0xFFFFFF);
25897 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25898 		return (EINVAL);
25899 	}
25900 
25901 	switch (cdxa->cdxa_format) {
25902 	case CDROM_XA_DATA:
25903 		buflen = CDROM_BLK_2048 * cdxa->cdxa_length;
25904 		read_flags = 0x10;
25905 		break;
25906 	case CDROM_XA_SECTOR_DATA:
25907 		buflen = CDROM_BLK_2352 * cdxa->cdxa_length;
25908 		read_flags = 0xf8;
25909 		break;
25910 	case CDROM_XA_DATA_W_ERROR:
25911 		buflen = CDROM_BLK_2646 * cdxa->cdxa_length;
25912 		read_flags = 0xfc;
25913 		break;
25914 	default:
25915 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
25916 		    "sr_read_cdxa: Format '0x%x' Not Supported\n",
25917 		    cdxa->cdxa_format);
25918 		kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25919 		return (EINVAL);
25920 	}
25921 
25922 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
25923 	bzero(cdb, CDB_GROUP5);
25924 	if (un->un_f_mmc_cap == TRUE) {
25925 		cdb[0] = (char)SCMD_READ_CD;
25926 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25927 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25928 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25929 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25930 		cdb[6] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25931 		cdb[7] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25932 		cdb[8] = ((cdxa->cdxa_length) & 0x000000ff);
25933 		cdb[9] = (char)read_flags;
25934 	} else {
25935 		/*
25936 		 * Note: A vendor specific command (0xDB) is being used her to
25937 		 * request a read of all subcodes.
25938 		 */
25939 		cdb[0] = (char)SCMD_READ_CDXA;
25940 		cdb[2] = (((cdxa->cdxa_addr) & 0xff000000) >> 24);
25941 		cdb[3] = (((cdxa->cdxa_addr) & 0x00ff0000) >> 16);
25942 		cdb[4] = (((cdxa->cdxa_addr) & 0x0000ff00) >> 8);
25943 		cdb[5] = ((cdxa->cdxa_addr) & 0x000000ff);
25944 		cdb[6] = (((cdxa->cdxa_length) & 0xff000000) >> 24);
25945 		cdb[7] = (((cdxa->cdxa_length) & 0x00ff0000) >> 16);
25946 		cdb[8] = (((cdxa->cdxa_length) & 0x0000ff00) >> 8);
25947 		cdb[9] = ((cdxa->cdxa_length) & 0x000000ff);
25948 		cdb[10] = cdxa->cdxa_format;
25949 	}
25950 	com->uscsi_cdb	   = cdb;
25951 	com->uscsi_cdblen  = CDB_GROUP5;
25952 	com->uscsi_bufaddr = (caddr_t)cdxa->cdxa_data;
25953 	com->uscsi_buflen  = buflen;
25954 	com->uscsi_flags   = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
25955 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_USERSPACE,
25956 	    SD_PATH_STANDARD);
25957 	kmem_free(cdxa, sizeof (struct cdrom_cdxa));
25958 	kmem_free(com, sizeof (*com));
25959 	return (rval);
25960 }
25961 
25962 
25963 /*
25964  *    Function: sr_eject()
25965  *
25966  * Description: This routine is the driver entry point for handling CD-ROM
25967  *		eject ioctl requests (FDEJECT, DKIOCEJECT, CDROMEJECT)
25968  *
25969  *   Arguments: dev	- the device 'dev_t'
25970  *
25971  * Return Code: the code returned by sd_send_scsi_cmd()
25972  */
25973 
25974 static int
25975 sr_eject(dev_t dev)
25976 {
25977 	struct sd_lun	*un;
25978 	int		rval;
25979 
25980 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
25981 	    (un->un_state == SD_STATE_OFFLINE)) {
25982 		return (ENXIO);
25983 	}
25984 
25985 	/*
25986 	 * To prevent race conditions with the eject
25987 	 * command, keep track of an eject command as
25988 	 * it progresses. If we are already handling
25989 	 * an eject command in the driver for the given
25990 	 * unit and another request to eject is received
25991 	 * immediately return EAGAIN so we don't lose
25992 	 * the command if the current eject command fails.
25993 	 */
25994 	mutex_enter(SD_MUTEX(un));
25995 	if (un->un_f_ejecting == TRUE) {
25996 		mutex_exit(SD_MUTEX(un));
25997 		return (EAGAIN);
25998 	}
25999 	un->un_f_ejecting = TRUE;
26000 	mutex_exit(SD_MUTEX(un));
26001 
26002 	if ((rval = sd_send_scsi_DOORLOCK(un, SD_REMOVAL_ALLOW,
26003 	    SD_PATH_STANDARD)) != 0) {
26004 		mutex_enter(SD_MUTEX(un));
26005 		un->un_f_ejecting = FALSE;
26006 		mutex_exit(SD_MUTEX(un));
26007 		return (rval);
26008 	}
26009 
26010 	rval = sd_send_scsi_START_STOP_UNIT(un, SD_TARGET_EJECT,
26011 	    SD_PATH_STANDARD);
26012 
26013 	if (rval == 0) {
26014 		mutex_enter(SD_MUTEX(un));
26015 		sr_ejected(un);
26016 		un->un_mediastate = DKIO_EJECTED;
26017 		un->un_f_ejecting = FALSE;
26018 		cv_broadcast(&un->un_state_cv);
26019 		mutex_exit(SD_MUTEX(un));
26020 	} else {
26021 		mutex_enter(SD_MUTEX(un));
26022 		un->un_f_ejecting = FALSE;
26023 		mutex_exit(SD_MUTEX(un));
26024 	}
26025 	return (rval);
26026 }
26027 
26028 
26029 /*
26030  *    Function: sr_ejected()
26031  *
26032  * Description: This routine updates the soft state structure to invalidate the
26033  *		geometry information after the media has been ejected or a
26034  *		media eject has been detected.
26035  *
26036  *   Arguments: un - driver soft state (unit) structure
26037  */
26038 
26039 static void
26040 sr_ejected(struct sd_lun *un)
26041 {
26042 	struct sd_errstats *stp;
26043 
26044 	ASSERT(un != NULL);
26045 	ASSERT(mutex_owned(SD_MUTEX(un)));
26046 
26047 	un->un_f_blockcount_is_valid	= FALSE;
26048 	un->un_f_tgt_blocksize_is_valid	= FALSE;
26049 	mutex_exit(SD_MUTEX(un));
26050 	cmlb_invalidate(un->un_cmlbhandle, (void *)SD_PATH_DIRECT_PRIORITY);
26051 	mutex_enter(SD_MUTEX(un));
26052 
26053 	if (un->un_errstats != NULL) {
26054 		stp = (struct sd_errstats *)un->un_errstats->ks_data;
26055 		stp->sd_capacity.value.ui64 = 0;
26056 	}
26057 
26058 	/* remove "capacity-of-device" properties */
26059 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
26060 	    "device-nblocks");
26061 	(void) ddi_prop_remove(DDI_DEV_T_NONE, SD_DEVINFO(un),
26062 	    "device-blksize");
26063 }
26064 
26065 
26066 /*
26067  *    Function: sr_check_wp()
26068  *
26069  * Description: This routine checks the write protection of a removable
26070  *      media disk and hotpluggable devices via the write protect bit of
26071  *      the Mode Page Header device specific field. Some devices choke
26072  *      on unsupported mode page. In order to workaround this issue,
26073  *      this routine has been implemented to use 0x3f mode page(request
26074  *      for all pages) for all device types.
26075  *
26076  *   Arguments: dev		- the device 'dev_t'
26077  *
26078  * Return Code: int indicating if the device is write protected (1) or not (0)
26079  *
26080  *     Context: Kernel thread.
26081  *
26082  */
26083 
26084 static int
26085 sr_check_wp(dev_t dev)
26086 {
26087 	struct sd_lun	*un;
26088 	uchar_t		device_specific;
26089 	uchar_t		*sense;
26090 	int		hdrlen;
26091 	int		rval = FALSE;
26092 
26093 	/*
26094 	 * Note: The return codes for this routine should be reworked to
26095 	 * properly handle the case of a NULL softstate.
26096 	 */
26097 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL) {
26098 		return (FALSE);
26099 	}
26100 
26101 	if (un->un_f_cfg_is_atapi == TRUE) {
26102 		/*
26103 		 * The mode page contents are not required; set the allocation
26104 		 * length for the mode page header only
26105 		 */
26106 		hdrlen = MODE_HEADER_LENGTH_GRP2;
26107 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
26108 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense, hdrlen,
26109 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
26110 			goto err_exit;
26111 		device_specific =
26112 		    ((struct mode_header_grp2 *)sense)->device_specific;
26113 	} else {
26114 		hdrlen = MODE_HEADER_LENGTH;
26115 		sense = kmem_zalloc(hdrlen, KM_SLEEP);
26116 		if (sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense, hdrlen,
26117 		    MODEPAGE_ALLPAGES, SD_PATH_STANDARD) != 0)
26118 			goto err_exit;
26119 		device_specific =
26120 		    ((struct mode_header *)sense)->device_specific;
26121 	}
26122 
26123 	/*
26124 	 * Write protect mode sense failed; not all disks
26125 	 * understand this query. Return FALSE assuming that
26126 	 * these devices are not writable.
26127 	 */
26128 	if (device_specific & WRITE_PROTECT) {
26129 		rval = TRUE;
26130 	}
26131 
26132 err_exit:
26133 	kmem_free(sense, hdrlen);
26134 	return (rval);
26135 }
26136 
26137 /*
26138  *    Function: sr_volume_ctrl()
26139  *
26140  * Description: This routine is the driver entry point for handling CD-ROM
26141  *		audio output volume ioctl requests. (CDROMVOLCTRL)
26142  *
26143  *   Arguments: dev	- the device 'dev_t'
26144  *		data	- pointer to user audio volume control structure
26145  *		flag	- this argument is a pass through to ddi_copyxxx()
26146  *			  directly from the mode argument of ioctl().
26147  *
26148  * Return Code: the code returned by sd_send_scsi_cmd()
26149  *		EFAULT if ddi_copyxxx() fails
26150  *		ENXIO if fail ddi_get_soft_state
26151  *		EINVAL if data pointer is NULL
26152  *
26153  */
26154 
26155 static int
26156 sr_volume_ctrl(dev_t dev, caddr_t data, int flag)
26157 {
26158 	struct sd_lun		*un;
26159 	struct cdrom_volctrl    volume;
26160 	struct cdrom_volctrl    *vol = &volume;
26161 	uchar_t			*sense_page;
26162 	uchar_t			*select_page;
26163 	uchar_t			*sense;
26164 	uchar_t			*select;
26165 	int			sense_buflen;
26166 	int			select_buflen;
26167 	int			rval;
26168 
26169 	if (data == NULL) {
26170 		return (EINVAL);
26171 	}
26172 
26173 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26174 	    (un->un_state == SD_STATE_OFFLINE)) {
26175 		return (ENXIO);
26176 	}
26177 
26178 	if (ddi_copyin(data, vol, sizeof (struct cdrom_volctrl), flag)) {
26179 		return (EFAULT);
26180 	}
26181 
26182 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
26183 		struct mode_header_grp2		*sense_mhp;
26184 		struct mode_header_grp2		*select_mhp;
26185 		int				bd_len;
26186 
26187 		sense_buflen = MODE_PARAM_LENGTH_GRP2 + MODEPAGE_AUDIO_CTRL_LEN;
26188 		select_buflen = MODE_HEADER_LENGTH_GRP2 +
26189 		    MODEPAGE_AUDIO_CTRL_LEN;
26190 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
26191 		select = kmem_zalloc(select_buflen, KM_SLEEP);
26192 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP1, sense,
26193 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
26194 		    SD_PATH_STANDARD)) != 0) {
26195 			SD_ERROR(SD_LOG_IOCTL_RMMEDIA, un,
26196 			    "sr_volume_ctrl: Mode Sense Failed\n");
26197 			kmem_free(sense, sense_buflen);
26198 			kmem_free(select, select_buflen);
26199 			return (rval);
26200 		}
26201 		sense_mhp = (struct mode_header_grp2 *)sense;
26202 		select_mhp = (struct mode_header_grp2 *)select;
26203 		bd_len = (sense_mhp->bdesc_length_hi << 8) |
26204 		    sense_mhp->bdesc_length_lo;
26205 		if (bd_len > MODE_BLK_DESC_LENGTH) {
26206 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26207 			    "sr_volume_ctrl: Mode Sense returned invalid "
26208 			    "block descriptor length\n");
26209 			kmem_free(sense, sense_buflen);
26210 			kmem_free(select, select_buflen);
26211 			return (EIO);
26212 		}
26213 		sense_page = (uchar_t *)
26214 		    (sense + MODE_HEADER_LENGTH_GRP2 + bd_len);
26215 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH_GRP2);
26216 		select_mhp->length_msb = 0;
26217 		select_mhp->length_lsb = 0;
26218 		select_mhp->bdesc_length_hi = 0;
26219 		select_mhp->bdesc_length_lo = 0;
26220 	} else {
26221 		struct mode_header		*sense_mhp, *select_mhp;
26222 
26223 		sense_buflen = MODE_PARAM_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
26224 		select_buflen = MODE_HEADER_LENGTH + MODEPAGE_AUDIO_CTRL_LEN;
26225 		sense  = kmem_zalloc(sense_buflen, KM_SLEEP);
26226 		select = kmem_zalloc(select_buflen, KM_SLEEP);
26227 		if ((rval = sd_send_scsi_MODE_SENSE(un, CDB_GROUP0, sense,
26228 		    sense_buflen, MODEPAGE_AUDIO_CTRL,
26229 		    SD_PATH_STANDARD)) != 0) {
26230 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26231 			    "sr_volume_ctrl: Mode Sense Failed\n");
26232 			kmem_free(sense, sense_buflen);
26233 			kmem_free(select, select_buflen);
26234 			return (rval);
26235 		}
26236 		sense_mhp  = (struct mode_header *)sense;
26237 		select_mhp = (struct mode_header *)select;
26238 		if (sense_mhp->bdesc_length > MODE_BLK_DESC_LENGTH) {
26239 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26240 			    "sr_volume_ctrl: Mode Sense returned invalid "
26241 			    "block descriptor length\n");
26242 			kmem_free(sense, sense_buflen);
26243 			kmem_free(select, select_buflen);
26244 			return (EIO);
26245 		}
26246 		sense_page = (uchar_t *)
26247 		    (sense + MODE_HEADER_LENGTH + sense_mhp->bdesc_length);
26248 		select_page = (uchar_t *)(select + MODE_HEADER_LENGTH);
26249 		select_mhp->length = 0;
26250 		select_mhp->bdesc_length = 0;
26251 	}
26252 	/*
26253 	 * Note: An audio control data structure could be created and overlayed
26254 	 * on the following in place of the array indexing method implemented.
26255 	 */
26256 
26257 	/* Build the select data for the user volume data */
26258 	select_page[0] = MODEPAGE_AUDIO_CTRL;
26259 	select_page[1] = 0xE;
26260 	/* Set the immediate bit */
26261 	select_page[2] = 0x04;
26262 	/* Zero out reserved fields */
26263 	select_page[3] = 0x00;
26264 	select_page[4] = 0x00;
26265 	/* Return sense data for fields not to be modified */
26266 	select_page[5] = sense_page[5];
26267 	select_page[6] = sense_page[6];
26268 	select_page[7] = sense_page[7];
26269 	/* Set the user specified volume levels for channel 0 and 1 */
26270 	select_page[8] = 0x01;
26271 	select_page[9] = vol->channel0;
26272 	select_page[10] = 0x02;
26273 	select_page[11] = vol->channel1;
26274 	/* Channel 2 and 3 are currently unsupported so return the sense data */
26275 	select_page[12] = sense_page[12];
26276 	select_page[13] = sense_page[13];
26277 	select_page[14] = sense_page[14];
26278 	select_page[15] = sense_page[15];
26279 
26280 	if ((un->un_f_cfg_is_atapi == TRUE) || (un->un_f_mmc_cap == TRUE)) {
26281 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP1, select,
26282 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
26283 	} else {
26284 		rval = sd_send_scsi_MODE_SELECT(un, CDB_GROUP0, select,
26285 		    select_buflen, SD_DONTSAVE_PAGE, SD_PATH_STANDARD);
26286 	}
26287 
26288 	kmem_free(sense, sense_buflen);
26289 	kmem_free(select, select_buflen);
26290 	return (rval);
26291 }
26292 
26293 
26294 /*
26295  *    Function: sr_read_sony_session_offset()
26296  *
26297  * Description: This routine is the driver entry point for handling CD-ROM
26298  *		ioctl requests for session offset information. (CDROMREADOFFSET)
26299  *		The address of the first track in the last session of a
26300  *		multi-session CD-ROM is returned
26301  *
26302  *		Note: This routine uses a vendor specific key value in the
26303  *		command control field without implementing any vendor check here
26304  *		or in the ioctl routine.
26305  *
26306  *   Arguments: dev	- the device 'dev_t'
26307  *		data	- pointer to an int to hold the requested address
26308  *		flag	- this argument is a pass through to ddi_copyxxx()
26309  *			  directly from the mode argument of ioctl().
26310  *
26311  * Return Code: the code returned by sd_send_scsi_cmd()
26312  *		EFAULT if ddi_copyxxx() fails
26313  *		ENXIO if fail ddi_get_soft_state
26314  *		EINVAL if data pointer is NULL
26315  */
26316 
26317 static int
26318 sr_read_sony_session_offset(dev_t dev, caddr_t data, int flag)
26319 {
26320 	struct sd_lun		*un;
26321 	struct uscsi_cmd	*com;
26322 	caddr_t			buffer;
26323 	char			cdb[CDB_GROUP1];
26324 	int			session_offset = 0;
26325 	int			rval;
26326 
26327 	if (data == NULL) {
26328 		return (EINVAL);
26329 	}
26330 
26331 	if ((un = ddi_get_soft_state(sd_state, SDUNIT(dev))) == NULL ||
26332 	    (un->un_state == SD_STATE_OFFLINE)) {
26333 		return (ENXIO);
26334 	}
26335 
26336 	buffer = kmem_zalloc((size_t)SONY_SESSION_OFFSET_LEN, KM_SLEEP);
26337 	bzero(cdb, CDB_GROUP1);
26338 	cdb[0] = SCMD_READ_TOC;
26339 	/*
26340 	 * Bytes 7 & 8 are the 12 byte allocation length for a single entry.
26341 	 * (4 byte TOC response header + 8 byte response data)
26342 	 */
26343 	cdb[8] = SONY_SESSION_OFFSET_LEN;
26344 	/* Byte 9 is the control byte. A vendor specific value is used */
26345 	cdb[9] = SONY_SESSION_OFFSET_KEY;
26346 	com = kmem_zalloc(sizeof (*com), KM_SLEEP);
26347 	com->uscsi_cdb = cdb;
26348 	com->uscsi_cdblen = CDB_GROUP1;
26349 	com->uscsi_bufaddr = buffer;
26350 	com->uscsi_buflen = SONY_SESSION_OFFSET_LEN;
26351 	com->uscsi_flags = USCSI_DIAGNOSE|USCSI_SILENT|USCSI_READ;
26352 
26353 	rval = sd_send_scsi_cmd(dev, com, FKIOCTL, UIO_SYSSPACE,
26354 	    SD_PATH_STANDARD);
26355 	if (rval != 0) {
26356 		kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
26357 		kmem_free(com, sizeof (*com));
26358 		return (rval);
26359 	}
26360 	if (buffer[1] == SONY_SESSION_OFFSET_VALID) {
26361 		session_offset =
26362 		    ((uchar_t)buffer[8] << 24) + ((uchar_t)buffer[9] << 16) +
26363 		    ((uchar_t)buffer[10] << 8) + ((uchar_t)buffer[11]);
26364 		/*
26365 		 * Offset returned offset in current lbasize block's. Convert to
26366 		 * 2k block's to return to the user
26367 		 */
26368 		if (un->un_tgt_blocksize == CDROM_BLK_512) {
26369 			session_offset >>= 2;
26370 		} else if (un->un_tgt_blocksize == CDROM_BLK_1024) {
26371 			session_offset >>= 1;
26372 		}
26373 	}
26374 
26375 	if (ddi_copyout(&session_offset, data, sizeof (int), flag) != 0) {
26376 		rval = EFAULT;
26377 	}
26378 
26379 	kmem_free(buffer, SONY_SESSION_OFFSET_LEN);
26380 	kmem_free(com, sizeof (*com));
26381 	return (rval);
26382 }
26383 
26384 
26385 /*
26386  *    Function: sd_wm_cache_constructor()
26387  *
26388  * Description: Cache Constructor for the wmap cache for the read/modify/write
26389  * 		devices.
26390  *
26391  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
26392  *		un	- sd_lun structure for the device.
26393  *		flag	- the km flags passed to constructor
26394  *
26395  * Return Code: 0 on success.
26396  *		-1 on failure.
26397  */
26398 
26399 /*ARGSUSED*/
26400 static int
26401 sd_wm_cache_constructor(void *wm, void *un, int flags)
26402 {
26403 	bzero(wm, sizeof (struct sd_w_map));
26404 	cv_init(&((struct sd_w_map *)wm)->wm_avail, NULL, CV_DRIVER, NULL);
26405 	return (0);
26406 }
26407 
26408 
26409 /*
26410  *    Function: sd_wm_cache_destructor()
26411  *
26412  * Description: Cache destructor for the wmap cache for the read/modify/write
26413  * 		devices.
26414  *
26415  *   Arguments: wm      - A pointer to the sd_w_map to be initialized.
26416  *		un	- sd_lun structure for the device.
26417  */
26418 /*ARGSUSED*/
26419 static void
26420 sd_wm_cache_destructor(void *wm, void *un)
26421 {
26422 	cv_destroy(&((struct sd_w_map *)wm)->wm_avail);
26423 }
26424 
26425 
26426 /*
26427  *    Function: sd_range_lock()
26428  *
26429  * Description: Lock the range of blocks specified as parameter to ensure
26430  *		that read, modify write is atomic and no other i/o writes
26431  *		to the same location. The range is specified in terms
26432  *		of start and end blocks. Block numbers are the actual
26433  *		media block numbers and not system.
26434  *
26435  *   Arguments: un	- sd_lun structure for the device.
26436  *		startb - The starting block number
26437  *		endb - The end block number
26438  *		typ - type of i/o - simple/read_modify_write
26439  *
26440  * Return Code: wm  - pointer to the wmap structure.
26441  *
26442  *     Context: This routine can sleep.
26443  */
26444 
26445 static struct sd_w_map *
26446 sd_range_lock(struct sd_lun *un, daddr_t startb, daddr_t endb, ushort_t typ)
26447 {
26448 	struct sd_w_map *wmp = NULL;
26449 	struct sd_w_map *sl_wmp = NULL;
26450 	struct sd_w_map *tmp_wmp;
26451 	wm_state state = SD_WM_CHK_LIST;
26452 
26453 
26454 	ASSERT(un != NULL);
26455 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26456 
26457 	mutex_enter(SD_MUTEX(un));
26458 
26459 	while (state != SD_WM_DONE) {
26460 
26461 		switch (state) {
26462 		case SD_WM_CHK_LIST:
26463 			/*
26464 			 * This is the starting state. Check the wmap list
26465 			 * to see if the range is currently available.
26466 			 */
26467 			if (!(typ & SD_WTYPE_RMW) && !(un->un_rmw_count)) {
26468 				/*
26469 				 * If this is a simple write and no rmw
26470 				 * i/o is pending then try to lock the
26471 				 * range as the range should be available.
26472 				 */
26473 				state = SD_WM_LOCK_RANGE;
26474 			} else {
26475 				tmp_wmp = sd_get_range(un, startb, endb);
26476 				if (tmp_wmp != NULL) {
26477 					if ((wmp != NULL) && ONLIST(un, wmp)) {
26478 						/*
26479 						 * Should not keep onlist wmps
26480 						 * while waiting this macro
26481 						 * will also do wmp = NULL;
26482 						 */
26483 						FREE_ONLIST_WMAP(un, wmp);
26484 					}
26485 					/*
26486 					 * sl_wmp is the wmap on which wait
26487 					 * is done, since the tmp_wmp points
26488 					 * to the inuse wmap, set sl_wmp to
26489 					 * tmp_wmp and change the state to sleep
26490 					 */
26491 					sl_wmp = tmp_wmp;
26492 					state = SD_WM_WAIT_MAP;
26493 				} else {
26494 					state = SD_WM_LOCK_RANGE;
26495 				}
26496 
26497 			}
26498 			break;
26499 
26500 		case SD_WM_LOCK_RANGE:
26501 			ASSERT(un->un_wm_cache);
26502 			/*
26503 			 * The range need to be locked, try to get a wmap.
26504 			 * First attempt it with NO_SLEEP, want to avoid a sleep
26505 			 * if possible as we will have to release the sd mutex
26506 			 * if we have to sleep.
26507 			 */
26508 			if (wmp == NULL)
26509 				wmp = kmem_cache_alloc(un->un_wm_cache,
26510 				    KM_NOSLEEP);
26511 			if (wmp == NULL) {
26512 				mutex_exit(SD_MUTEX(un));
26513 				_NOTE(DATA_READABLE_WITHOUT_LOCK
26514 				    (sd_lun::un_wm_cache))
26515 				wmp = kmem_cache_alloc(un->un_wm_cache,
26516 				    KM_SLEEP);
26517 				mutex_enter(SD_MUTEX(un));
26518 				/*
26519 				 * we released the mutex so recheck and go to
26520 				 * check list state.
26521 				 */
26522 				state = SD_WM_CHK_LIST;
26523 			} else {
26524 				/*
26525 				 * We exit out of state machine since we
26526 				 * have the wmap. Do the housekeeping first.
26527 				 * place the wmap on the wmap list if it is not
26528 				 * on it already and then set the state to done.
26529 				 */
26530 				wmp->wm_start = startb;
26531 				wmp->wm_end = endb;
26532 				wmp->wm_flags = typ | SD_WM_BUSY;
26533 				if (typ & SD_WTYPE_RMW) {
26534 					un->un_rmw_count++;
26535 				}
26536 				/*
26537 				 * If not already on the list then link
26538 				 */
26539 				if (!ONLIST(un, wmp)) {
26540 					wmp->wm_next = un->un_wm;
26541 					wmp->wm_prev = NULL;
26542 					if (wmp->wm_next)
26543 						wmp->wm_next->wm_prev = wmp;
26544 					un->un_wm = wmp;
26545 				}
26546 				state = SD_WM_DONE;
26547 			}
26548 			break;
26549 
26550 		case SD_WM_WAIT_MAP:
26551 			ASSERT(sl_wmp->wm_flags & SD_WM_BUSY);
26552 			/*
26553 			 * Wait is done on sl_wmp, which is set in the
26554 			 * check_list state.
26555 			 */
26556 			sl_wmp->wm_wanted_count++;
26557 			cv_wait(&sl_wmp->wm_avail, SD_MUTEX(un));
26558 			sl_wmp->wm_wanted_count--;
26559 			/*
26560 			 * We can reuse the memory from the completed sl_wmp
26561 			 * lock range for our new lock, but only if noone is
26562 			 * waiting for it.
26563 			 */
26564 			ASSERT(!(sl_wmp->wm_flags & SD_WM_BUSY));
26565 			if (sl_wmp->wm_wanted_count == 0) {
26566 				if (wmp != NULL)
26567 					CHK_N_FREEWMP(un, wmp);
26568 				wmp = sl_wmp;
26569 			}
26570 			sl_wmp = NULL;
26571 			/*
26572 			 * After waking up, need to recheck for availability of
26573 			 * range.
26574 			 */
26575 			state = SD_WM_CHK_LIST;
26576 			break;
26577 
26578 		default:
26579 			panic("sd_range_lock: "
26580 			    "Unknown state %d in sd_range_lock", state);
26581 			/*NOTREACHED*/
26582 		} /* switch(state) */
26583 
26584 	} /* while(state != SD_WM_DONE) */
26585 
26586 	mutex_exit(SD_MUTEX(un));
26587 
26588 	ASSERT(wmp != NULL);
26589 
26590 	return (wmp);
26591 }
26592 
26593 
26594 /*
26595  *    Function: sd_get_range()
26596  *
26597  * Description: Find if there any overlapping I/O to this one
26598  *		Returns the write-map of 1st such I/O, NULL otherwise.
26599  *
26600  *   Arguments: un	- sd_lun structure for the device.
26601  *		startb - The starting block number
26602  *		endb - The end block number
26603  *
26604  * Return Code: wm  - pointer to the wmap structure.
26605  */
26606 
26607 static struct sd_w_map *
26608 sd_get_range(struct sd_lun *un, daddr_t startb, daddr_t endb)
26609 {
26610 	struct sd_w_map *wmp;
26611 
26612 	ASSERT(un != NULL);
26613 
26614 	for (wmp = un->un_wm; wmp != NULL; wmp = wmp->wm_next) {
26615 		if (!(wmp->wm_flags & SD_WM_BUSY)) {
26616 			continue;
26617 		}
26618 		if ((startb >= wmp->wm_start) && (startb <= wmp->wm_end)) {
26619 			break;
26620 		}
26621 		if ((endb >= wmp->wm_start) && (endb <= wmp->wm_end)) {
26622 			break;
26623 		}
26624 	}
26625 
26626 	return (wmp);
26627 }
26628 
26629 
26630 /*
26631  *    Function: sd_free_inlist_wmap()
26632  *
26633  * Description: Unlink and free a write map struct.
26634  *
26635  *   Arguments: un      - sd_lun structure for the device.
26636  *		wmp	- sd_w_map which needs to be unlinked.
26637  */
26638 
26639 static void
26640 sd_free_inlist_wmap(struct sd_lun *un, struct sd_w_map *wmp)
26641 {
26642 	ASSERT(un != NULL);
26643 
26644 	if (un->un_wm == wmp) {
26645 		un->un_wm = wmp->wm_next;
26646 	} else {
26647 		wmp->wm_prev->wm_next = wmp->wm_next;
26648 	}
26649 
26650 	if (wmp->wm_next) {
26651 		wmp->wm_next->wm_prev = wmp->wm_prev;
26652 	}
26653 
26654 	wmp->wm_next = wmp->wm_prev = NULL;
26655 
26656 	kmem_cache_free(un->un_wm_cache, wmp);
26657 }
26658 
26659 
26660 /*
26661  *    Function: sd_range_unlock()
26662  *
26663  * Description: Unlock the range locked by wm.
26664  *		Free write map if nobody else is waiting on it.
26665  *
26666  *   Arguments: un      - sd_lun structure for the device.
26667  *              wmp     - sd_w_map which needs to be unlinked.
26668  */
26669 
26670 static void
26671 sd_range_unlock(struct sd_lun *un, struct sd_w_map *wm)
26672 {
26673 	ASSERT(un != NULL);
26674 	ASSERT(wm != NULL);
26675 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26676 
26677 	mutex_enter(SD_MUTEX(un));
26678 
26679 	if (wm->wm_flags & SD_WTYPE_RMW) {
26680 		un->un_rmw_count--;
26681 	}
26682 
26683 	if (wm->wm_wanted_count) {
26684 		wm->wm_flags = 0;
26685 		/*
26686 		 * Broadcast that the wmap is available now.
26687 		 */
26688 		cv_broadcast(&wm->wm_avail);
26689 	} else {
26690 		/*
26691 		 * If no one is waiting on the map, it should be free'ed.
26692 		 */
26693 		sd_free_inlist_wmap(un, wm);
26694 	}
26695 
26696 	mutex_exit(SD_MUTEX(un));
26697 }
26698 
26699 
26700 /*
26701  *    Function: sd_read_modify_write_task
26702  *
26703  * Description: Called from a taskq thread to initiate the write phase of
26704  *		a read-modify-write request.  This is used for targets where
26705  *		un->un_sys_blocksize != un->un_tgt_blocksize.
26706  *
26707  *   Arguments: arg - a pointer to the buf(9S) struct for the write command.
26708  *
26709  *     Context: Called under taskq thread context.
26710  */
26711 
26712 static void
26713 sd_read_modify_write_task(void *arg)
26714 {
26715 	struct sd_mapblocksize_info	*bsp;
26716 	struct buf	*bp;
26717 	struct sd_xbuf	*xp;
26718 	struct sd_lun	*un;
26719 
26720 	bp = arg;	/* The bp is given in arg */
26721 	ASSERT(bp != NULL);
26722 
26723 	/* Get the pointer to the layer-private data struct */
26724 	xp = SD_GET_XBUF(bp);
26725 	ASSERT(xp != NULL);
26726 	bsp = xp->xb_private;
26727 	ASSERT(bsp != NULL);
26728 
26729 	un = SD_GET_UN(bp);
26730 	ASSERT(un != NULL);
26731 	ASSERT(!mutex_owned(SD_MUTEX(un)));
26732 
26733 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26734 	    "sd_read_modify_write_task: entry: buf:0x%p\n", bp);
26735 
26736 	/*
26737 	 * This is the write phase of a read-modify-write request, called
26738 	 * under the context of a taskq thread in response to the completion
26739 	 * of the read portion of the rmw request completing under interrupt
26740 	 * context. The write request must be sent from here down the iostart
26741 	 * chain as if it were being sent from sd_mapblocksize_iostart(), so
26742 	 * we use the layer index saved in the layer-private data area.
26743 	 */
26744 	SD_NEXT_IOSTART(bsp->mbs_layer_index, un, bp);
26745 
26746 	SD_TRACE(SD_LOG_IO_RMMEDIA, un,
26747 	    "sd_read_modify_write_task: exit: buf:0x%p\n", bp);
26748 }
26749 
26750 
26751 /*
26752  *    Function: sddump_do_read_of_rmw()
26753  *
26754  * Description: This routine will be called from sddump, If sddump is called
26755  *		with an I/O which not aligned on device blocksize boundary
26756  *		then the write has to be converted to read-modify-write.
26757  *		Do the read part here in order to keep sddump simple.
26758  *		Note - That the sd_mutex is held across the call to this
26759  *		routine.
26760  *
26761  *   Arguments: un	- sd_lun
26762  *		blkno	- block number in terms of media block size.
26763  *		nblk	- number of blocks.
26764  *		bpp	- pointer to pointer to the buf structure. On return
26765  *			from this function, *bpp points to the valid buffer
26766  *			to which the write has to be done.
26767  *
26768  * Return Code: 0 for success or errno-type return code
26769  */
26770 
26771 static int
26772 sddump_do_read_of_rmw(struct sd_lun *un, uint64_t blkno, uint64_t nblk,
26773 	struct buf **bpp)
26774 {
26775 	int err;
26776 	int i;
26777 	int rval;
26778 	struct buf *bp;
26779 	struct scsi_pkt *pkt = NULL;
26780 	uint32_t target_blocksize;
26781 
26782 	ASSERT(un != NULL);
26783 	ASSERT(mutex_owned(SD_MUTEX(un)));
26784 
26785 	target_blocksize = un->un_tgt_blocksize;
26786 
26787 	mutex_exit(SD_MUTEX(un));
26788 
26789 	bp = scsi_alloc_consistent_buf(SD_ADDRESS(un), (struct buf *)NULL,
26790 	    (size_t)(nblk * target_blocksize), B_READ, NULL_FUNC, NULL);
26791 	if (bp == NULL) {
26792 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26793 		    "no resources for dumping; giving up");
26794 		err = ENOMEM;
26795 		goto done;
26796 	}
26797 
26798 	rval = sd_setup_rw_pkt(un, &pkt, bp, 0, NULL_FUNC, NULL,
26799 	    blkno, nblk);
26800 	if (rval != 0) {
26801 		scsi_free_consistent_buf(bp);
26802 		scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26803 		    "no resources for dumping; giving up");
26804 		err = ENOMEM;
26805 		goto done;
26806 	}
26807 
26808 	pkt->pkt_flags |= FLAG_NOINTR;
26809 
26810 	err = EIO;
26811 	for (i = 0; i < SD_NDUMP_RETRIES; i++) {
26812 
26813 		/*
26814 		 * Scsi_poll returns 0 (success) if the command completes and
26815 		 * the status block is STATUS_GOOD.  We should only check
26816 		 * errors if this condition is not true.  Even then we should
26817 		 * send our own request sense packet only if we have a check
26818 		 * condition and auto request sense has not been performed by
26819 		 * the hba.
26820 		 */
26821 		SD_TRACE(SD_LOG_DUMP, un, "sddump: sending read\n");
26822 
26823 		if ((sd_scsi_poll(un, pkt) == 0) && (pkt->pkt_resid == 0)) {
26824 			err = 0;
26825 			break;
26826 		}
26827 
26828 		/*
26829 		 * Check CMD_DEV_GONE 1st, give up if device is gone,
26830 		 * no need to read RQS data.
26831 		 */
26832 		if (pkt->pkt_reason == CMD_DEV_GONE) {
26833 			scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
26834 			    "Error while dumping state with rmw..."
26835 			    "Device is gone\n");
26836 			break;
26837 		}
26838 
26839 		if (SD_GET_PKT_STATUS(pkt) == STATUS_CHECK) {
26840 			SD_INFO(SD_LOG_DUMP, un,
26841 			    "sddump: read failed with CHECK, try # %d\n", i);
26842 			if (((pkt->pkt_state & STATE_ARQ_DONE) == 0)) {
26843 				(void) sd_send_polled_RQS(un);
26844 			}
26845 
26846 			continue;
26847 		}
26848 
26849 		if (SD_GET_PKT_STATUS(pkt) == STATUS_BUSY) {
26850 			int reset_retval = 0;
26851 
26852 			SD_INFO(SD_LOG_DUMP, un,
26853 			    "sddump: read failed with BUSY, try # %d\n", i);
26854 
26855 			if (un->un_f_lun_reset_enabled == TRUE) {
26856 				reset_retval = scsi_reset(SD_ADDRESS(un),
26857 				    RESET_LUN);
26858 			}
26859 			if (reset_retval == 0) {
26860 				(void) scsi_reset(SD_ADDRESS(un), RESET_TARGET);
26861 			}
26862 			(void) sd_send_polled_RQS(un);
26863 
26864 		} else {
26865 			SD_INFO(SD_LOG_DUMP, un,
26866 			    "sddump: read failed with 0x%x, try # %d\n",
26867 			    SD_GET_PKT_STATUS(pkt), i);
26868 			mutex_enter(SD_MUTEX(un));
26869 			sd_reset_target(un, pkt);
26870 			mutex_exit(SD_MUTEX(un));
26871 		}
26872 
26873 		/*
26874 		 * If we are not getting anywhere with lun/target resets,
26875 		 * let's reset the bus.
26876 		 */
26877 		if (i > SD_NDUMP_RETRIES/2) {
26878 			(void) scsi_reset(SD_ADDRESS(un), RESET_ALL);
26879 			(void) sd_send_polled_RQS(un);
26880 		}
26881 
26882 	}
26883 	scsi_destroy_pkt(pkt);
26884 
26885 	if (err != 0) {
26886 		scsi_free_consistent_buf(bp);
26887 		*bpp = NULL;
26888 	} else {
26889 		*bpp = bp;
26890 	}
26891 
26892 done:
26893 	mutex_enter(SD_MUTEX(un));
26894 	return (err);
26895 }
26896 
26897 
26898 /*
26899  *    Function: sd_failfast_flushq
26900  *
26901  * Description: Take all bp's on the wait queue that have B_FAILFAST set
26902  *		in b_flags and move them onto the failfast queue, then kick
26903  *		off a thread to return all bp's on the failfast queue to
26904  *		their owners with an error set.
26905  *
26906  *   Arguments: un - pointer to the soft state struct for the instance.
26907  *
26908  *     Context: may execute in interrupt context.
26909  */
26910 
26911 static void
26912 sd_failfast_flushq(struct sd_lun *un)
26913 {
26914 	struct buf *bp;
26915 	struct buf *next_waitq_bp;
26916 	struct buf *prev_waitq_bp = NULL;
26917 
26918 	ASSERT(un != NULL);
26919 	ASSERT(mutex_owned(SD_MUTEX(un)));
26920 	ASSERT(un->un_failfast_state == SD_FAILFAST_ACTIVE);
26921 	ASSERT(un->un_failfast_bp == NULL);
26922 
26923 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
26924 	    "sd_failfast_flushq: entry: un:0x%p\n", un);
26925 
26926 	/*
26927 	 * Check if we should flush all bufs when entering failfast state, or
26928 	 * just those with B_FAILFAST set.
26929 	 */
26930 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) {
26931 		/*
26932 		 * Move *all* bp's on the wait queue to the failfast flush
26933 		 * queue, including those that do NOT have B_FAILFAST set.
26934 		 */
26935 		if (un->un_failfast_headp == NULL) {
26936 			ASSERT(un->un_failfast_tailp == NULL);
26937 			un->un_failfast_headp = un->un_waitq_headp;
26938 		} else {
26939 			ASSERT(un->un_failfast_tailp != NULL);
26940 			un->un_failfast_tailp->av_forw = un->un_waitq_headp;
26941 		}
26942 
26943 		un->un_failfast_tailp = un->un_waitq_tailp;
26944 
26945 		/* update kstat for each bp moved out of the waitq */
26946 		for (bp = un->un_waitq_headp; bp != NULL; bp = bp->av_forw) {
26947 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
26948 		}
26949 
26950 		/* empty the waitq */
26951 		un->un_waitq_headp = un->un_waitq_tailp = NULL;
26952 
26953 	} else {
26954 		/*
26955 		 * Go thru the wait queue, pick off all entries with
26956 		 * B_FAILFAST set, and move these onto the failfast queue.
26957 		 */
26958 		for (bp = un->un_waitq_headp; bp != NULL; bp = next_waitq_bp) {
26959 			/*
26960 			 * Save the pointer to the next bp on the wait queue,
26961 			 * so we get to it on the next iteration of this loop.
26962 			 */
26963 			next_waitq_bp = bp->av_forw;
26964 
26965 			/*
26966 			 * If this bp from the wait queue does NOT have
26967 			 * B_FAILFAST set, just move on to the next element
26968 			 * in the wait queue. Note, this is the only place
26969 			 * where it is correct to set prev_waitq_bp.
26970 			 */
26971 			if ((bp->b_flags & B_FAILFAST) == 0) {
26972 				prev_waitq_bp = bp;
26973 				continue;
26974 			}
26975 
26976 			/*
26977 			 * Remove the bp from the wait queue.
26978 			 */
26979 			if (bp == un->un_waitq_headp) {
26980 				/* The bp is the first element of the waitq. */
26981 				un->un_waitq_headp = next_waitq_bp;
26982 				if (un->un_waitq_headp == NULL) {
26983 					/* The wait queue is now empty */
26984 					un->un_waitq_tailp = NULL;
26985 				}
26986 			} else {
26987 				/*
26988 				 * The bp is either somewhere in the middle
26989 				 * or at the end of the wait queue.
26990 				 */
26991 				ASSERT(un->un_waitq_headp != NULL);
26992 				ASSERT(prev_waitq_bp != NULL);
26993 				ASSERT((prev_waitq_bp->b_flags & B_FAILFAST)
26994 				    == 0);
26995 				if (bp == un->un_waitq_tailp) {
26996 					/* bp is the last entry on the waitq. */
26997 					ASSERT(next_waitq_bp == NULL);
26998 					un->un_waitq_tailp = prev_waitq_bp;
26999 				}
27000 				prev_waitq_bp->av_forw = next_waitq_bp;
27001 			}
27002 			bp->av_forw = NULL;
27003 
27004 			/*
27005 			 * update kstat since the bp is moved out of
27006 			 * the waitq
27007 			 */
27008 			SD_UPDATE_KSTATS(un, kstat_waitq_exit, bp);
27009 
27010 			/*
27011 			 * Now put the bp onto the failfast queue.
27012 			 */
27013 			if (un->un_failfast_headp == NULL) {
27014 				/* failfast queue is currently empty */
27015 				ASSERT(un->un_failfast_tailp == NULL);
27016 				un->un_failfast_headp =
27017 				    un->un_failfast_tailp = bp;
27018 			} else {
27019 				/* Add the bp to the end of the failfast q */
27020 				ASSERT(un->un_failfast_tailp != NULL);
27021 				ASSERT(un->un_failfast_tailp->b_flags &
27022 				    B_FAILFAST);
27023 				un->un_failfast_tailp->av_forw = bp;
27024 				un->un_failfast_tailp = bp;
27025 			}
27026 		}
27027 	}
27028 
27029 	/*
27030 	 * Now return all bp's on the failfast queue to their owners.
27031 	 */
27032 	while ((bp = un->un_failfast_headp) != NULL) {
27033 
27034 		un->un_failfast_headp = bp->av_forw;
27035 		if (un->un_failfast_headp == NULL) {
27036 			un->un_failfast_tailp = NULL;
27037 		}
27038 
27039 		/*
27040 		 * We want to return the bp with a failure error code, but
27041 		 * we do not want a call to sd_start_cmds() to occur here,
27042 		 * so use sd_return_failed_command_no_restart() instead of
27043 		 * sd_return_failed_command().
27044 		 */
27045 		sd_return_failed_command_no_restart(un, bp, EIO);
27046 	}
27047 
27048 	/* Flush the xbuf queues if required. */
27049 	if (sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_QUEUES) {
27050 		ddi_xbuf_flushq(un->un_xbuf_attr, sd_failfast_flushq_callback);
27051 	}
27052 
27053 	SD_TRACE(SD_LOG_IO_FAILFAST, un,
27054 	    "sd_failfast_flushq: exit: un:0x%p\n", un);
27055 }
27056 
27057 
27058 /*
27059  *    Function: sd_failfast_flushq_callback
27060  *
27061  * Description: Return TRUE if the given bp meets the criteria for failfast
27062  *		flushing. Used with ddi_xbuf_flushq(9F).
27063  *
27064  *   Arguments: bp - ptr to buf struct to be examined.
27065  *
27066  *     Context: Any
27067  */
27068 
27069 static int
27070 sd_failfast_flushq_callback(struct buf *bp)
27071 {
27072 	/*
27073 	 * Return TRUE if (1) we want to flush ALL bufs when the failfast
27074 	 * state is entered; OR (2) the given bp has B_FAILFAST set.
27075 	 */
27076 	return (((sd_failfast_flushctl & SD_FAILFAST_FLUSH_ALL_BUFS) ||
27077 	    (bp->b_flags & B_FAILFAST)) ? TRUE : FALSE);
27078 }
27079 
27080 
27081 
27082 /*
27083  * Function: sd_setup_next_xfer
27084  *
27085  * Description: Prepare next I/O operation using DMA_PARTIAL
27086  *
27087  */
27088 
27089 static int
27090 sd_setup_next_xfer(struct sd_lun *un, struct buf *bp,
27091     struct scsi_pkt *pkt, struct sd_xbuf *xp)
27092 {
27093 	ssize_t	num_blks_not_xfered;
27094 	daddr_t	strt_blk_num;
27095 	ssize_t	bytes_not_xfered;
27096 	int	rval;
27097 
27098 	ASSERT(pkt->pkt_resid == 0);
27099 
27100 	/*
27101 	 * Calculate next block number and amount to be transferred.
27102 	 *
27103 	 * How much data NOT transfered to the HBA yet.
27104 	 */
27105 	bytes_not_xfered = xp->xb_dma_resid;
27106 
27107 	/*
27108 	 * figure how many blocks NOT transfered to the HBA yet.
27109 	 */
27110 	num_blks_not_xfered = SD_BYTES2TGTBLOCKS(un, bytes_not_xfered);
27111 
27112 	/*
27113 	 * set starting block number to the end of what WAS transfered.
27114 	 */
27115 	strt_blk_num = xp->xb_blkno +
27116 	    SD_BYTES2TGTBLOCKS(un, bp->b_bcount - bytes_not_xfered);
27117 
27118 	/*
27119 	 * Move pkt to the next portion of the xfer.  sd_setup_next_rw_pkt
27120 	 * will call scsi_initpkt with NULL_FUNC so we do not have to release
27121 	 * the disk mutex here.
27122 	 */
27123 	rval = sd_setup_next_rw_pkt(un, pkt, bp,
27124 	    strt_blk_num, num_blks_not_xfered);
27125 
27126 	if (rval == 0) {
27127 
27128 		/*
27129 		 * Success.
27130 		 *
27131 		 * Adjust things if there are still more blocks to be
27132 		 * transfered.
27133 		 */
27134 		xp->xb_dma_resid = pkt->pkt_resid;
27135 		pkt->pkt_resid = 0;
27136 
27137 		return (1);
27138 	}
27139 
27140 	/*
27141 	 * There's really only one possible return value from
27142 	 * sd_setup_next_rw_pkt which occurs when scsi_init_pkt
27143 	 * returns NULL.
27144 	 */
27145 	ASSERT(rval == SD_PKT_ALLOC_FAILURE);
27146 
27147 	bp->b_resid = bp->b_bcount;
27148 	bp->b_flags |= B_ERROR;
27149 
27150 	scsi_log(SD_DEVINFO(un), sd_label, CE_WARN,
27151 	    "Error setting up next portion of DMA transfer\n");
27152 
27153 	return (0);
27154 }
27155 
27156 /*
27157  *    Function: sd_panic_for_res_conflict
27158  *
27159  * Description: Call panic with a string formatted with "Reservation Conflict"
27160  *		and a human readable identifier indicating the SD instance
27161  *		that experienced the reservation conflict.
27162  *
27163  *   Arguments: un - pointer to the soft state struct for the instance.
27164  *
27165  *     Context: may execute in interrupt context.
27166  */
27167 
27168 #define	SD_RESV_CONFLICT_FMT_LEN 40
27169 void
27170 sd_panic_for_res_conflict(struct sd_lun *un)
27171 {
27172 	char panic_str[SD_RESV_CONFLICT_FMT_LEN+MAXPATHLEN];
27173 	char path_str[MAXPATHLEN];
27174 
27175 	(void) snprintf(panic_str, sizeof (panic_str),
27176 	    "Reservation Conflict\nDisk: %s",
27177 	    ddi_pathname(SD_DEVINFO(un), path_str));
27178 
27179 	panic(panic_str);
27180 }
27181 
27182 /*
27183  * Note: The following sd_faultinjection_ioctl( ) routines implement
27184  * driver support for handling fault injection for error analysis
27185  * causing faults in multiple layers of the driver.
27186  *
27187  */
27188 
27189 #ifdef SD_FAULT_INJECTION
27190 static uint_t   sd_fault_injection_on = 0;
27191 
27192 /*
27193  *    Function: sd_faultinjection_ioctl()
27194  *
27195  * Description: This routine is the driver entry point for handling
27196  *              faultinjection ioctls to inject errors into the
27197  *              layer model
27198  *
27199  *   Arguments: cmd	- the ioctl cmd received
27200  *		arg	- the arguments from user and returns
27201  */
27202 
27203 static void
27204 sd_faultinjection_ioctl(int cmd, intptr_t arg,  struct sd_lun *un) {
27205 
27206 	uint_t i;
27207 	uint_t rval;
27208 
27209 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl: entry\n");
27210 
27211 	mutex_enter(SD_MUTEX(un));
27212 
27213 	switch (cmd) {
27214 	case SDIOCRUN:
27215 		/* Allow pushed faults to be injected */
27216 		SD_INFO(SD_LOG_SDTEST, un,
27217 		    "sd_faultinjection_ioctl: Injecting Fault Run\n");
27218 
27219 		sd_fault_injection_on = 1;
27220 
27221 		SD_INFO(SD_LOG_IOERR, un,
27222 		    "sd_faultinjection_ioctl: run finished\n");
27223 		break;
27224 
27225 	case SDIOCSTART:
27226 		/* Start Injection Session */
27227 		SD_INFO(SD_LOG_SDTEST, un,
27228 		    "sd_faultinjection_ioctl: Injecting Fault Start\n");
27229 
27230 		sd_fault_injection_on = 0;
27231 		un->sd_injection_mask = 0xFFFFFFFF;
27232 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
27233 			un->sd_fi_fifo_pkt[i] = NULL;
27234 			un->sd_fi_fifo_xb[i] = NULL;
27235 			un->sd_fi_fifo_un[i] = NULL;
27236 			un->sd_fi_fifo_arq[i] = NULL;
27237 		}
27238 		un->sd_fi_fifo_start = 0;
27239 		un->sd_fi_fifo_end = 0;
27240 
27241 		mutex_enter(&(un->un_fi_mutex));
27242 		un->sd_fi_log[0] = '\0';
27243 		un->sd_fi_buf_len = 0;
27244 		mutex_exit(&(un->un_fi_mutex));
27245 
27246 		SD_INFO(SD_LOG_IOERR, un,
27247 		    "sd_faultinjection_ioctl: start finished\n");
27248 		break;
27249 
27250 	case SDIOCSTOP:
27251 		/* Stop Injection Session */
27252 		SD_INFO(SD_LOG_SDTEST, un,
27253 		    "sd_faultinjection_ioctl: Injecting Fault Stop\n");
27254 		sd_fault_injection_on = 0;
27255 		un->sd_injection_mask = 0x0;
27256 
27257 		/* Empty stray or unuseds structs from fifo */
27258 		for (i = 0; i < SD_FI_MAX_ERROR; i++) {
27259 			if (un->sd_fi_fifo_pkt[i] != NULL) {
27260 				kmem_free(un->sd_fi_fifo_pkt[i],
27261 				    sizeof (struct sd_fi_pkt));
27262 			}
27263 			if (un->sd_fi_fifo_xb[i] != NULL) {
27264 				kmem_free(un->sd_fi_fifo_xb[i],
27265 				    sizeof (struct sd_fi_xb));
27266 			}
27267 			if (un->sd_fi_fifo_un[i] != NULL) {
27268 				kmem_free(un->sd_fi_fifo_un[i],
27269 				    sizeof (struct sd_fi_un));
27270 			}
27271 			if (un->sd_fi_fifo_arq[i] != NULL) {
27272 				kmem_free(un->sd_fi_fifo_arq[i],
27273 				    sizeof (struct sd_fi_arq));
27274 			}
27275 			un->sd_fi_fifo_pkt[i] = NULL;
27276 			un->sd_fi_fifo_un[i] = NULL;
27277 			un->sd_fi_fifo_xb[i] = NULL;
27278 			un->sd_fi_fifo_arq[i] = NULL;
27279 		}
27280 		un->sd_fi_fifo_start = 0;
27281 		un->sd_fi_fifo_end = 0;
27282 
27283 		SD_INFO(SD_LOG_IOERR, un,
27284 		    "sd_faultinjection_ioctl: stop finished\n");
27285 		break;
27286 
27287 	case SDIOCINSERTPKT:
27288 		/* Store a packet struct to be pushed onto fifo */
27289 		SD_INFO(SD_LOG_SDTEST, un,
27290 		    "sd_faultinjection_ioctl: Injecting Fault Insert Pkt\n");
27291 
27292 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27293 
27294 		sd_fault_injection_on = 0;
27295 
27296 		/* No more that SD_FI_MAX_ERROR allowed in Queue */
27297 		if (un->sd_fi_fifo_pkt[i] != NULL) {
27298 			kmem_free(un->sd_fi_fifo_pkt[i],
27299 			    sizeof (struct sd_fi_pkt));
27300 		}
27301 		if (arg != NULL) {
27302 			un->sd_fi_fifo_pkt[i] =
27303 			    kmem_alloc(sizeof (struct sd_fi_pkt), KM_NOSLEEP);
27304 			if (un->sd_fi_fifo_pkt[i] == NULL) {
27305 				/* Alloc failed don't store anything */
27306 				break;
27307 			}
27308 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_pkt[i],
27309 			    sizeof (struct sd_fi_pkt), 0);
27310 			if (rval == -1) {
27311 				kmem_free(un->sd_fi_fifo_pkt[i],
27312 				    sizeof (struct sd_fi_pkt));
27313 				un->sd_fi_fifo_pkt[i] = NULL;
27314 			}
27315 		} else {
27316 			SD_INFO(SD_LOG_IOERR, un,
27317 			    "sd_faultinjection_ioctl: pkt null\n");
27318 		}
27319 		break;
27320 
27321 	case SDIOCINSERTXB:
27322 		/* Store a xb struct to be pushed onto fifo */
27323 		SD_INFO(SD_LOG_SDTEST, un,
27324 		    "sd_faultinjection_ioctl: Injecting Fault Insert XB\n");
27325 
27326 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27327 
27328 		sd_fault_injection_on = 0;
27329 
27330 		if (un->sd_fi_fifo_xb[i] != NULL) {
27331 			kmem_free(un->sd_fi_fifo_xb[i],
27332 			    sizeof (struct sd_fi_xb));
27333 			un->sd_fi_fifo_xb[i] = NULL;
27334 		}
27335 		if (arg != NULL) {
27336 			un->sd_fi_fifo_xb[i] =
27337 			    kmem_alloc(sizeof (struct sd_fi_xb), KM_NOSLEEP);
27338 			if (un->sd_fi_fifo_xb[i] == NULL) {
27339 				/* Alloc failed don't store anything */
27340 				break;
27341 			}
27342 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_xb[i],
27343 			    sizeof (struct sd_fi_xb), 0);
27344 
27345 			if (rval == -1) {
27346 				kmem_free(un->sd_fi_fifo_xb[i],
27347 				    sizeof (struct sd_fi_xb));
27348 				un->sd_fi_fifo_xb[i] = NULL;
27349 			}
27350 		} else {
27351 			SD_INFO(SD_LOG_IOERR, un,
27352 			    "sd_faultinjection_ioctl: xb null\n");
27353 		}
27354 		break;
27355 
27356 	case SDIOCINSERTUN:
27357 		/* Store a un struct to be pushed onto fifo */
27358 		SD_INFO(SD_LOG_SDTEST, un,
27359 		    "sd_faultinjection_ioctl: Injecting Fault Insert UN\n");
27360 
27361 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27362 
27363 		sd_fault_injection_on = 0;
27364 
27365 		if (un->sd_fi_fifo_un[i] != NULL) {
27366 			kmem_free(un->sd_fi_fifo_un[i],
27367 			    sizeof (struct sd_fi_un));
27368 			un->sd_fi_fifo_un[i] = NULL;
27369 		}
27370 		if (arg != NULL) {
27371 			un->sd_fi_fifo_un[i] =
27372 			    kmem_alloc(sizeof (struct sd_fi_un), KM_NOSLEEP);
27373 			if (un->sd_fi_fifo_un[i] == NULL) {
27374 				/* Alloc failed don't store anything */
27375 				break;
27376 			}
27377 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_un[i],
27378 			    sizeof (struct sd_fi_un), 0);
27379 			if (rval == -1) {
27380 				kmem_free(un->sd_fi_fifo_un[i],
27381 				    sizeof (struct sd_fi_un));
27382 				un->sd_fi_fifo_un[i] = NULL;
27383 			}
27384 
27385 		} else {
27386 			SD_INFO(SD_LOG_IOERR, un,
27387 			    "sd_faultinjection_ioctl: un null\n");
27388 		}
27389 
27390 		break;
27391 
27392 	case SDIOCINSERTARQ:
27393 		/* Store a arq struct to be pushed onto fifo */
27394 		SD_INFO(SD_LOG_SDTEST, un,
27395 		    "sd_faultinjection_ioctl: Injecting Fault Insert ARQ\n");
27396 		i = un->sd_fi_fifo_end % SD_FI_MAX_ERROR;
27397 
27398 		sd_fault_injection_on = 0;
27399 
27400 		if (un->sd_fi_fifo_arq[i] != NULL) {
27401 			kmem_free(un->sd_fi_fifo_arq[i],
27402 			    sizeof (struct sd_fi_arq));
27403 			un->sd_fi_fifo_arq[i] = NULL;
27404 		}
27405 		if (arg != NULL) {
27406 			un->sd_fi_fifo_arq[i] =
27407 			    kmem_alloc(sizeof (struct sd_fi_arq), KM_NOSLEEP);
27408 			if (un->sd_fi_fifo_arq[i] == NULL) {
27409 				/* Alloc failed don't store anything */
27410 				break;
27411 			}
27412 			rval = ddi_copyin((void *)arg, un->sd_fi_fifo_arq[i],
27413 			    sizeof (struct sd_fi_arq), 0);
27414 			if (rval == -1) {
27415 				kmem_free(un->sd_fi_fifo_arq[i],
27416 				    sizeof (struct sd_fi_arq));
27417 				un->sd_fi_fifo_arq[i] = NULL;
27418 			}
27419 
27420 		} else {
27421 			SD_INFO(SD_LOG_IOERR, un,
27422 			    "sd_faultinjection_ioctl: arq null\n");
27423 		}
27424 
27425 		break;
27426 
27427 	case SDIOCPUSH:
27428 		/* Push stored xb, pkt, un, and arq onto fifo */
27429 		sd_fault_injection_on = 0;
27430 
27431 		if (arg != NULL) {
27432 			rval = ddi_copyin((void *)arg, &i, sizeof (uint_t), 0);
27433 			if (rval != -1 &&
27434 			    un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
27435 				un->sd_fi_fifo_end += i;
27436 			}
27437 		} else {
27438 			SD_INFO(SD_LOG_IOERR, un,
27439 			    "sd_faultinjection_ioctl: push arg null\n");
27440 			if (un->sd_fi_fifo_end + i < SD_FI_MAX_ERROR) {
27441 				un->sd_fi_fifo_end++;
27442 			}
27443 		}
27444 		SD_INFO(SD_LOG_IOERR, un,
27445 		    "sd_faultinjection_ioctl: push to end=%d\n",
27446 		    un->sd_fi_fifo_end);
27447 		break;
27448 
27449 	case SDIOCRETRIEVE:
27450 		/* Return buffer of log from Injection session */
27451 		SD_INFO(SD_LOG_SDTEST, un,
27452 		    "sd_faultinjection_ioctl: Injecting Fault Retreive");
27453 
27454 		sd_fault_injection_on = 0;
27455 
27456 		mutex_enter(&(un->un_fi_mutex));
27457 		rval = ddi_copyout(un->sd_fi_log, (void *)arg,
27458 		    un->sd_fi_buf_len+1, 0);
27459 		mutex_exit(&(un->un_fi_mutex));
27460 
27461 		if (rval == -1) {
27462 			/*
27463 			 * arg is possibly invalid setting
27464 			 * it to NULL for return
27465 			 */
27466 			arg = NULL;
27467 		}
27468 		break;
27469 	}
27470 
27471 	mutex_exit(SD_MUTEX(un));
27472 	SD_TRACE(SD_LOG_IOERR, un, "sd_faultinjection_ioctl:"
27473 			    " exit\n");
27474 }
27475 
27476 
27477 /*
27478  *    Function: sd_injection_log()
27479  *
27480  * Description: This routine adds buff to the already existing injection log
27481  *              for retrieval via faultinjection_ioctl for use in fault
27482  *              detection and recovery
27483  *
27484  *   Arguments: buf - the string to add to the log
27485  */
27486 
27487 static void
27488 sd_injection_log(char *buf, struct sd_lun *un)
27489 {
27490 	uint_t len;
27491 
27492 	ASSERT(un != NULL);
27493 	ASSERT(buf != NULL);
27494 
27495 	mutex_enter(&(un->un_fi_mutex));
27496 
27497 	len = min(strlen(buf), 255);
27498 	/* Add logged value to Injection log to be returned later */
27499 	if (len + un->sd_fi_buf_len < SD_FI_MAX_BUF) {
27500 		uint_t	offset = strlen((char *)un->sd_fi_log);
27501 		char *destp = (char *)un->sd_fi_log + offset;
27502 		int i;
27503 		for (i = 0; i < len; i++) {
27504 			*destp++ = *buf++;
27505 		}
27506 		un->sd_fi_buf_len += len;
27507 		un->sd_fi_log[un->sd_fi_buf_len] = '\0';
27508 	}
27509 
27510 	mutex_exit(&(un->un_fi_mutex));
27511 }
27512 
27513 
27514 /*
27515  *    Function: sd_faultinjection()
27516  *
27517  * Description: This routine takes the pkt and changes its
27518  *		content based on error injection scenerio.
27519  *
27520  *   Arguments: pktp	- packet to be changed
27521  */
27522 
27523 static void
27524 sd_faultinjection(struct scsi_pkt *pktp)
27525 {
27526 	uint_t i;
27527 	struct sd_fi_pkt *fi_pkt;
27528 	struct sd_fi_xb *fi_xb;
27529 	struct sd_fi_un *fi_un;
27530 	struct sd_fi_arq *fi_arq;
27531 	struct buf *bp;
27532 	struct sd_xbuf *xb;
27533 	struct sd_lun *un;
27534 
27535 	ASSERT(pktp != NULL);
27536 
27537 	/* pull bp xb and un from pktp */
27538 	bp = (struct buf *)pktp->pkt_private;
27539 	xb = SD_GET_XBUF(bp);
27540 	un = SD_GET_UN(bp);
27541 
27542 	ASSERT(un != NULL);
27543 
27544 	mutex_enter(SD_MUTEX(un));
27545 
27546 	SD_TRACE(SD_LOG_SDTEST, un,
27547 	    "sd_faultinjection: entry Injection from sdintr\n");
27548 
27549 	/* if injection is off return */
27550 	if (sd_fault_injection_on == 0 ||
27551 	    un->sd_fi_fifo_start == un->sd_fi_fifo_end) {
27552 		mutex_exit(SD_MUTEX(un));
27553 		return;
27554 	}
27555 
27556 
27557 	/* take next set off fifo */
27558 	i = un->sd_fi_fifo_start % SD_FI_MAX_ERROR;
27559 
27560 	fi_pkt = un->sd_fi_fifo_pkt[i];
27561 	fi_xb = un->sd_fi_fifo_xb[i];
27562 	fi_un = un->sd_fi_fifo_un[i];
27563 	fi_arq = un->sd_fi_fifo_arq[i];
27564 
27565 
27566 	/* set variables accordingly */
27567 	/* set pkt if it was on fifo */
27568 	if (fi_pkt != NULL) {
27569 		SD_CONDSET(pktp, pkt, pkt_flags, "pkt_flags");
27570 		SD_CONDSET(*pktp, pkt, pkt_scbp, "pkt_scbp");
27571 		SD_CONDSET(*pktp, pkt, pkt_cdbp, "pkt_cdbp");
27572 		SD_CONDSET(pktp, pkt, pkt_state, "pkt_state");
27573 		SD_CONDSET(pktp, pkt, pkt_statistics, "pkt_statistics");
27574 		SD_CONDSET(pktp, pkt, pkt_reason, "pkt_reason");
27575 
27576 	}
27577 
27578 	/* set xb if it was on fifo */
27579 	if (fi_xb != NULL) {
27580 		SD_CONDSET(xb, xb, xb_blkno, "xb_blkno");
27581 		SD_CONDSET(xb, xb, xb_dma_resid, "xb_dma_resid");
27582 		SD_CONDSET(xb, xb, xb_retry_count, "xb_retry_count");
27583 		SD_CONDSET(xb, xb, xb_victim_retry_count,
27584 		    "xb_victim_retry_count");
27585 		SD_CONDSET(xb, xb, xb_sense_status, "xb_sense_status");
27586 		SD_CONDSET(xb, xb, xb_sense_state, "xb_sense_state");
27587 		SD_CONDSET(xb, xb, xb_sense_resid, "xb_sense_resid");
27588 
27589 		/* copy in block data from sense */
27590 		if (fi_xb->xb_sense_data[0] != -1) {
27591 			bcopy(fi_xb->xb_sense_data, xb->xb_sense_data,
27592 			    SENSE_LENGTH);
27593 		}
27594 
27595 		/* copy in extended sense codes */
27596 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_code,
27597 		    "es_code");
27598 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_key,
27599 		    "es_key");
27600 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb, es_add_code,
27601 		    "es_add_code");
27602 		SD_CONDSET(((struct scsi_extended_sense *)xb), xb,
27603 		    es_qual_code, "es_qual_code");
27604 	}
27605 
27606 	/* set un if it was on fifo */
27607 	if (fi_un != NULL) {
27608 		SD_CONDSET(un->un_sd->sd_inq, un, inq_rmb, "inq_rmb");
27609 		SD_CONDSET(un, un, un_ctype, "un_ctype");
27610 		SD_CONDSET(un, un, un_reset_retry_count,
27611 		    "un_reset_retry_count");
27612 		SD_CONDSET(un, un, un_reservation_type, "un_reservation_type");
27613 		SD_CONDSET(un, un, un_resvd_status, "un_resvd_status");
27614 		SD_CONDSET(un, un, un_f_arq_enabled, "un_f_arq_enabled");
27615 		SD_CONDSET(un, un, un_f_allow_bus_device_reset,
27616 		    "un_f_allow_bus_device_reset");
27617 		SD_CONDSET(un, un, un_f_opt_queueing, "un_f_opt_queueing");
27618 
27619 	}
27620 
27621 	/* copy in auto request sense if it was on fifo */
27622 	if (fi_arq != NULL) {
27623 		bcopy(fi_arq, pktp->pkt_scbp, sizeof (struct sd_fi_arq));
27624 	}
27625 
27626 	/* free structs */
27627 	if (un->sd_fi_fifo_pkt[i] != NULL) {
27628 		kmem_free(un->sd_fi_fifo_pkt[i], sizeof (struct sd_fi_pkt));
27629 	}
27630 	if (un->sd_fi_fifo_xb[i] != NULL) {
27631 		kmem_free(un->sd_fi_fifo_xb[i], sizeof (struct sd_fi_xb));
27632 	}
27633 	if (un->sd_fi_fifo_un[i] != NULL) {
27634 		kmem_free(un->sd_fi_fifo_un[i], sizeof (struct sd_fi_un));
27635 	}
27636 	if (un->sd_fi_fifo_arq[i] != NULL) {
27637 		kmem_free(un->sd_fi_fifo_arq[i], sizeof (struct sd_fi_arq));
27638 	}
27639 
27640 	/*
27641 	 * kmem_free does not gurantee to set to NULL
27642 	 * since we uses these to determine if we set
27643 	 * values or not lets confirm they are always
27644 	 * NULL after free
27645 	 */
27646 	un->sd_fi_fifo_pkt[i] = NULL;
27647 	un->sd_fi_fifo_un[i] = NULL;
27648 	un->sd_fi_fifo_xb[i] = NULL;
27649 	un->sd_fi_fifo_arq[i] = NULL;
27650 
27651 	un->sd_fi_fifo_start++;
27652 
27653 	mutex_exit(SD_MUTEX(un));
27654 
27655 	SD_TRACE(SD_LOG_SDTEST, un, "sd_faultinjection: exit\n");
27656 }
27657 
27658 #endif /* SD_FAULT_INJECTION */
27659 
27660 /*
27661  * This routine is invoked in sd_unit_attach(). Before calling it, the
27662  * properties in conf file should be processed already, and "hotpluggable"
27663  * property was processed also.
27664  *
27665  * The sd driver distinguishes 3 different type of devices: removable media,
27666  * non-removable media, and hotpluggable. Below the differences are defined:
27667  *
27668  * 1. Device ID
27669  *
27670  *     The device ID of a device is used to identify this device. Refer to
27671  *     ddi_devid_register(9F).
27672  *
27673  *     For a non-removable media disk device which can provide 0x80 or 0x83
27674  *     VPD page (refer to INQUIRY command of SCSI SPC specification), a unique
27675  *     device ID is created to identify this device. For other non-removable
27676  *     media devices, a default device ID is created only if this device has
27677  *     at least 2 alter cylinders. Otherwise, this device has no devid.
27678  *
27679  *     -------------------------------------------------------
27680  *     removable media   hotpluggable  | Can Have Device ID
27681  *     -------------------------------------------------------
27682  *         false             false     |     Yes
27683  *         false             true      |     Yes
27684  *         true                x       |     No
27685  *     ------------------------------------------------------
27686  *
27687  *
27688  * 2. SCSI group 4 commands
27689  *
27690  *     In SCSI specs, only some commands in group 4 command set can use
27691  *     8-byte addresses that can be used to access >2TB storage spaces.
27692  *     Other commands have no such capability. Without supporting group4,
27693  *     it is impossible to make full use of storage spaces of a disk with
27694  *     capacity larger than 2TB.
27695  *
27696  *     -----------------------------------------------
27697  *     removable media   hotpluggable   LP64  |  Group
27698  *     -----------------------------------------------
27699  *           false          false       false |   1
27700  *           false          false       true  |   4
27701  *           false          true        false |   1
27702  *           false          true        true  |   4
27703  *           true             x           x   |   5
27704  *     -----------------------------------------------
27705  *
27706  *
27707  * 3. Check for VTOC Label
27708  *
27709  *     If a direct-access disk has no EFI label, sd will check if it has a
27710  *     valid VTOC label. Now, sd also does that check for removable media
27711  *     and hotpluggable devices.
27712  *
27713  *     --------------------------------------------------------------
27714  *     Direct-Access   removable media    hotpluggable |  Check Label
27715  *     -------------------------------------------------------------
27716  *         false          false           false        |   No
27717  *         false          false           true         |   No
27718  *         false          true            false        |   Yes
27719  *         false          true            true         |   Yes
27720  *         true            x                x          |   Yes
27721  *     --------------------------------------------------------------
27722  *
27723  *
27724  * 4. Building default VTOC label
27725  *
27726  *     As section 3 says, sd checks if some kinds of devices have VTOC label.
27727  *     If those devices have no valid VTOC label, sd(7d) will attempt to
27728  *     create default VTOC for them. Currently sd creates default VTOC label
27729  *     for all devices on x86 platform (VTOC_16), but only for removable
27730  *     media devices on SPARC (VTOC_8).
27731  *
27732  *     -----------------------------------------------------------
27733  *       removable media hotpluggable platform   |   Default Label
27734  *     -----------------------------------------------------------
27735  *             false          false    sparc     |     No
27736  *             false          true      x86      |     Yes
27737  *             false          true     sparc     |     Yes
27738  *             true             x        x       |     Yes
27739  *     ----------------------------------------------------------
27740  *
27741  *
27742  * 5. Supported blocksizes of target devices
27743  *
27744  *     Sd supports non-512-byte blocksize for removable media devices only.
27745  *     For other devices, only 512-byte blocksize is supported. This may be
27746  *     changed in near future because some RAID devices require non-512-byte
27747  *     blocksize
27748  *
27749  *     -----------------------------------------------------------
27750  *     removable media    hotpluggable    | non-512-byte blocksize
27751  *     -----------------------------------------------------------
27752  *           false          false         |   No
27753  *           false          true          |   No
27754  *           true             x           |   Yes
27755  *     -----------------------------------------------------------
27756  *
27757  *
27758  * 6. Automatic mount & unmount
27759  *
27760  *     Sd(7d) driver provides DKIOCREMOVABLE ioctl. This ioctl is used to query
27761  *     if a device is removable media device. It return 1 for removable media
27762  *     devices, and 0 for others.
27763  *
27764  *     The automatic mounting subsystem should distinguish between the types
27765  *     of devices and apply automounting policies to each.
27766  *
27767  *
27768  * 7. fdisk partition management
27769  *
27770  *     Fdisk is traditional partition method on x86 platform. Sd(7d) driver
27771  *     just supports fdisk partitions on x86 platform. On sparc platform, sd
27772  *     doesn't support fdisk partitions at all. Note: pcfs(7fs) can recognize
27773  *     fdisk partitions on both x86 and SPARC platform.
27774  *
27775  *     -----------------------------------------------------------
27776  *       platform   removable media  USB/1394  |  fdisk supported
27777  *     -----------------------------------------------------------
27778  *        x86         X               X        |       true
27779  *     ------------------------------------------------------------
27780  *        sparc       X               X        |       false
27781  *     ------------------------------------------------------------
27782  *
27783  *
27784  * 8. MBOOT/MBR
27785  *
27786  *     Although sd(7d) doesn't support fdisk on SPARC platform, it does support
27787  *     read/write mboot for removable media devices on sparc platform.
27788  *
27789  *     -----------------------------------------------------------
27790  *       platform   removable media  USB/1394  |  mboot supported
27791  *     -----------------------------------------------------------
27792  *        x86         X               X        |       true
27793  *     ------------------------------------------------------------
27794  *        sparc      false           false     |       false
27795  *        sparc      false           true      |       true
27796  *        sparc      true            false     |       true
27797  *        sparc      true            true      |       true
27798  *     ------------------------------------------------------------
27799  *
27800  *
27801  * 9.  error handling during opening device
27802  *
27803  *     If failed to open a disk device, an errno is returned. For some kinds
27804  *     of errors, different errno is returned depending on if this device is
27805  *     a removable media device. This brings USB/1394 hard disks in line with
27806  *     expected hard disk behavior. It is not expected that this breaks any
27807  *     application.
27808  *
27809  *     ------------------------------------------------------
27810  *       removable media    hotpluggable   |  errno
27811  *     ------------------------------------------------------
27812  *             false          false        |   EIO
27813  *             false          true         |   EIO
27814  *             true             x          |   ENXIO
27815  *     ------------------------------------------------------
27816  *
27817  *
27818  * 11. ioctls: DKIOCEJECT, CDROMEJECT
27819  *
27820  *     These IOCTLs are applicable only to removable media devices.
27821  *
27822  *     -----------------------------------------------------------
27823  *       removable media    hotpluggable   |DKIOCEJECT, CDROMEJECT
27824  *     -----------------------------------------------------------
27825  *             false          false        |     No
27826  *             false          true         |     No
27827  *             true            x           |     Yes
27828  *     -----------------------------------------------------------
27829  *
27830  *
27831  * 12. Kstats for partitions
27832  *
27833  *     sd creates partition kstat for non-removable media devices. USB and
27834  *     Firewire hard disks now have partition kstats
27835  *
27836  *      ------------------------------------------------------
27837  *       removable media    hotpluggable   |   kstat
27838  *      ------------------------------------------------------
27839  *             false          false        |    Yes
27840  *             false          true         |    Yes
27841  *             true             x          |    No
27842  *       ------------------------------------------------------
27843  *
27844  *
27845  * 13. Removable media & hotpluggable properties
27846  *
27847  *     Sd driver creates a "removable-media" property for removable media
27848  *     devices. Parent nexus drivers create a "hotpluggable" property if
27849  *     it supports hotplugging.
27850  *
27851  *     ---------------------------------------------------------------------
27852  *     removable media   hotpluggable |  "removable-media"   " hotpluggable"
27853  *     ---------------------------------------------------------------------
27854  *       false            false       |    No                   No
27855  *       false            true        |    No                   Yes
27856  *       true             false       |    Yes                  No
27857  *       true             true        |    Yes                  Yes
27858  *     ---------------------------------------------------------------------
27859  *
27860  *
27861  * 14. Power Management
27862  *
27863  *     sd only power manages removable media devices or devices that support
27864  *     LOG_SENSE or have a "pm-capable" property  (PSARC/2002/250)
27865  *
27866  *     A parent nexus that supports hotplugging can also set "pm-capable"
27867  *     if the disk can be power managed.
27868  *
27869  *     ------------------------------------------------------------
27870  *       removable media hotpluggable pm-capable  |   power manage
27871  *     ------------------------------------------------------------
27872  *             false          false     false     |     No
27873  *             false          false     true      |     Yes
27874  *             false          true      false     |     No
27875  *             false          true      true      |     Yes
27876  *             true             x        x        |     Yes
27877  *     ------------------------------------------------------------
27878  *
27879  *      USB and firewire hard disks can now be power managed independently
27880  *      of the framebuffer
27881  *
27882  *
27883  * 15. Support for USB disks with capacity larger than 1TB
27884  *
27885  *     Currently, sd doesn't permit a fixed disk device with capacity
27886  *     larger than 1TB to be used in a 32-bit operating system environment.
27887  *     However, sd doesn't do that for removable media devices. Instead, it
27888  *     assumes that removable media devices cannot have a capacity larger
27889  *     than 1TB. Therefore, using those devices on 32-bit system is partially
27890  *     supported, which can cause some unexpected results.
27891  *
27892  *     ---------------------------------------------------------------------
27893  *       removable media    USB/1394 | Capacity > 1TB |   Used in 32-bit env
27894  *     ---------------------------------------------------------------------
27895  *             false          false  |   true         |     no
27896  *             false          true   |   true         |     no
27897  *             true           false  |   true         |     Yes
27898  *             true           true   |   true         |     Yes
27899  *     ---------------------------------------------------------------------
27900  *
27901  *
27902  * 16. Check write-protection at open time
27903  *
27904  *     When a removable media device is being opened for writing without NDELAY
27905  *     flag, sd will check if this device is writable. If attempting to open
27906  *     without NDELAY flag a write-protected device, this operation will abort.
27907  *
27908  *     ------------------------------------------------------------
27909  *       removable media    USB/1394   |   WP Check
27910  *     ------------------------------------------------------------
27911  *             false          false    |     No
27912  *             false          true     |     No
27913  *             true           false    |     Yes
27914  *             true           true     |     Yes
27915  *     ------------------------------------------------------------
27916  *
27917  *
27918  * 17. syslog when corrupted VTOC is encountered
27919  *
27920  *      Currently, if an invalid VTOC is encountered, sd only print syslog
27921  *      for fixed SCSI disks.
27922  *     ------------------------------------------------------------
27923  *       removable media    USB/1394   |   print syslog
27924  *     ------------------------------------------------------------
27925  *             false          false    |     Yes
27926  *             false          true     |     No
27927  *             true           false    |     No
27928  *             true           true     |     No
27929  *     ------------------------------------------------------------
27930  */
27931 static void
27932 sd_set_unit_attributes(struct sd_lun *un, dev_info_t *devi)
27933 {
27934 	int	pm_capable_prop;
27935 
27936 	ASSERT(un->un_sd);
27937 	ASSERT(un->un_sd->sd_inq);
27938 
27939 	/*
27940 	 * Enable SYNC CACHE support for all devices.
27941 	 */
27942 	un->un_f_sync_cache_supported = TRUE;
27943 
27944 	if (un->un_sd->sd_inq->inq_rmb) {
27945 		/*
27946 		 * The media of this device is removable. And for this kind
27947 		 * of devices, it is possible to change medium after opening
27948 		 * devices. Thus we should support this operation.
27949 		 */
27950 		un->un_f_has_removable_media = TRUE;
27951 
27952 		/*
27953 		 * support non-512-byte blocksize of removable media devices
27954 		 */
27955 		un->un_f_non_devbsize_supported = TRUE;
27956 
27957 		/*
27958 		 * Assume that all removable media devices support DOOR_LOCK
27959 		 */
27960 		un->un_f_doorlock_supported = TRUE;
27961 
27962 		/*
27963 		 * For a removable media device, it is possible to be opened
27964 		 * with NDELAY flag when there is no media in drive, in this
27965 		 * case we don't care if device is writable. But if without
27966 		 * NDELAY flag, we need to check if media is write-protected.
27967 		 */
27968 		un->un_f_chk_wp_open = TRUE;
27969 
27970 		/*
27971 		 * need to start a SCSI watch thread to monitor media state,
27972 		 * when media is being inserted or ejected, notify syseventd.
27973 		 */
27974 		un->un_f_monitor_media_state = TRUE;
27975 
27976 		/*
27977 		 * Some devices don't support START_STOP_UNIT command.
27978 		 * Therefore, we'd better check if a device supports it
27979 		 * before sending it.
27980 		 */
27981 		un->un_f_check_start_stop = TRUE;
27982 
27983 		/*
27984 		 * support eject media ioctl:
27985 		 *		FDEJECT, DKIOCEJECT, CDROMEJECT
27986 		 */
27987 		un->un_f_eject_media_supported = TRUE;
27988 
27989 		/*
27990 		 * Because many removable-media devices don't support
27991 		 * LOG_SENSE, we couldn't use this command to check if
27992 		 * a removable media device support power-management.
27993 		 * We assume that they support power-management via
27994 		 * START_STOP_UNIT command and can be spun up and down
27995 		 * without limitations.
27996 		 */
27997 		un->un_f_pm_supported = TRUE;
27998 
27999 		/*
28000 		 * Need to create a zero length (Boolean) property
28001 		 * removable-media for the removable media devices.
28002 		 * Note that the return value of the property is not being
28003 		 * checked, since if unable to create the property
28004 		 * then do not want the attach to fail altogether. Consistent
28005 		 * with other property creation in attach.
28006 		 */
28007 		(void) ddi_prop_create(DDI_DEV_T_NONE, devi,
28008 		    DDI_PROP_CANSLEEP, "removable-media", NULL, 0);
28009 
28010 	} else {
28011 		/*
28012 		 * create device ID for device
28013 		 */
28014 		un->un_f_devid_supported = TRUE;
28015 
28016 		/*
28017 		 * Spin up non-removable-media devices once it is attached
28018 		 */
28019 		un->un_f_attach_spinup = TRUE;
28020 
28021 		/*
28022 		 * According to SCSI specification, Sense data has two kinds of
28023 		 * format: fixed format, and descriptor format. At present, we
28024 		 * don't support descriptor format sense data for removable
28025 		 * media.
28026 		 */
28027 		if (SD_INQUIRY(un)->inq_dtype == DTYPE_DIRECT) {
28028 			un->un_f_descr_format_supported = TRUE;
28029 		}
28030 
28031 		/*
28032 		 * kstats are created only for non-removable media devices.
28033 		 *
28034 		 * Set this in sd.conf to 0 in order to disable kstats.  The
28035 		 * default is 1, so they are enabled by default.
28036 		 */
28037 		un->un_f_pkstats_enabled = (ddi_prop_get_int(DDI_DEV_T_ANY,
28038 		    SD_DEVINFO(un), DDI_PROP_DONTPASS,
28039 		    "enable-partition-kstats", 1));
28040 
28041 		/*
28042 		 * Check if HBA has set the "pm-capable" property.
28043 		 * If "pm-capable" exists and is non-zero then we can
28044 		 * power manage the device without checking the start/stop
28045 		 * cycle count log sense page.
28046 		 *
28047 		 * If "pm-capable" exists and is SD_PM_CAPABLE_FALSE (0)
28048 		 * then we should not power manage the device.
28049 		 *
28050 		 * If "pm-capable" doesn't exist then pm_capable_prop will
28051 		 * be set to SD_PM_CAPABLE_UNDEFINED (-1).  In this case,
28052 		 * sd will check the start/stop cycle count log sense page
28053 		 * and power manage the device if the cycle count limit has
28054 		 * not been exceeded.
28055 		 */
28056 		pm_capable_prop = ddi_prop_get_int(DDI_DEV_T_ANY, devi,
28057 		    DDI_PROP_DONTPASS, "pm-capable", SD_PM_CAPABLE_UNDEFINED);
28058 		if (pm_capable_prop == SD_PM_CAPABLE_UNDEFINED) {
28059 			un->un_f_log_sense_supported = TRUE;
28060 		} else {
28061 			/*
28062 			 * pm-capable property exists.
28063 			 *
28064 			 * Convert "TRUE" values for pm_capable_prop to
28065 			 * SD_PM_CAPABLE_TRUE (1) to make it easier to check
28066 			 * later. "TRUE" values are any values except
28067 			 * SD_PM_CAPABLE_FALSE (0) and
28068 			 * SD_PM_CAPABLE_UNDEFINED (-1)
28069 			 */
28070 			if (pm_capable_prop == SD_PM_CAPABLE_FALSE) {
28071 				un->un_f_log_sense_supported = FALSE;
28072 			} else {
28073 				un->un_f_pm_supported = TRUE;
28074 			}
28075 
28076 			SD_INFO(SD_LOG_ATTACH_DETACH, un,
28077 			    "sd_unit_attach: un:0x%p pm-capable "
28078 			    "property set to %d.\n", un, un->un_f_pm_supported);
28079 		}
28080 	}
28081 
28082 	if (un->un_f_is_hotpluggable) {
28083 
28084 		/*
28085 		 * Have to watch hotpluggable devices as well, since
28086 		 * that's the only way for userland applications to
28087 		 * detect hot removal while device is busy/mounted.
28088 		 */
28089 		un->un_f_monitor_media_state = TRUE;
28090 
28091 		un->un_f_check_start_stop = TRUE;
28092 
28093 	}
28094 }
28095 
28096 /*
28097  * sd_tg_rdwr:
28098  * Provides rdwr access for cmlb via sd_tgops. The start_block is
28099  * in sys block size, req_length in bytes.
28100  *
28101  */
28102 static int
28103 sd_tg_rdwr(dev_info_t *devi, uchar_t cmd, void *bufaddr,
28104     diskaddr_t start_block, size_t reqlength, void *tg_cookie)
28105 {
28106 	struct sd_lun *un;
28107 	int path_flag = (int)(uintptr_t)tg_cookie;
28108 	char *dkl = NULL;
28109 	diskaddr_t real_addr = start_block;
28110 	diskaddr_t first_byte, end_block;
28111 
28112 	size_t	buffer_size = reqlength;
28113 	int rval;
28114 	diskaddr_t	cap;
28115 	uint32_t	lbasize;
28116 
28117 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
28118 	if (un == NULL)
28119 		return (ENXIO);
28120 
28121 	if (cmd != TG_READ && cmd != TG_WRITE)
28122 		return (EINVAL);
28123 
28124 	mutex_enter(SD_MUTEX(un));
28125 	if (un->un_f_tgt_blocksize_is_valid == FALSE) {
28126 		mutex_exit(SD_MUTEX(un));
28127 		rval = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
28128 		    &lbasize, path_flag);
28129 		if (rval != 0)
28130 			return (rval);
28131 		mutex_enter(SD_MUTEX(un));
28132 		sd_update_block_info(un, lbasize, cap);
28133 		if ((un->un_f_tgt_blocksize_is_valid == FALSE)) {
28134 			mutex_exit(SD_MUTEX(un));
28135 			return (EIO);
28136 		}
28137 	}
28138 
28139 	if (NOT_DEVBSIZE(un)) {
28140 		/*
28141 		 * sys_blocksize != tgt_blocksize, need to re-adjust
28142 		 * blkno and save the index to beginning of dk_label
28143 		 */
28144 		first_byte  = SD_SYSBLOCKS2BYTES(un, start_block);
28145 		real_addr = first_byte / un->un_tgt_blocksize;
28146 
28147 		end_block = (first_byte + reqlength +
28148 		    un->un_tgt_blocksize - 1) / un->un_tgt_blocksize;
28149 
28150 		/* round up buffer size to multiple of target block size */
28151 		buffer_size = (end_block - real_addr) * un->un_tgt_blocksize;
28152 
28153 		SD_TRACE(SD_LOG_IO_PARTITION, un, "sd_tg_rdwr",
28154 		    "label_addr: 0x%x allocation size: 0x%x\n",
28155 		    real_addr, buffer_size);
28156 
28157 		if (((first_byte % un->un_tgt_blocksize) != 0) ||
28158 		    (reqlength % un->un_tgt_blocksize) != 0)
28159 			/* the request is not aligned */
28160 			dkl = kmem_zalloc(buffer_size, KM_SLEEP);
28161 	}
28162 
28163 	/*
28164 	 * The MMC standard allows READ CAPACITY to be
28165 	 * inaccurate by a bounded amount (in the interest of
28166 	 * response latency).  As a result, failed READs are
28167 	 * commonplace (due to the reading of metadata and not
28168 	 * data). Depending on the per-Vendor/drive Sense data,
28169 	 * the failed READ can cause many (unnecessary) retries.
28170 	 */
28171 
28172 	if (ISCD(un) && (cmd == TG_READ) &&
28173 	    (un->un_f_blockcount_is_valid == TRUE) &&
28174 	    ((start_block == (un->un_blockcount - 1))||
28175 	    (start_block == (un->un_blockcount - 2)))) {
28176 			path_flag = SD_PATH_DIRECT_PRIORITY;
28177 	}
28178 
28179 	mutex_exit(SD_MUTEX(un));
28180 	if (cmd == TG_READ) {
28181 		rval = sd_send_scsi_READ(un, (dkl != NULL)? dkl: bufaddr,
28182 		    buffer_size, real_addr, path_flag);
28183 		if (dkl != NULL)
28184 			bcopy(dkl + SD_TGTBYTEOFFSET(un, start_block,
28185 			    real_addr), bufaddr, reqlength);
28186 	} else {
28187 		if (dkl) {
28188 			rval = sd_send_scsi_READ(un, dkl, buffer_size,
28189 			    real_addr, path_flag);
28190 			if (rval) {
28191 				kmem_free(dkl, buffer_size);
28192 				return (rval);
28193 			}
28194 			bcopy(bufaddr, dkl + SD_TGTBYTEOFFSET(un, start_block,
28195 			    real_addr), reqlength);
28196 		}
28197 		rval = sd_send_scsi_WRITE(un, (dkl != NULL)? dkl: bufaddr,
28198 		    buffer_size, real_addr, path_flag);
28199 	}
28200 
28201 	if (dkl != NULL)
28202 		kmem_free(dkl, buffer_size);
28203 
28204 	return (rval);
28205 }
28206 
28207 
28208 static int
28209 sd_tg_getinfo(dev_info_t *devi, int cmd, void *arg, void *tg_cookie)
28210 {
28211 
28212 	struct sd_lun *un;
28213 	diskaddr_t	cap;
28214 	uint32_t	lbasize;
28215 	int		path_flag = (int)(uintptr_t)tg_cookie;
28216 	int		ret = 0;
28217 
28218 	un = ddi_get_soft_state(sd_state, ddi_get_instance(devi));
28219 	if (un == NULL)
28220 		return (ENXIO);
28221 
28222 	switch (cmd) {
28223 	case TG_GETPHYGEOM:
28224 	case TG_GETVIRTGEOM:
28225 	case TG_GETCAPACITY:
28226 	case  TG_GETBLOCKSIZE:
28227 		mutex_enter(SD_MUTEX(un));
28228 
28229 		if ((un->un_f_blockcount_is_valid == TRUE) &&
28230 		    (un->un_f_tgt_blocksize_is_valid == TRUE)) {
28231 			cap = un->un_blockcount;
28232 			lbasize = un->un_tgt_blocksize;
28233 			mutex_exit(SD_MUTEX(un));
28234 		} else {
28235 			mutex_exit(SD_MUTEX(un));
28236 			ret = sd_send_scsi_READ_CAPACITY(un, (uint64_t *)&cap,
28237 			    &lbasize, path_flag);
28238 			if (ret != 0)
28239 				return (ret);
28240 			mutex_enter(SD_MUTEX(un));
28241 			sd_update_block_info(un, lbasize, cap);
28242 			if ((un->un_f_blockcount_is_valid == FALSE) ||
28243 			    (un->un_f_tgt_blocksize_is_valid == FALSE)) {
28244 				mutex_exit(SD_MUTEX(un));
28245 				return (EIO);
28246 			}
28247 			mutex_exit(SD_MUTEX(un));
28248 		}
28249 
28250 		if (cmd == TG_GETCAPACITY) {
28251 			*(diskaddr_t *)arg = cap;
28252 			return (0);
28253 		}
28254 
28255 		if (cmd == TG_GETBLOCKSIZE) {
28256 			*(uint32_t *)arg = lbasize;
28257 			return (0);
28258 		}
28259 
28260 		if (cmd == TG_GETPHYGEOM)
28261 			ret = sd_get_physical_geometry(un, (cmlb_geom_t *)arg,
28262 			    cap, lbasize, path_flag);
28263 		else
28264 			/* TG_GETVIRTGEOM */
28265 			ret = sd_get_virtual_geometry(un,
28266 			    (cmlb_geom_t *)arg, cap, lbasize);
28267 
28268 		return (ret);
28269 
28270 	case TG_GETATTR:
28271 		mutex_enter(SD_MUTEX(un));
28272 		((tg_attribute_t *)arg)->media_is_writable =
28273 		    un->un_f_mmc_writable_media;
28274 		mutex_exit(SD_MUTEX(un));
28275 		return (0);
28276 	default:
28277 		return (ENOTTY);
28278 
28279 	}
28280 
28281 }
28282